Spaces:
Running

axeronis commited on
Commit
b38cc4d
·
1 Parent(s): eb11f98

feat: booking system overhaul - remove debounce, day/week/month views, resource filter, drag-n-drop, Telegram notifications

Browse files
backend/app/api/bookings.py CHANGED
@@ -17,6 +17,30 @@ logger = get_logger(__name__)
17
 
18
  router = APIRouter(prefix="/bookings", tags=["Bookings"])
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  # -----------------------------------------------------------------------------
21
  # APPOINTMENTS
22
  # -----------------------------------------------------------------------------
@@ -170,6 +194,9 @@ from pydantic import BaseModel
170
  class AppointmentUpdateRequest(BaseModel):
171
  status: Optional[str] = None
172
  notes: Optional[str] = None
 
 
 
173
 
174
  @router.patch("/{appointment_id}")
175
  async def update_appointment(
@@ -178,11 +205,20 @@ async def update_appointment(
178
  session: AsyncSession = Depends(get_session),
179
  current_user: User = Depends(get_current_user)
180
  ):
181
- """Update appointment status or notes."""
 
 
 
 
 
 
182
  appointment = await session.get(Appointment, appointment_id)
183
  if not appointment or appointment.tenant_id != current_user.tenant_id:
184
  raise HTTPException(status_code=404, detail="Appointment not found")
185
 
 
 
 
186
  if update_data.status:
187
  try:
188
  appointment.status = AppointmentStatus(update_data.status)
@@ -192,10 +228,61 @@ async def update_appointment(
192
  if update_data.notes is not None:
193
  appointment.notes = update_data.notes
194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  session.add(appointment)
196
  await session.commit()
197
  await session.refresh(appointment)
198
- return appointment
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
 
200
  # -----------------------------------------------------------------------------
201
  # SERVICES
 
17
 
18
  router = APIRouter(prefix="/bookings", tags=["Bookings"])
19
 
20
+ # -----------------------------------------------------------------------------
21
+ # BOOKING SETTINGS
22
+ # -----------------------------------------------------------------------------
23
+
24
+ @router.get("/settings")
25
+ async def get_booking_settings(
26
+ session: AsyncSession = Depends(get_session),
27
+ current_user: User = Depends(get_current_user)
28
+ ):
29
+ """Get company booking settings for the tenant."""
30
+ tenant = await session.get(Tenant, current_user.tenant_id)
31
+ if not tenant:
32
+ raise HTTPException(status_code=404, detail="Tenant not found")
33
+
34
+ booking_settings = tenant.booking_settings or {}
35
+
36
+ return {
37
+ "working_hours": booking_settings.get("working_hours", {"start": "09:00", "end": "18:00"}),
38
+ "working_days": booking_settings.get("working_days", [0, 1, 2, 3, 4]), # Mon-Fri
39
+ "slot_duration": booking_settings.get("slot_duration", 30),
40
+ "timezone": tenant.timezone or "Asia/Bishkek"
41
+ }
42
+
43
+
44
  # -----------------------------------------------------------------------------
45
  # APPOINTMENTS
46
  # -----------------------------------------------------------------------------
 
194
  class AppointmentUpdateRequest(BaseModel):
195
  status: Optional[str] = None
196
  notes: Optional[str] = None
197
+ start_time: Optional[datetime] = None
198
+ end_time: Optional[datetime] = None
199
+ resource_id: Optional[UUID] = None
200
 
201
  @router.patch("/{appointment_id}")
202
  async def update_appointment(
 
205
  session: AsyncSession = Depends(get_session),
206
  current_user: User = Depends(get_current_user)
207
  ):
208
+ """Update appointment status, notes, time or resource.
209
+
210
+ Sends Telegram notification to client if time is changed.
211
+ """
212
+ from app.models.booking import Resource
213
+ from app.models.lead import Lead
214
+
215
  appointment = await session.get(Appointment, appointment_id)
216
  if not appointment or appointment.tenant_id != current_user.tenant_id:
217
  raise HTTPException(status_code=404, detail="Appointment not found")
218
 
219
+ old_start_time = appointment.start_time
220
+ time_changed = False
221
+
222
  if update_data.status:
223
  try:
224
  appointment.status = AppointmentStatus(update_data.status)
 
228
  if update_data.notes is not None:
229
  appointment.notes = update_data.notes
230
 
231
+ if update_data.start_time is not None:
232
+ if update_data.start_time != old_start_time:
233
+ time_changed = True
234
+ appointment.start_time = update_data.start_time
235
+
236
+ if update_data.end_time is not None:
237
+ appointment.end_time = update_data.end_time
238
+
239
+ if update_data.resource_id is not None:
240
+ # Verify resource exists and belongs to tenant
241
+ resource = await session.get(Resource, update_data.resource_id)
242
+ if resource and resource.tenant_id == current_user.tenant_id:
243
+ appointment.resource_id = update_data.resource_id
244
+
245
  session.add(appointment)
246
  await session.commit()
247
  await session.refresh(appointment)
248
+
249
+ # Send Telegram notification if time changed
250
+ if time_changed and appointment.lead_id:
251
+ try:
252
+ lead = await session.get(Lead, appointment.lead_id)
253
+ tenant = await session.get(Tenant, current_user.tenant_id)
254
+
255
+ if lead and lead.telegram_id and tenant and tenant.telegram_bot_token:
256
+ import httpx
257
+
258
+ # Format times for message
259
+ old_time_str = old_start_time.strftime("%d.%m в %H:%M") if old_start_time else "неизвестно"
260
+ new_time_str = appointment.start_time.strftime("%d.%m в %H:%M") if appointment.start_time else "неизвестно"
261
+
262
+ message = f"📅 Ваша запись перенесена!\n\n❌ Было: {old_time_str}\n✅ Стало: {new_time_str}\n\nЕсли это время вам не подходит, напишите нам."
263
+
264
+ async with httpx.AsyncClient() as client:
265
+ await client.post(
266
+ f"https://api.telegram.org/bot{tenant.telegram_bot_token}/sendMessage",
267
+ json={
268
+ "chat_id": lead.telegram_id,
269
+ "text": message
270
+ },
271
+ timeout=10.0
272
+ )
273
+ logger.info(f"📱 Sent reschedule notification to client {lead.telegram_id}")
274
+ except Exception as e:
275
+ logger.error(f"Failed to send reschedule notification: {e}")
276
+
277
+ return {
278
+ "id": str(appointment.id),
279
+ "start_time": appointment.start_time.isoformat() if appointment.start_time else None,
280
+ "end_time": appointment.end_time.isoformat() if appointment.end_time else None,
281
+ "status": appointment.status.value if appointment.status else None,
282
+ "resource_id": str(appointment.resource_id) if appointment.resource_id else None,
283
+ "ok": True
284
+ }
285
+
286
 
287
  # -----------------------------------------------------------------------------
288
  # SERVICES
backend/app/api/webhook.py CHANGED
@@ -1096,13 +1096,9 @@ async def process_ai_response_background(
1096
  )
1097
  return
1098
 
1099
- # TASK 1: Add 2-second debouncing delay (reduced from 4s for faster response)
1100
- # This gives the user time to finish typing multiple messages
1101
- logger.info(
1102
- "⏳ Starting 2-second debounce delay...",
1103
- lead_id=str(lead_id)
1104
- )
1105
- await asyncio.sleep(2)
1106
 
1107
  async with async_session_maker() as session:
1108
  try:
 
1096
  )
1097
  return
1098
 
1099
+ # NOTE: Debounce removed for faster AI response
1100
+ # Message batching still works via the check on lines 1176-1202
1101
+ # which collects all user messages since last AI response
 
 
 
 
1102
 
1103
  async with async_session_maker() as session:
1104
  try:
frontend/app/appointments/page.tsx CHANGED
@@ -1,19 +1,51 @@
1
  'use client'
2
 
3
- import { useState, useMemo } from 'react'
4
  import { useQuery, useQueryClient } from '@tanstack/react-query'
5
  import { bookingsApi, api } from '@/lib/api'
6
- import { CalendarView } from '@/components/bookings/CalendarView'
7
  import { AppointmentDetails } from '@/components/bookings/AppointmentDetails'
8
- import { Plus, Settings, Calendar as CalendarIcon, Loader2, X, Users, Clock, TrendingUp } from 'lucide-react'
9
  import Link from 'next/link'
10
- import { isSameDay, startOfWeek, endOfWeek, startOfMonth, endOfMonth, isWithinInterval } from 'date-fns'
 
11
  import { useAuth } from '@/contexts/AuthContext'
12
  import { motion, AnimatePresence } from 'framer-motion'
13
  import { CreateAppointmentModal } from '@/components/bookings/CreateAppointmentModal'
 
14
 
15
- // Stats calculation helper
16
- function calculateStats(appointments: any[]) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  const now = new Date()
18
  const weekStart = startOfWeek(now, { weekStartsOn: 1 })
19
  const weekEnd = endOfWeek(now, { weekStartsOn: 1 })
@@ -40,11 +72,18 @@ function calculateStats(appointments: any[]) {
40
  export default function AppointmentsPage() {
41
  const { user, isLoading: authLoading } = useAuth()
42
  const queryClient = useQueryClient()
43
- const [selectedDate, setSelectedDate] = useState<Date>(new Date())
44
- const [selectedAppointment, setSelectedAppointment] = useState<any>(null)
 
 
 
 
45
  const [showCreateModal, setShowCreateModal] = useState(false)
46
 
47
- // Fetch tenant settings (booking_settings)
 
 
 
48
  const { data: tenantData } = useQuery({
49
  queryKey: ['tenant-settings', user?.tenant_id],
50
  queryFn: async () => {
@@ -52,8 +91,6 @@ export default function AppointmentsPage() {
52
  return res.data
53
  },
54
  enabled: !!user && !authLoading,
55
- staleTime: 0,
56
- refetchOnMount: 'always',
57
  })
58
 
59
  // Fetch services
@@ -63,15 +100,15 @@ export default function AppointmentsPage() {
63
  enabled: !!user && !authLoading,
64
  })
65
 
66
- // Fetch resources (masters)
67
- const { data: resources = [] } = useQuery({
68
  queryKey: ['booking-resources', user?.tenant_id],
69
  queryFn: () => bookingsApi.getResources(),
70
  enabled: !!user && !authLoading,
71
  })
72
 
73
- // React Query for appointments
74
- const { data: appointments = [], isLoading } = useQuery({
75
  queryKey: ['appointments', user?.tenant_id],
76
  queryFn: () => bookingsApi.getAppointments(),
77
  enabled: !!user && !authLoading,
@@ -79,47 +116,160 @@ export default function AppointmentsPage() {
79
  refetchOnMount: 'always',
80
  })
81
 
82
- // Extract booking settings
83
  const bookingSettings = tenantData?.booking_settings || {
84
- working_days: ['mon', 'tue', 'wed', 'thu', 'fri'],
85
  working_hours: { start: '09:00', end: '18:00' },
86
  slot_duration: 30,
87
- timezone: 'Europe/Moscow'
88
  }
89
 
90
  // Calculate stats
91
  const stats = useMemo(() => calculateStats(appointments), [appointments])
92
 
93
- const handleDateSelect = (date: Date) => {
94
- setSelectedDate(date)
95
- }
 
 
 
 
96
 
97
- const handleCloseDetails = () => {
98
- setSelectedAppointment(null)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  }
100
 
101
- const handleDelete = (appointmentId: string) => {
102
- queryClient.invalidateQueries({ queryKey: ['appointments'] })
 
103
  setSelectedAppointment(null)
104
  }
105
 
106
- const handleStatusChange = (appointmentId: string, newStatus: string) => {
107
- queryClient.invalidateQueries({ queryKey: ['appointments'] })
108
- if (selectedAppointment?.id === appointmentId) {
109
- setSelectedAppointment({ ...selectedAppointment, status: newStatus })
 
 
 
 
 
110
  }
111
  }
112
 
113
- const handleCreateSuccess = () => {
114
- setShowCreateModal(false)
115
- queryClient.invalidateQueries({ queryKey: ['appointments'] })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  }
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  return (
119
  <div className="min-h-screen p-3 md:p-6 lg:p-10 font-['Inter']">
120
- <div className="max-w-[1600px] mx-auto min-h-[calc(100vh-24px)] md:h-[calc(100vh-80px)] flex flex-col">
121
 
122
- {/* Header with Stats */}
123
  <div className="flex flex-col gap-4 mb-4 md:mb-6 flex-shrink-0">
124
  {/* Title Row */}
125
  <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
@@ -128,7 +278,7 @@ export default function AppointmentsPage() {
128
  <CalendarIcon className="w-5 h-5 md:w-6 md:h-6 text-indigo-400" />
129
  </div>
130
  <div>
131
- <h1 className="text-xl md:text-3xl font-bold text-white tracking-tight">Календарь</h1>
132
  <div className="flex items-center gap-2 text-xs md:text-sm text-slate-400 mt-0.5 md:mt-1">
133
  <span className="w-1.5 h-1.5 md:w-2 md:h-2 rounded-full bg-emerald-500"></span>
134
  <span>Онлайн запись активна</span>
@@ -181,41 +331,244 @@ export default function AppointmentsPage() {
181
  </div>
182
  </div>
183
 
184
- {/* Content Grid */}
185
- <div className="flex-1 grid grid-cols-1 lg:grid-cols-12 gap-4 md:gap-6 min-h-0">
186
- {/* Left: Main Calendar */}
187
- <div className="lg:col-span-8 h-full flex flex-col min-h-0">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  {isLoading ? (
189
- <div className="flex-1 flex items-center justify-center bg-surface-elevated border border-white/5 rounded-xl md:rounded-3xl min-h-[400px]">
190
- <Loader2 className="w-8 h-8 md:w-10 md:h-10 animate-spin text-indigo-500" />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  </div>
192
  ) : (
193
- <CalendarView
194
- appointments={appointments}
195
- selectedDate={selectedDate}
196
- onSelectDate={handleDateSelect}
197
- onSelectAppointment={setSelectedAppointment}
198
- workingDays={bookingSettings.working_days}
199
- workingHours={bookingSettings.working_hours}
200
- resources={resources}
201
- timezone={tenantData?.timezone || 'Asia/Bishkek'}
202
- region={tenantData?.region || 'kg'}
203
- />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  )}
205
  </div>
206
 
207
- {/* Right: Details Panel */}
208
- <div className="hidden lg:block lg:col-span-4 h-full min-h-0">
209
  <AppointmentDetails
210
  appointment={selectedAppointment}
211
- onClose={handleCloseDetails}
212
  onDelete={handleDelete}
213
  onStatusChange={handleStatusChange}
214
  />
215
  </div>
216
  </div>
217
 
218
- {/* Mobile: Appointment Details Modal */}
219
  <AnimatePresence>
220
  {selectedAppointment && (
221
  <motion.div
@@ -223,7 +576,7 @@ export default function AppointmentsPage() {
223
  animate={{ opacity: 1 }}
224
  exit={{ opacity: 0 }}
225
  className="lg:hidden fixed inset-0 z-50 bg-black/60 backdrop-blur-sm"
226
- onClick={handleCloseDetails}
227
  >
228
  <motion.div
229
  initial={{ y: '100%' }}
@@ -234,7 +587,7 @@ export default function AppointmentsPage() {
234
  onClick={(e) => e.stopPropagation()}
235
  >
236
  <div className="sticky top-0 bg-[#1E1F2E] pt-3 pb-2 px-4 flex items-center gap-3 z-10 border-b border-white/5">
237
- <button onClick={handleCloseDetails} className="p-2 hover:bg-white/10 rounded-lg">
238
  <X className="w-5 h-5 text-slate-400" />
239
  </button>
240
  <span className="font-semibold text-white">Детали записи</span>
@@ -242,7 +595,7 @@ export default function AppointmentsPage() {
242
  <div className="bg-[#1E1F2E] pb-20">
243
  <AppointmentDetails
244
  appointment={selectedAppointment}
245
- onClose={handleCloseDetails}
246
  onDelete={handleDelete}
247
  onStatusChange={handleStatusChange}
248
  />
@@ -252,12 +605,15 @@ export default function AppointmentsPage() {
252
  )}
253
  </AnimatePresence>
254
 
255
- {/* Create Appointment Modal */}
256
  <AnimatePresence>
257
  {showCreateModal && (
258
  <CreateAppointmentModal
259
  onClose={() => setShowCreateModal(false)}
260
- onSuccess={handleCreateSuccess}
 
 
 
261
  services={services}
262
  bookingSettings={bookingSettings}
263
  />
 
1
  'use client'
2
 
3
+ import { useState, useMemo, useCallback } from 'react'
4
  import { useQuery, useQueryClient } from '@tanstack/react-query'
5
  import { bookingsApi, api } from '@/lib/api'
 
6
  import { AppointmentDetails } from '@/components/bookings/AppointmentDetails'
7
+ import { Plus, Settings, Calendar as CalendarIcon, Loader2, X, Users, Clock, TrendingUp, ChevronLeft, ChevronRight, LayoutGrid, LayoutList, Check, GripVertical } from 'lucide-react'
8
  import Link from 'next/link'
9
+ import { format, addDays, addWeeks, addMonths, startOfWeek, endOfWeek, startOfMonth, endOfMonth, isWithinInterval, isSameDay, isSameMonth, eachDayOfInterval, getDay, startOfDay, differenceInMinutes, parseISO } from 'date-fns'
10
+ import { ru } from 'date-fns/locale'
11
  import { useAuth } from '@/contexts/AuthContext'
12
  import { motion, AnimatePresence } from 'framer-motion'
13
  import { CreateAppointmentModal } from '@/components/bookings/CreateAppointmentModal'
14
+ import { cn } from '@/lib/utils'
15
 
16
+ type ViewMode = 'day' | 'week' | 'month'
17
+
18
+ interface Resource {
19
+ id: string
20
+ name: string
21
+ color?: string
22
+ }
23
+
24
+ interface Appointment {
25
+ id: string
26
+ start_time: string
27
+ end_time: string
28
+ status: string
29
+ lead_id: string
30
+ lead_name?: string
31
+ resource_id?: string
32
+ resource_name?: string
33
+ service_name?: string
34
+ notes?: string
35
+ }
36
+
37
+ // Color palette for resources
38
+ const RESOURCE_COLORS = [
39
+ 'bg-indigo-500', 'bg-emerald-500', 'bg-amber-500', 'bg-rose-500',
40
+ 'bg-cyan-500', 'bg-purple-500', 'bg-orange-500', 'bg-teal-500'
41
+ ]
42
+
43
+ function getResourceColor(index: number) {
44
+ return RESOURCE_COLORS[index % RESOURCE_COLORS.length]
45
+ }
46
+
47
+ // Stats calculation
48
+ function calculateStats(appointments: Appointment[]) {
49
  const now = new Date()
50
  const weekStart = startOfWeek(now, { weekStartsOn: 1 })
51
  const weekEnd = endOfWeek(now, { weekStartsOn: 1 })
 
72
  export default function AppointmentsPage() {
73
  const { user, isLoading: authLoading } = useAuth()
74
  const queryClient = useQueryClient()
75
+
76
+ // View state
77
+ const [viewMode, setViewMode] = useState<ViewMode>('week')
78
+ const [currentDate, setCurrentDate] = useState<Date>(new Date())
79
+ const [selectedResourceIds, setSelectedResourceIds] = useState<string[]>([]) // empty = all
80
+ const [selectedAppointment, setSelectedAppointment] = useState<Appointment | null>(null)
81
  const [showCreateModal, setShowCreateModal] = useState(false)
82
 
83
+ // Drag state
84
+ const [draggedAppointment, setDraggedAppointment] = useState<Appointment | null>(null)
85
+
86
+ // Fetch tenant settings
87
  const { data: tenantData } = useQuery({
88
  queryKey: ['tenant-settings', user?.tenant_id],
89
  queryFn: async () => {
 
91
  return res.data
92
  },
93
  enabled: !!user && !authLoading,
 
 
94
  })
95
 
96
  // Fetch services
 
100
  enabled: !!user && !authLoading,
101
  })
102
 
103
+ // Fetch resources
104
+ const { data: resources = [] } = useQuery<Resource[]>({
105
  queryKey: ['booking-resources', user?.tenant_id],
106
  queryFn: () => bookingsApi.getResources(),
107
  enabled: !!user && !authLoading,
108
  })
109
 
110
+ // Fetch appointments
111
+ const { data: appointments = [], isLoading, refetch } = useQuery<Appointment[]>({
112
  queryKey: ['appointments', user?.tenant_id],
113
  queryFn: () => bookingsApi.getAppointments(),
114
  enabled: !!user && !authLoading,
 
116
  refetchOnMount: 'always',
117
  })
118
 
119
+ // Booking settings
120
  const bookingSettings = tenantData?.booking_settings || {
121
+ working_days: [0, 1, 2, 3, 4],
122
  working_hours: { start: '09:00', end: '18:00' },
123
  slot_duration: 30,
 
124
  }
125
 
126
  // Calculate stats
127
  const stats = useMemo(() => calculateStats(appointments), [appointments])
128
 
129
+ // Filter appointments by selected resources
130
+ const filteredAppointments = useMemo(() => {
131
+ if (selectedResourceIds.length === 0) return appointments
132
+ return appointments.filter(apt =>
133
+ apt.resource_id && selectedResourceIds.includes(apt.resource_id)
134
+ )
135
+ }, [appointments, selectedResourceIds])
136
 
137
+ // Navigate dates
138
+ const navigateDate = useCallback((direction: 'prev' | 'next') => {
139
+ setCurrentDate(prev => {
140
+ switch (viewMode) {
141
+ case 'day':
142
+ return direction === 'next' ? addDays(prev, 1) : addDays(prev, -1)
143
+ case 'week':
144
+ return direction === 'next' ? addWeeks(prev, 1) : addWeeks(prev, -1)
145
+ case 'month':
146
+ return direction === 'next' ? addMonths(prev, 1) : addMonths(prev, -1)
147
+ }
148
+ })
149
+ }, [viewMode])
150
+
151
+ // Get date label
152
+ const dateLabel = useMemo(() => {
153
+ switch (viewMode) {
154
+ case 'day':
155
+ return format(currentDate, 'd MMMM yyyy', { locale: ru })
156
+ case 'week':
157
+ const weekStart = startOfWeek(currentDate, { weekStartsOn: 1 })
158
+ const weekEnd = endOfWeek(currentDate, { weekStartsOn: 1 })
159
+ return `${format(weekStart, 'd')} - ${format(weekEnd, 'd MMMM yyyy', { locale: ru })}`
160
+ case 'month':
161
+ return format(currentDate, 'MMMM yyyy', { locale: ru })
162
+ }
163
+ }, [currentDate, viewMode])
164
+
165
+ // Toggle resource filter
166
+ const toggleResourceFilter = (resourceId: string) => {
167
+ setSelectedResourceIds(prev => {
168
+ if (prev.includes(resourceId)) {
169
+ return prev.filter(id => id !== resourceId)
170
+ }
171
+ return [...prev, resourceId]
172
+ })
173
  }
174
 
175
+ // Handle appointment actions
176
+ const handleDelete = async (appointmentId: string) => {
177
+ await queryClient.invalidateQueries({ queryKey: ['appointments'] })
178
  setSelectedAppointment(null)
179
  }
180
 
181
+ const handleStatusChange = async (appointmentId: string, newStatus: string) => {
182
+ try {
183
+ await bookingsApi.updateAppointment(appointmentId, { status: newStatus })
184
+ refetch()
185
+ if (selectedAppointment?.id === appointmentId) {
186
+ setSelectedAppointment({ ...selectedAppointment, status: newStatus })
187
+ }
188
+ } catch (e) {
189
+ console.error('Failed to update status:', e)
190
  }
191
  }
192
 
193
+ // Drag and drop handlers
194
+ const handleDragStart = (apt: Appointment) => {
195
+ setDraggedAppointment(apt)
196
+ }
197
+
198
+ const handleDragEnd = () => {
199
+ setDraggedAppointment(null)
200
+ }
201
+
202
+ const handleDrop = async (newDate: Date, newHour: number) => {
203
+ if (!draggedAppointment) return
204
+
205
+ const newStartTime = new Date(newDate)
206
+ newStartTime.setHours(newHour, 0, 0, 0)
207
+
208
+ const oldStart = new Date(draggedAppointment.start_time)
209
+ const duration = draggedAppointment.end_time
210
+ ? differenceInMinutes(new Date(draggedAppointment.end_time), oldStart)
211
+ : 30
212
+
213
+ const newEndTime = new Date(newStartTime.getTime() + duration * 60000)
214
+
215
+ try {
216
+ await bookingsApi.updateAppointment(draggedAppointment.id, {
217
+ start_time: newStartTime.toISOString(),
218
+ end_time: newEndTime.toISOString()
219
+ })
220
+ refetch()
221
+ } catch (e) {
222
+ console.error('Failed to reschedule:', e)
223
+ }
224
+
225
+ setDraggedAppointment(null)
226
  }
227
 
228
+ // Generate time slots for day/week view
229
+ const hours = useMemo(() => {
230
+ const start = parseInt(bookingSettings.working_hours.start?.split(':')[0] || '9')
231
+ const end = parseInt(bookingSettings.working_hours.end?.split(':')[0] || '18')
232
+ return Array.from({ length: end - start }, (_, i) => start + i)
233
+ }, [bookingSettings])
234
+
235
+ // Get days for current view
236
+ const viewDays = useMemo(() => {
237
+ switch (viewMode) {
238
+ case 'day':
239
+ return [currentDate]
240
+ case 'week':
241
+ return eachDayOfInterval({
242
+ start: startOfWeek(currentDate, { weekStartsOn: 1 }),
243
+ end: endOfWeek(currentDate, { weekStartsOn: 1 })
244
+ })
245
+ case 'month':
246
+ return eachDayOfInterval({
247
+ start: startOfWeek(startOfMonth(currentDate), { weekStartsOn: 1 }),
248
+ end: endOfWeek(endOfMonth(currentDate), { weekStartsOn: 1 })
249
+ })
250
+ }
251
+ }, [viewMode, currentDate])
252
+
253
+ // Get appointments for a specific day and hour
254
+ const getAppointmentsForSlot = useCallback((day: Date, hour: number) => {
255
+ return filteredAppointments.filter(apt => {
256
+ const start = new Date(apt.start_time)
257
+ return isSameDay(start, day) && start.getHours() === hour
258
+ })
259
+ }, [filteredAppointments])
260
+
261
+ // Get all appointments for day (month view)
262
+ const getAppointmentsForDay = useCallback((day: Date) => {
263
+ return filteredAppointments.filter(apt => {
264
+ return isSameDay(new Date(apt.start_time), day) && apt.status !== 'cancelled'
265
+ })
266
+ }, [filteredAppointments])
267
+
268
  return (
269
  <div className="min-h-screen p-3 md:p-6 lg:p-10 font-['Inter']">
270
+ <div className="max-w-[1800px] mx-auto min-h-[calc(100vh-24px)] flex flex-col">
271
 
272
+ {/* Header */}
273
  <div className="flex flex-col gap-4 mb-4 md:mb-6 flex-shrink-0">
274
  {/* Title Row */}
275
  <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
 
278
  <CalendarIcon className="w-5 h-5 md:w-6 md:h-6 text-indigo-400" />
279
  </div>
280
  <div>
281
+ <h1 className="text-xl md:text-3xl font-bold text-white tracking-tight">Календарь записей</h1>
282
  <div className="flex items-center gap-2 text-xs md:text-sm text-slate-400 mt-0.5 md:mt-1">
283
  <span className="w-1.5 h-1.5 md:w-2 md:h-2 rounded-full bg-emerald-500"></span>
284
  <span>Онлайн запись активна</span>
 
331
  </div>
332
  </div>
333
 
334
+ {/* Controls Bar */}
335
+ <div className="flex flex-wrap items-center justify-between gap-4 mb-4">
336
+ {/* View Mode Switcher */}
337
+ <div className="flex items-center gap-1 bg-white/5 border border-white/10 rounded-xl p-1">
338
+ {(['day', 'week', 'month'] as ViewMode[]).map(mode => (
339
+ <button
340
+ key={mode}
341
+ onClick={() => setViewMode(mode)}
342
+ className={cn(
343
+ "px-4 py-2 rounded-lg text-sm font-medium transition-all",
344
+ viewMode === mode
345
+ ? "bg-indigo-600 text-white"
346
+ : "text-slate-400 hover:text-white hover:bg-white/10"
347
+ )}
348
+ >
349
+ {mode === 'day' ? 'День' : mode === 'week' ? 'Неделя' : 'Месяц'}
350
+ </button>
351
+ ))}
352
+ </div>
353
+
354
+ {/* Date Navigation */}
355
+ <div className="flex items-center gap-2">
356
+ <button
357
+ onClick={() => navigateDate('prev')}
358
+ className="p-2 bg-white/5 border border-white/10 rounded-lg hover:bg-white/10"
359
+ >
360
+ <ChevronLeft className="w-5 h-5 text-slate-400" />
361
+ </button>
362
+ <button
363
+ onClick={() => setCurrentDate(new Date())}
364
+ className="px-4 py-2 bg-white/5 border border-white/10 rounded-lg text-sm text-white font-medium hover:bg-white/10"
365
+ >
366
+ Сегодня
367
+ </button>
368
+ <span className="min-w-[180px] text-center text-white font-semibold">{dateLabel}</span>
369
+ <button
370
+ onClick={() => navigateDate('next')}
371
+ className="p-2 bg-white/5 border border-white/10 rounded-lg hover:bg-white/10"
372
+ >
373
+ <ChevronRight className="w-5 h-5 text-slate-400" />
374
+ </button>
375
+ </div>
376
+
377
+ {/* Resource Filter */}
378
+ {resources.length > 0 && (
379
+ <div className="flex items-center gap-2 flex-wrap">
380
+ <span className="text-xs text-slate-500 uppercase font-semibold">Ресурсы:</span>
381
+ <button
382
+ onClick={() => setSelectedResourceIds([])}
383
+ className={cn(
384
+ "px-3 py-1.5 rounded-lg text-xs font-medium border transition-all",
385
+ selectedResourceIds.length === 0
386
+ ? "bg-indigo-600/20 border-indigo-500/50 text-white"
387
+ : "bg-white/5 border-white/10 text-slate-400 hover:bg-white/10"
388
+ )}
389
+ >
390
+ Все
391
+ </button>
392
+ {resources.map((resource, idx) => (
393
+ <button
394
+ key={resource.id}
395
+ onClick={() => toggleResourceFilter(resource.id)}
396
+ className={cn(
397
+ "px-3 py-1.5 rounded-lg text-xs font-medium border transition-all flex items-center gap-2",
398
+ selectedResourceIds.includes(resource.id)
399
+ ? "bg-indigo-600/20 border-indigo-500/50 text-white"
400
+ : "bg-white/5 border-white/10 text-slate-400 hover:bg-white/10"
401
+ )}
402
+ >
403
+ <span className={cn("w-2 h-2 rounded-full", getResourceColor(idx))} />
404
+ {resource.name}
405
+ </button>
406
+ ))}
407
+ </div>
408
+ )}
409
+ </div>
410
+
411
+ {/* Calendar Grid */}
412
+ <div className="flex-1 grid grid-cols-1 lg:grid-cols-12 gap-4 min-h-0">
413
+ {/* Calendar */}
414
+ <div className="lg:col-span-9 bg-[#0a0a12] border border-white/10 rounded-2xl overflow-hidden">
415
  {isLoading ? (
416
+ <div className="flex items-center justify-center h-96">
417
+ <Loader2 className="w-8 h-8 animate-spin text-indigo-500" />
418
+ </div>
419
+ ) : viewMode === 'month' ? (
420
+ /* Month View */
421
+ <div className="grid grid-cols-7 h-full">
422
+ {/* Day headers */}
423
+ {['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'].map(day => (
424
+ <div key={day} className="py-2 text-center text-xs text-slate-500 font-semibold border-b border-white/5">
425
+ {day}
426
+ </div>
427
+ ))}
428
+ {/* Days */}
429
+ {viewDays.map(day => {
430
+ const dayAppts = getAppointmentsForDay(day)
431
+ const isToday = isSameDay(day, new Date())
432
+ const isCurrentMonth = isSameMonth(day, currentDate)
433
+
434
+ return (
435
+ <div
436
+ key={day.toString()}
437
+ className={cn(
438
+ "min-h-[100px] p-2 border-b border-r border-white/5 transition-colors",
439
+ !isCurrentMonth && "opacity-40",
440
+ isToday && "bg-indigo-500/5"
441
+ )}
442
+ onDragOver={(e) => e.preventDefault()}
443
+ onDrop={() => handleDrop(day, 10)}
444
+ >
445
+ <div className={cn(
446
+ "text-sm font-medium mb-1",
447
+ isToday ? "text-indigo-400" : "text-slate-400"
448
+ )}>
449
+ {format(day, 'd')}
450
+ </div>
451
+ <div className="space-y-1">
452
+ {dayAppts.slice(0, 3).map(apt => {
453
+ const resourceIdx = resources.findIndex(r => r.id === apt.resource_id)
454
+ return (
455
+ <div
456
+ key={apt.id}
457
+ draggable
458
+ onDragStart={() => handleDragStart(apt)}
459
+ onDragEnd={handleDragEnd}
460
+ onClick={() => setSelectedAppointment(apt)}
461
+ className={cn(
462
+ "text-xs px-2 py-1 rounded cursor-pointer truncate flex items-center gap-1",
463
+ "bg-indigo-500/20 text-indigo-300 hover:bg-indigo-500/30"
464
+ )}
465
+ >
466
+ <GripVertical className="w-3 h-3 opacity-50 shrink-0" />
467
+ {resourceIdx >= 0 && (
468
+ <span className={cn("w-1.5 h-1.5 rounded-full shrink-0", getResourceColor(resourceIdx))} />
469
+ )}
470
+ {format(new Date(apt.start_time), 'HH:mm')}
471
+ {apt.lead_name && <span className="truncate">{apt.lead_name}</span>}
472
+ </div>
473
+ )
474
+ })}
475
+ {dayAppts.length > 3 && (
476
+ <div className="text-xs text-slate-500 px-2">
477
+ +{dayAppts.length - 3} ещё
478
+ </div>
479
+ )}
480
+ </div>
481
+ </div>
482
+ )
483
+ })}
484
  </div>
485
  ) : (
486
+ /* Day/Week View */
487
+ <div className="flex h-[600px] overflow-auto">
488
+ {/* Time column */}
489
+ <div className="w-16 flex-shrink-0 border-r border-white/5">
490
+ <div className="h-10 border-b border-white/5" />
491
+ {hours.map(hour => (
492
+ <div key={hour} className="h-16 px-2 py-1 text-xs text-slate-500 text-right">
493
+ {`${hour}:00`}
494
+ </div>
495
+ ))}
496
+ </div>
497
+
498
+ {/* Days columns */}
499
+ {viewDays.map(day => {
500
+ const isToday = isSameDay(day, new Date())
501
+ return (
502
+ <div key={day.toString()} className="flex-1 min-w-[120px] border-r border-white/5">
503
+ {/* Day header */}
504
+ <div className={cn(
505
+ "h-10 px-2 flex items-center justify-center text-sm font-medium border-b border-white/5",
506
+ isToday ? "text-indigo-400 bg-indigo-500/10" : "text-slate-400"
507
+ )}>
508
+ <span>{format(day, viewMode === 'day' ? 'EEEE, d MMM' : 'EEE d', { locale: ru })}</span>
509
+ </div>
510
+ {/* Hour slots */}
511
+ {hours.map(hour => {
512
+ const slotAppts = getAppointmentsForSlot(day, hour)
513
+ return (
514
+ <div
515
+ key={hour}
516
+ className={cn(
517
+ "h-16 border-b border-white/5 p-0.5 transition-colors",
518
+ draggedAppointment && "hover:bg-indigo-500/10"
519
+ )}
520
+ onDragOver={(e) => e.preventDefault()}
521
+ onDrop={() => handleDrop(day, hour)}
522
+ >
523
+ {slotAppts.map(apt => {
524
+ const resourceIdx = resources.findIndex(r => r.id === apt.resource_id)
525
+ return (
526
+ <div
527
+ key={apt.id}
528
+ draggable
529
+ onDragStart={() => handleDragStart(apt)}
530
+ onDragEnd={handleDragEnd}
531
+ onClick={() => setSelectedAppointment(apt)}
532
+ className={cn(
533
+ "text-xs px-2 py-1 rounded cursor-pointer flex items-center gap-1 mb-0.5",
534
+ apt.status === 'cancelled'
535
+ ? "bg-red-500/20 text-red-300 line-through"
536
+ : apt.status === 'completed'
537
+ ? "bg-emerald-500/20 text-emerald-300"
538
+ : "bg-indigo-500/20 text-indigo-300 hover:bg-indigo-500/30"
539
+ )}
540
+ >
541
+ <GripVertical className="w-3 h-3 opacity-50 shrink-0 cursor-grab" />
542
+ {resourceIdx >= 0 && (
543
+ <span className={cn("w-2 h-2 rounded-full shrink-0", getResourceColor(resourceIdx))} />
544
+ )}
545
+ <span className="font-medium">{format(new Date(apt.start_time), 'HH:mm')}</span>
546
+ <span className="truncate">{apt.lead_name || apt.service_name || 'Запись'}</span>
547
+ </div>
548
+ )
549
+ })}
550
+ </div>
551
+ )
552
+ })}
553
+ </div>
554
+ )
555
+ })}
556
+ </div>
557
  )}
558
  </div>
559
 
560
+ {/* Right Panel - Appointment Details */}
561
+ <div className="hidden lg:block lg:col-span-3 h-full min-h-0">
562
  <AppointmentDetails
563
  appointment={selectedAppointment}
564
+ onClose={() => setSelectedAppointment(null)}
565
  onDelete={handleDelete}
566
  onStatusChange={handleStatusChange}
567
  />
568
  </div>
569
  </div>
570
 
571
+ {/* Mobile Details Modal */}
572
  <AnimatePresence>
573
  {selectedAppointment && (
574
  <motion.div
 
576
  animate={{ opacity: 1 }}
577
  exit={{ opacity: 0 }}
578
  className="lg:hidden fixed inset-0 z-50 bg-black/60 backdrop-blur-sm"
579
+ onClick={() => setSelectedAppointment(null)}
580
  >
581
  <motion.div
582
  initial={{ y: '100%' }}
 
587
  onClick={(e) => e.stopPropagation()}
588
  >
589
  <div className="sticky top-0 bg-[#1E1F2E] pt-3 pb-2 px-4 flex items-center gap-3 z-10 border-b border-white/5">
590
+ <button onClick={() => setSelectedAppointment(null)} className="p-2 hover:bg-white/10 rounded-lg">
591
  <X className="w-5 h-5 text-slate-400" />
592
  </button>
593
  <span className="font-semibold text-white">Детали записи</span>
 
595
  <div className="bg-[#1E1F2E] pb-20">
596
  <AppointmentDetails
597
  appointment={selectedAppointment}
598
+ onClose={() => setSelectedAppointment(null)}
599
  onDelete={handleDelete}
600
  onStatusChange={handleStatusChange}
601
  />
 
605
  )}
606
  </AnimatePresence>
607
 
608
+ {/* Create Modal */}
609
  <AnimatePresence>
610
  {showCreateModal && (
611
  <CreateAppointmentModal
612
  onClose={() => setShowCreateModal(false)}
613
+ onSuccess={() => {
614
+ setShowCreateModal(false)
615
+ refetch()
616
+ }}
617
  services={services}
618
  bookingSettings={bookingSettings}
619
  />
frontend/components/bookings/AppointmentDetails.tsx CHANGED
@@ -2,11 +2,12 @@
2
 
3
  import { format, formatDistanceToNow, isToday, isYesterday } from 'date-fns'
4
  import { ru } from 'date-fns/locale'
5
- import { User, Phone, Mail, Clock, Calendar, CheckCircle2, Circle, XCircle, AlertCircle, FileText, Send } from 'lucide-react'
6
  import { cn } from '@/lib/utils'
7
  import { useState } from 'react'
8
  import { useToast } from '@/contexts/ToastContext'
9
  import { MicroChat } from './MicroChat'
 
10
 
11
  interface AppointmentDetailsProps {
12
  appointment: any
@@ -29,32 +30,21 @@ export function AppointmentDetails({ appointment, onClose, onStatusChange, onDel
29
  </div>
30
  <h3 className="text-xl font-bold text-white mb-2">Нет выбранной записи</h3>
31
  <p className="text-slate-400 max-w-[250px]">
32
- Выберите день в календаре или конкретную запись, чтобы увидеть подробности.
33
  </p>
34
  </div>
35
  )
36
  }
37
 
38
- const { id, lead, service, start_time, status, notes } = appointment
39
  const startDate = new Date(start_time)
 
40
 
41
- // Extract client name from notes if lead.name is missing
42
- // Notes format: "ClientName | Topic"
43
  const extractedName = notes?.split('|')?.[0]?.trim()
44
- const clientName = lead?.name || extractedName || 'Клиент'
45
  const clientInitial = clientName.charAt(0).toUpperCase()
46
-
47
- // Dynamic last message time
48
- const getLastMessageText = () => {
49
- const lastActivity = lead?.updated_at ? new Date(lead.updated_at) : startDate
50
- if (isToday(lastActivity)) {
51
- return `Сегодня в ${format(lastActivity, 'HH:mm')}`
52
- } else if (isYesterday(lastActivity)) {
53
- return `Вчера в ${format(lastActivity, 'HH:mm')}`
54
- } else {
55
- return formatDistanceToNow(lastActivity, { addSuffix: true, locale: ru })
56
- }
57
- }
58
 
59
  const statusConfig = {
60
  'scheduled': { label: 'Запланировано', color: 'text-indigo-400', bg: 'bg-indigo-500/10', border: 'border-indigo-500/20', icon: Circle },
@@ -70,58 +60,33 @@ export function AppointmentDetails({ appointment, onClose, onStatusChange, onDel
70
  if (isUpdating) return
71
  setIsUpdating(true)
72
  try {
73
- const token = localStorage.getItem('auth_token')
74
- const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/bookings/${id}`, {
75
- method: 'PATCH',
76
- headers: {
77
- 'Content-Type': 'application/json',
78
- 'Authorization': `Bearer ${token}`
79
- },
80
- body: JSON.stringify({ status: newStatus })
81
- })
82
- if (response.ok) {
83
- showSuccess('Статус обновлён')
84
- onStatusChange?.(id, newStatus)
85
- } else {
86
- showError('Ошибка обновления статуса')
87
- }
88
  } catch (error) {
89
- showError('Ошибка сети')
90
  } finally {
91
  setIsUpdating(false)
92
  }
93
  }
94
 
95
- const handleCancel = () => handleStatusChange('cancelled')
96
- const handleComplete = () => handleStatusChange('completed')
97
-
98
  const handleDelete = async () => {
99
  if (isDeleting) return
100
  setIsDeleting(true)
101
  try {
102
- const token = localStorage.getItem('auth_token')
103
- const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/bookings/${id}?hard=true`, {
104
- method: 'DELETE',
105
- headers: {
106
- 'Authorization': `Bearer ${token}`
107
- }
108
- })
109
- if (response.ok) {
110
- showSuccess('Запись удалена')
111
- onDelete?.(id)
112
- setShowDeleteConfirm(false)
113
- } else {
114
- showError('Ошибка удаления')
115
- }
116
  } catch (error) {
117
- showError('Ошибка сети')
118
  } finally {
119
  setIsDeleting(false)
120
  }
121
  }
122
 
123
  return (
124
- <div className="h-full bg-[#1E1F2E] border border-white/5 rounded-3xl p-6 shadow-2xl flex flex-col gap-6 overflow-y-auto">
125
  {/* Header / Client Info */}
126
  <div className="bg-white/5 rounded-2xl p-5 border border-white/5">
127
  <div className="flex items-center gap-4 mb-4">
@@ -130,14 +95,16 @@ export function AppointmentDetails({ appointment, onClose, onStatusChange, onDel
130
  </div>
131
  <div>
132
  <h2 className="text-xl font-bold text-white">{clientName}</h2>
 
 
 
 
 
 
133
  </div>
134
  </div>
135
 
136
- <div className="space-y-3 pt-2">
137
- <div className="flex items-center gap-3 text-sm text-slate-300">
138
- <User className="w-4 h-4 text-slate-500" />
139
- <span>{clientName}</span>
140
- </div>
141
  {lead?.phone && (
142
  <div className="flex items-center gap-3 text-sm text-slate-300">
143
  <Phone className="w-4 h-4 text-slate-500" />
@@ -153,37 +120,52 @@ export function AppointmentDetails({ appointment, onClose, onStatusChange, onDel
153
  </div>
154
  </div>
155
 
156
- {/* Appointment Type */}
157
- <div>
158
- <h3 className="text-sm font-medium text-slate-500 mb-2 uppercase tracking-wide">Тип встречи</h3>
159
- <div className="text-white font-semibold text-lg">
160
- {service?.name || 'Консультация'}
161
  </div>
162
- <div className="flex items-center gap-2 mt-1 text-indigo-400 text-sm font-medium">
163
- <Clock className="w-4 h-4" />
164
- {format(startDate, 'd MMMM yyyy, HH:mm', { locale: ru })}
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  </div>
166
  </div>
167
 
168
  {/* Notes */}
169
  {notes && (
170
  <div>
171
- <h3 className="text-sm font-medium text-slate-500 mb-2 uppercase tracking-wide">Заметки</h3>
172
- <div className="bg-white/5 rounded-xl p-4 border border-white/5 text-slate-300 text-sm leading-relaxed">
173
  {notes}
174
  </div>
175
  </div>
176
  )}
177
 
178
- {/* Micro Chat - Last messages */}
179
- <div>
180
- <h3 className="text-sm font-medium text-slate-500 mb-3 uppercase tracking-wide">Контекст диалога</h3>
181
- <MicroChat leadId={lead?.id} maxMessages={4} />
182
- </div>
 
 
183
 
184
- {/* Status */}
185
  <div>
186
- <h3 className="text-sm font-medium text-slate-500 mb-3 uppercase tracking-wide">Статус</h3>
187
  <div className={cn(
188
  "flex items-center justify-between p-3 rounded-xl border",
189
  currentStatus.bg,
@@ -193,53 +175,52 @@ export function AppointmentDetails({ appointment, onClose, onStatusChange, onDel
193
  <StatusIcon className="w-4 h-4" />
194
  {currentStatus.label}
195
  </span>
196
- {status === 'scheduled' && (
 
 
 
 
197
  <button
198
- onClick={handleComplete}
199
  disabled={isUpdating}
200
- className="text-xs text-emerald-400 hover:text-emerald-300 transition-colors underline disabled:opacity-50"
201
  >
 
202
  Завершить
203
  </button>
204
- )}
205
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  </div>
207
 
208
- {/* Divider */}
209
- <div className="h-px w-full bg-white/10 my-2" />
210
-
211
- {/* Actions */}
212
- {status === 'scheduled' && (
213
- <div className="grid grid-cols-2 gap-3 mt-auto">
214
- <button
215
- onClick={() => showSuccess('Функция переноса в разработке')}
216
- className="p-3 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-white text-sm font-medium transition-all"
217
- >
218
- Перенести
219
- </button>
220
- <button
221
- onClick={handleCancel}
222
- disabled={isUpdating}
223
- className="p-3 rounded-xl bg-red-500/10 hover:bg-red-500/20 border border-red-500/20 text-red-400 text-sm font-medium transition-all disabled:opacity-50"
224
- >
225
- {isUpdating ? 'Отмена...' : 'Отменить'}
226
- </button>
227
- </div>
228
- )}
229
-
230
- {/* Delete Button - visible for all statuses */}
231
- <div className="mt-3">
232
  {!showDeleteConfirm ? (
233
  <button
234
  onClick={() => setShowDeleteConfirm(true)}
235
- className="w-full p-3 rounded-xl bg-red-500/5 hover:bg-red-500/10 border border-red-500/10 text-red-400/70 text-sm font-medium transition-all flex items-center justify-center gap-2"
236
  >
237
  <XCircle className="w-4 h-4" />
238
  Удалить запись
239
  </button>
240
  ) : (
241
  <div className="bg-red-500/10 border border-red-500/20 rounded-xl p-4">
242
- <p className="text-red-400 text-sm mb-3 text-center">Удалить навсегда?</p>
243
  <div className="flex gap-2">
244
  <button
245
  onClick={() => setShowDeleteConfirm(false)}
 
2
 
3
  import { format, formatDistanceToNow, isToday, isYesterday } from 'date-fns'
4
  import { ru } from 'date-fns/locale'
5
+ import { User, Phone, Mail, Clock, Calendar, CheckCircle2, Circle, XCircle, AlertCircle, Edit2, Users } from 'lucide-react'
6
  import { cn } from '@/lib/utils'
7
  import { useState } from 'react'
8
  import { useToast } from '@/contexts/ToastContext'
9
  import { MicroChat } from './MicroChat'
10
+ import { bookingsApi } from '@/lib/api'
11
 
12
  interface AppointmentDetailsProps {
13
  appointment: any
 
30
  </div>
31
  <h3 className="text-xl font-bold text-white mb-2">Нет выбранной записи</h3>
32
  <p className="text-slate-400 max-w-[250px]">
33
+ Выберите запись в календаре, чтобы увидеть подробности.
34
  </p>
35
  </div>
36
  )
37
  }
38
 
39
+ const { id, lead, service, start_time, end_time, status, notes, resource_name, resource_id, lead_name, service_name } = appointment
40
  const startDate = new Date(start_time)
41
+ const endDate = end_time ? new Date(end_time) : null
42
 
43
+ // Extract client name
 
44
  const extractedName = notes?.split('|')?.[0]?.trim()
45
+ const clientName = lead_name || lead?.name || extractedName || 'Клиент'
46
  const clientInitial = clientName.charAt(0).toUpperCase()
47
+ const serviceName = service_name || service?.name || 'Консультация'
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  const statusConfig = {
50
  'scheduled': { label: 'Запланировано', color: 'text-indigo-400', bg: 'bg-indigo-500/10', border: 'border-indigo-500/20', icon: Circle },
 
60
  if (isUpdating) return
61
  setIsUpdating(true)
62
  try {
63
+ await bookingsApi.updateAppointment(id, { status: newStatus })
64
+ showSuccess('Статус обновлён')
65
+ onStatusChange?.(id, newStatus)
 
 
 
 
 
 
 
 
 
 
 
 
66
  } catch (error) {
67
+ showError('Ошибка обновления статуса')
68
  } finally {
69
  setIsUpdating(false)
70
  }
71
  }
72
 
 
 
 
73
  const handleDelete = async () => {
74
  if (isDeleting) return
75
  setIsDeleting(true)
76
  try {
77
+ await bookingsApi.cancelAppointment(id)
78
+ showSuccess('Запись удалена')
79
+ onDelete?.(id)
80
+ setShowDeleteConfirm(false)
 
 
 
 
 
 
 
 
 
 
81
  } catch (error) {
82
+ showError('Ошибка удаления')
83
  } finally {
84
  setIsDeleting(false)
85
  }
86
  }
87
 
88
  return (
89
+ <div className="h-full bg-[#1E1F2E] border border-white/5 rounded-3xl p-6 shadow-2xl flex flex-col gap-5 overflow-y-auto">
90
  {/* Header / Client Info */}
91
  <div className="bg-white/5 rounded-2xl p-5 border border-white/5">
92
  <div className="flex items-center gap-4 mb-4">
 
95
  </div>
96
  <div>
97
  <h2 className="text-xl font-bold text-white">{clientName}</h2>
98
+ {resource_name && (
99
+ <div className="flex items-center gap-1.5 text-sm text-slate-400 mt-0.5">
100
+ <Users className="w-3.5 h-3.5" />
101
+ <span>{resource_name}</span>
102
+ </div>
103
+ )}
104
  </div>
105
  </div>
106
 
107
+ <div className="space-y-2.5 pt-2">
 
 
 
 
108
  {lead?.phone && (
109
  <div className="flex items-center gap-3 text-sm text-slate-300">
110
  <Phone className="w-4 h-4 text-slate-500" />
 
120
  </div>
121
  </div>
122
 
123
+ {/* Service & Time */}
124
+ <div className="grid grid-cols-2 gap-4">
125
+ <div>
126
+ <h3 className="text-xs font-semibold text-slate-500 mb-1.5 uppercase tracking-wide">Услуга</h3>
127
+ <div className="text-white font-semibold">{serviceName}</div>
128
  </div>
129
+ <div>
130
+ <h3 className="text-xs font-semibold text-slate-500 mb-1.5 uppercase tracking-wide">Время</h3>
131
+ <div className="text-indigo-400 font-semibold flex items-center gap-1.5">
132
+ <Clock className="w-4 h-4" />
133
+ {format(startDate, 'HH:mm')}
134
+ {endDate && <span className="text-slate-500">- {format(endDate, 'HH:mm')}</span>}
135
+ </div>
136
+ </div>
137
+ </div>
138
+
139
+ {/* Date */}
140
+ <div>
141
+ <h3 className="text-xs font-semibold text-slate-500 mb-1.5 uppercase tracking-wide">Дата</h3>
142
+ <div className="text-white font-medium flex items-center gap-2">
143
+ <Calendar className="w-4 h-4 text-slate-500" />
144
+ {format(startDate, 'd MMMM yyyy, EEEE', { locale: ru })}
145
  </div>
146
  </div>
147
 
148
  {/* Notes */}
149
  {notes && (
150
  <div>
151
+ <h3 className="text-xs font-semibold text-slate-500 mb-1.5 uppercase tracking-wide">Заметки</h3>
152
+ <div className="bg-white/5 rounded-xl p-3 border border-white/5 text-slate-300 text-sm leading-relaxed">
153
  {notes}
154
  </div>
155
  </div>
156
  )}
157
 
158
+ {/* Micro Chat */}
159
+ {(lead?.id || appointment.lead_id) && (
160
+ <div>
161
+ <h3 className="text-xs font-semibold text-slate-500 mb-2 uppercase tracking-wide">Последние сообщения</h3>
162
+ <MicroChat leadId={lead?.id || appointment.lead_id} maxMessages={3} />
163
+ </div>
164
+ )}
165
 
166
+ {/* Status with Quick Actions */}
167
  <div>
168
+ <h3 className="text-xs font-semibold text-slate-500 mb-2 uppercase tracking-wide">Статус</h3>
169
  <div className={cn(
170
  "flex items-center justify-between p-3 rounded-xl border",
171
  currentStatus.bg,
 
175
  <StatusIcon className="w-4 h-4" />
176
  {currentStatus.label}
177
  </span>
178
+ </div>
179
+
180
+ {/* Quick Status Buttons */}
181
+ {status === 'scheduled' && (
182
+ <div className="flex gap-2 mt-3">
183
  <button
184
+ onClick={() => handleStatusChange('completed')}
185
  disabled={isUpdating}
186
+ className="flex-1 py-2 px-3 rounded-lg bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-xs font-medium hover:bg-emerald-500/20 transition-all disabled:opacity-50 flex items-center justify-center gap-1.5"
187
  >
188
+ <CheckCircle2 className="w-3.5 h-3.5" />
189
  Завершить
190
  </button>
191
+ <button
192
+ onClick={() => handleStatusChange('no_show')}
193
+ disabled={isUpdating}
194
+ className="flex-1 py-2 px-3 rounded-lg bg-amber-500/10 border border-amber-500/20 text-amber-400 text-xs font-medium hover:bg-amber-500/20 transition-all disabled:opacity-50 flex items-center justify-center gap-1.5"
195
+ >
196
+ <AlertCircle className="w-3.5 h-3.5" />
197
+ Неявка
198
+ </button>
199
+ <button
200
+ onClick={() => handleStatusChange('cancelled')}
201
+ disabled={isUpdating}
202
+ className="flex-1 py-2 px-3 rounded-lg bg-red-500/10 border border-red-500/20 text-red-400 text-xs font-medium hover:bg-red-500/20 transition-all disabled:opacity-50 flex items-center justify-center gap-1.5"
203
+ >
204
+ <XCircle className="w-3.5 h-3.5" />
205
+ Отменить
206
+ </button>
207
+ </div>
208
+ )}
209
  </div>
210
 
211
+ {/* Delete Button */}
212
+ <div className="mt-auto pt-4 border-t border-white/5">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  {!showDeleteConfirm ? (
214
  <button
215
  onClick={() => setShowDeleteConfirm(true)}
216
+ className="w-full p-2.5 rounded-xl bg-red-500/5 hover:bg-red-500/10 border border-red-500/10 text-red-400/70 text-sm font-medium transition-all flex items-center justify-center gap-2"
217
  >
218
  <XCircle className="w-4 h-4" />
219
  Удалить запись
220
  </button>
221
  ) : (
222
  <div className="bg-red-500/10 border border-red-500/20 rounded-xl p-4">
223
+ <p className="text-red-400 text-sm mb-3 text-center">Удалить запись навсегда?</p>
224
  <div className="flex gap-2">
225
  <button
226
  onClick={() => setShowDeleteConfirm(false)}
frontend/components/bookings/BookingModal.tsx CHANGED
@@ -27,6 +27,13 @@ interface Service {
27
  duration_minutes: number
28
  }
29
 
 
 
 
 
 
 
 
30
  interface ExistingAppointment {
31
  id: string
32
  start_time: string
@@ -35,8 +42,8 @@ interface ExistingAppointment {
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)
@@ -48,15 +55,11 @@ function generateTimeSlots(startTime: string, endTime: string): string[] {
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)
@@ -68,6 +71,7 @@ export function BookingModal({ isOpen, onClose, leadId, leadName }: BookingModal
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)
@@ -81,20 +85,28 @@ export function BookingModal({ isOpen, onClose, leadId, leadName }: BookingModal
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
  }
@@ -114,29 +126,46 @@ export function BookingModal({ isOpen, onClose, leadId, leadName }: BookingModal
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
@@ -169,6 +198,11 @@ export function BookingModal({ isOpen, onClose, leadId, leadName }: BookingModal
169
  }
170
  }, [selectedDate, selectedTime, selectedService, selectedResource, services, leadId, bookingNote])
171
 
 
 
 
 
 
172
  if (!isOpen) return null
173
 
174
  const hasExistingBooking = existingAppointments.length > 0
@@ -204,6 +238,9 @@ export function BookingModal({ isOpen, onClose, leadId, leadName }: BookingModal
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}
@@ -225,7 +262,9 @@ export function BookingModal({ isOpen, onClose, leadId, leadName }: BookingModal
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" />
@@ -288,7 +327,7 @@ export function BookingModal({ isOpen, onClose, leadId, leadName }: BookingModal
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
@@ -305,6 +344,11 @@ export function BookingModal({ isOpen, onClose, leadId, leadName }: BookingModal
305
  </button>
306
  ))}
307
  </div>
 
 
 
 
 
308
  </section>
309
  )}
310
 
@@ -332,6 +376,7 @@ export function BookingModal({ isOpen, onClose, leadId, leadName }: BookingModal
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
  })}
@@ -340,9 +385,14 @@ export function BookingModal({ isOpen, onClose, leadId, leadName }: BookingModal
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 => (
 
27
  duration_minutes: number
28
  }
29
 
30
+ interface BookingSettings {
31
+ working_hours: { start: string; end: string }
32
+ working_days: number[] // 0=Mon, 6=Sun
33
+ slot_duration: number
34
+ timezone: string
35
+ }
36
+
37
  interface ExistingAppointment {
38
  id: string
39
  start_time: string
 
42
  resource_name?: string
43
  }
44
 
45
+ // Generate time slots from start to end with interval
46
+ function generateTimeSlots(startTime: string, endTime: string, interval: number = 30): string[] {
47
  const slots: string[] = []
48
  const [startH, startM] = startTime.split(':').map(Number)
49
  const [endH, endM] = endTime.split(':').map(Number)
 
55
  const h = Math.floor(current / 60)
56
  const m = current % 60
57
  slots.push(`${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`)
58
+ current += interval
59
  }
60
  return slots
61
  }
62
 
 
 
 
 
63
  export function BookingModal({ isOpen, onClose, leadId, leadName }: BookingModalProps) {
64
  const [selectedDate, setSelectedDate] = useState<Date>(startOfToday())
65
  const [selectedTime, setSelectedTime] = useState<string | null>(null)
 
71
  // Data states
72
  const [services, setServices] = useState<Service[]>([])
73
  const [resources, setResources] = useState<Resource[]>([])
74
+ const [bookingSettings, setBookingSettings] = useState<BookingSettings | null>(null)
75
  const [existingAppointments, setExistingAppointments] = useState<ExistingAppointment[]>([])
76
  const [selectedService, setSelectedService] = useState<string | null>(null)
77
  const [isLoading, setIsLoading] = useState(true)
 
85
 
86
  const loadData = async () => {
87
  try {
88
+ const [servicesData, resourcesData, settingsData, appointmentsData] = await Promise.all([
89
  bookingsApi.getServices(),
90
  bookingsApi.getResources(),
91
+ bookingsApi.getBookingSettings(),
92
  bookingsApi.getAppointmentsByLead(leadId)
93
  ])
94
 
95
  setServices(servicesData?.length ? servicesData : [{ id: 'default', name: 'Консультация', duration_minutes: 30 }])
96
  setSelectedService(servicesData?.[0]?.id || 'default')
97
  setResources(resourcesData || [])
98
+ setBookingSettings(settingsData)
99
  setExistingAppointments(appointmentsData?.filter((a: ExistingAppointment) => a.status === 'scheduled') || [])
100
  } catch (e) {
101
  console.error('Failed to load booking data:', e)
102
  setServices([{ id: 'default', name: 'Консультация', duration_minutes: 30 }])
103
  setSelectedService('default')
104
+ setBookingSettings({
105
+ working_hours: { start: '09:00', end: '18:00' },
106
+ working_days: [0, 1, 2, 3, 4],
107
+ slot_duration: 30,
108
+ timezone: 'Asia/Bishkek'
109
+ })
110
  } finally {
111
  setIsLoading(false)
112
  }
 
126
  return resources.find(r => r.id === selectedResource)
127
  }, [selectedResource, resources])
128
 
129
+ // Get working hours for current context
130
+ // Priority: Resource working hours > Company booking settings
131
+ const getWorkingHoursForDate = useCallback((date: Date): { start: string; end: string } | null => {
132
+ const jsDay = getDay(date) // 0=Sunday, 1=Monday, ...
133
+ // Convert to 0=Monday format
134
+ const dayKey = String(jsDay === 0 ? 6 : jsDay - 1)
135
+
136
+ // If resource selected, use its working hours
137
+ if (selectedResourceData?.working_hours) {
138
+ const resourceHours = selectedResourceData.working_hours[dayKey]
139
+ if (!resourceHours) return null // Day off for resource
140
+ return resourceHours
 
141
  }
142
 
143
+ // Otherwise use company settings
144
+ if (bookingSettings) {
145
+ // Check if this day is a working day
146
+ const dayIndex = jsDay === 0 ? 6 : jsDay - 1 // Convert to 0=Mon
147
+ if (!bookingSettings.working_days.includes(dayIndex)) {
148
+ return null // Day off for company
149
+ }
150
+ return bookingSettings.working_hours
151
+ }
152
 
153
+ return { start: '09:00', end: '18:00' }
154
+ }, [selectedResourceData, bookingSettings])
155
 
156
+ // Check if date is working day
157
+ const isWorkingDay = useCallback((date: Date) => {
158
+ return getWorkingHoursForDate(date) !== null
159
+ }, [getWorkingHoursForDate])
160
+
161
+ // Memoized time slots based on selected date and resource/company settings
162
+ const timeSlots = useMemo(() => {
163
+ const hours = getWorkingHoursForDate(selectedDate)
164
+ if (!hours) return []
165
+
166
+ const interval = bookingSettings?.slot_duration || 30
167
+ return generateTimeSlots(hours.start, hours.end, interval)
168
+ }, [selectedDate, getWorkingHoursForDate, bookingSettings])
169
 
170
  const handleBook = useCallback(async () => {
171
  if (!selectedDate || !selectedTime || !selectedService) return
 
198
  }
199
  }, [selectedDate, selectedTime, selectedService, selectedResource, services, leadId, bookingNote])
200
 
201
+ // Reset time when date or resource changes
202
+ useEffect(() => {
203
+ setSelectedTime(null)
204
+ }, [selectedDate, selectedResource])
205
+
206
  if (!isOpen) return null
207
 
208
  const hasExistingBooking = existingAppointments.length > 0
 
238
  Встреча с <span className="text-white font-medium">{leadName}</span> на{' '}
239
  <span className="text-indigo-400 font-bold">{selectedTime}</span>{' '}
240
  {format(selectedDate, 'd MMMM', { locale: ru })}
241
+ {selectedResourceData && (
242
+ <span className="text-slate-500"> • {selectedResourceData.name}</span>
243
+ )}
244
  </p>
245
  <button
246
  onClick={onClose}
 
262
  <CalendarIcon className="w-5 h-5 text-indigo-400" />
263
  Запись: {leadName || 'Клиент'}
264
  </h3>
265
+ <p className="text-xs text-slate-500 mt-0.5">
266
+ {bookingSettings?.timezone && `Часовой пояс: ${bookingSettings.timezone}`}
267
+ </p>
268
  </div>
269
  <button onClick={onClose} className="p-2 hover:bg-white/10 rounded-lg transition-colors text-slate-400 hover:text-white">
270
  <X className="w-5 h-5" />
 
327
  : "bg-white/5 border-white/10 text-slate-400 hover:bg-white/10"
328
  )}
329
  >
330
+ Любой (по расписанию компании)
331
  </button>
332
  {resources.map(r => (
333
  <button
 
344
  </button>
345
  ))}
346
  </div>
347
+ {selectedResourceData && (
348
+ <p className="text-xs text-slate-600 mt-2">
349
+ Показано расписание: {selectedResourceData.name}
350
+ </p>
351
+ )}
352
  </section>
353
  )}
354
 
 
376
  >
377
  <span className="text-[10px] font-semibold uppercase">{format(date, 'eee', { locale: ru })}</span>
378
  <span className="text-lg font-bold">{format(date, 'd')}</span>
379
+ {!isWorking && <span className="text-[8px] text-slate-700">выходной</span>}
380
  </button>
381
  )
382
  })}
 
385
 
386
  {/* Times */}
387
  <section>
388
+ <label className="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-3">
389
+ Время
390
+ {selectedResourceData && (
391
+ <span className="text-slate-600 font-normal ml-2">({selectedResourceData.name})</span>
392
+ )}
393
+ </label>
394
  {timeSlots.length === 0 ? (
395
+ <p className="text-sm text-slate-500">Выходной день - выберите другую дату</p>
396
  ) : (
397
  <div className="grid grid-cols-4 gap-2 max-h-[200px] overflow-y-auto">
398
  {timeSlots.map(time => (
frontend/lib/api.ts CHANGED
@@ -515,6 +515,22 @@ export const bookingsApi = {
515
  return response.data
516
  },
517
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518
  // Resources API
519
  getResources: async () => {
520
  const response = await api.get('/api/v1/bookings/resources')
 
515
  return response.data
516
  },
517
 
518
+ getBookingSettings: async () => {
519
+ const response = await api.get('/api/v1/bookings/settings')
520
+ return response.data
521
+ },
522
+
523
+ updateAppointment: async (appointmentId: string, data: {
524
+ start_time?: string
525
+ end_time?: string
526
+ status?: string
527
+ resource_id?: string | null
528
+ notes?: string
529
+ }) => {
530
+ const response = await api.patch(`/api/v1/bookings/${appointmentId}`, data)
531
+ return response.data
532
+ },
533
+
534
  // Resources API
535
  getResources: async () => {
536
  const response = await api.get('/api/v1/bookings/resources')