Spaces:
Running

axeronis commited on
Commit
b34de88
·
1 Parent(s): 9d4c0e3

feat: improve appointments page with stats, working day highlighting, create modal; remove Google Sheets from channels

Browse files
frontend/app/appointments/page.tsx CHANGED
@@ -1,24 +1,67 @@
1
  'use client'
2
 
3
- import { useState } from 'react'
4
  import { useQuery, useQueryClient } from '@tanstack/react-query'
5
- import { bookingsApi } 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 } from 'lucide-react'
9
  import Link from 'next/link'
10
- import { isSameDay } from 'date-fns'
11
  import { useAuth } from '@/contexts/AuthContext'
12
  import { motion, AnimatePresence } from 'framer-motion'
13
- import { useTranslation } from '@/lib/i18n'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  export default function AppointmentsPage() {
16
  const { user, isLoading: authLoading } = useAuth()
17
  const queryClient = useQueryClient()
18
  const [selectedDate, setSelectedDate] = useState<Date>(new Date())
19
  const [selectedAppointment, setSelectedAppointment] = useState<any>(null)
 
20
 
21
- // React Query for appointments - always fetch fresh to avoid stale tenant data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  const { data: appointments = [], isLoading } = useQuery({
23
  queryKey: ['appointments', user?.tenant_id],
24
  queryFn: () => bookingsApi.getAppointments(),
@@ -27,70 +70,111 @@ export default function AppointmentsPage() {
27
  refetchOnMount: 'always',
28
  })
29
 
30
- // When date changes, try to find an appointment on that day to select automatically, or clear selection
 
 
 
 
 
 
 
 
 
 
31
  const handleDateSelect = (date: Date) => {
32
  setSelectedDate(date)
33
  }
34
 
35
- // Close mobile details panel
36
  const handleCloseDetails = () => {
37
  setSelectedAppointment(null)
38
  }
39
 
40
- // Handle appointment delete - refresh list and clear selection
41
  const handleDelete = (appointmentId: string) => {
42
  queryClient.invalidateQueries({ queryKey: ['appointments'] })
43
  setSelectedAppointment(null)
44
  }
45
 
46
- // Handle status change - refresh list
47
  const handleStatusChange = (appointmentId: string, newStatus: string) => {
48
  queryClient.invalidateQueries({ queryKey: ['appointments'] })
49
- // Update local state too for immediate feedback
50
  if (selectedAppointment?.id === appointmentId) {
51
  setSelectedAppointment({ ...selectedAppointment, status: newStatus })
52
  }
53
  }
54
 
 
 
 
 
 
55
  return (
56
  <div className="min-h-screen p-3 md:p-6 lg:p-10 font-['Inter']">
57
  <div className="max-w-[1600px] mx-auto min-h-[calc(100vh-24px)] md:h-[calc(100vh-80px)] flex flex-col">
58
 
59
- {/* Header - Responsive */}
60
- <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-4 md:mb-8 flex-shrink-0">
61
- <div className="flex items-center gap-3 md:gap-4">
62
- <div className="w-10 h-10 md:w-12 md:h-12 rounded-xl md:rounded-2xl bg-indigo-500/10 flex items-center justify-center border border-indigo-500/20">
63
- <CalendarIcon className="w-5 h-5 md:w-6 md:h-6 text-indigo-400" />
64
- </div>
65
- <div>
66
- <h1 className="text-xl md:text-3xl font-bold text-white tracking-tight">Календарь</h1>
67
- <div className="flex items-center gap-2 text-xs md:text-sm text-slate-400 mt-0.5 md:mt-1">
68
- <span className="w-1.5 h-1.5 md:w-2 md:h-2 rounded-full bg-emerald-500"></span>
69
- <span>Онлайн запись активна</span>
70
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  </div>
72
  </div>
73
 
74
- <div className="flex gap-2 md:gap-3 w-full sm:w-auto">
75
- <Link
76
- href="/settings/brain"
77
- className="flex-1 sm:flex-initial px-3 md:px-5 py-2 md:py-2.5 bg-white/5 border border-white/10 text-slate-300 font-medium rounded-lg md:rounded-xl hover:bg-white/10 transition-colors flex items-center justify-center gap-2 text-sm"
78
- >
79
- <Settings className="w-4 h-4" />
80
- <span className="hidden sm:inline">Настройки</span>
81
- </Link>
82
- <button className="flex-1 sm:flex-initial px-3 md:px-5 py-2 md:py-2.5 bg-indigo-600 text-white font-bold rounded-lg md:rounded-xl hover:bg-indigo-700 shadow-lg shadow-indigo-500/20 transition-all flex items-center justify-center gap-2 text-sm">
83
- <Plus className="w-4 h-4 md:w-5 md:h-5" />
84
- <span className="hidden sm:inline">Новая запись</span>
85
- <span className="sm:hidden">Запись</span>
86
- </button>
 
 
 
 
 
 
 
 
 
 
87
  </div>
88
  </div>
89
 
90
- {/* Content Grid - Responsive */}
91
  <div className="flex-1 grid grid-cols-1 lg:grid-cols-12 gap-4 md:gap-6 min-h-0">
92
-
93
- {/* Left: Main Calendar - Full width on mobile */}
94
  <div className="lg:col-span-8 h-full flex flex-col min-h-0">
95
  {isLoading ? (
96
  <div className="flex-1 flex items-center justify-center bg-surface-elevated border border-white/5 rounded-xl md:rounded-3xl min-h-[400px]">
@@ -102,11 +186,13 @@ export default function AppointmentsPage() {
102
  selectedDate={selectedDate}
103
  onSelectDate={handleDateSelect}
104
  onSelectAppointment={setSelectedAppointment}
 
 
105
  />
106
  )}
107
  </div>
108
 
109
- {/* Right: Details Panel - Hidden on mobile, shown as modal */}
110
  <div className="hidden lg:block lg:col-span-4 h-full min-h-0">
111
  <AppointmentDetails
112
  appointment={selectedAppointment}
@@ -135,7 +221,6 @@ export default function AppointmentsPage() {
135
  className="absolute bottom-0 left-0 right-0 max-h-[80vh] overflow-y-auto rounded-t-3xl"
136
  onClick={(e) => e.stopPropagation()}
137
  >
138
- {/* Close handle + Back button */}
139
  <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">
140
  <button onClick={handleCloseDetails} className="p-2 hover:bg-white/10 rounded-lg">
141
  <X className="w-5 h-5 text-slate-400" />
@@ -154,6 +239,18 @@ export default function AppointmentsPage() {
154
  </motion.div>
155
  )}
156
  </AnimatePresence>
 
 
 
 
 
 
 
 
 
 
 
 
157
  </div>
158
  </div>
159
  )
 
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 })
20
+ const monthStart = startOfMonth(now)
21
+ const monthEnd = endOfMonth(now)
22
+
23
+ const today = appointments.filter(apt =>
24
+ isSameDay(new Date(apt.start_time), now) && apt.status !== 'cancelled'
25
+ ).length
26
+
27
+ const thisWeek = appointments.filter(apt => {
28
+ const date = new Date(apt.start_time)
29
+ return isWithinInterval(date, { start: weekStart, end: weekEnd }) && apt.status !== 'cancelled'
30
+ }).length
31
+
32
+ const thisMonth = appointments.filter(apt => {
33
+ const date = new Date(apt.start_time)
34
+ return isWithinInterval(date, { start: monthStart, end: monthEnd }) && apt.status !== 'cancelled'
35
+ }).length
36
+
37
+ return { today, thisWeek, thisMonth }
38
+ }
39
 
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 () => {
51
+ const res = await api.get('/api/v1/tenants/me')
52
+ return res.data
53
+ },
54
+ enabled: !!user && !authLoading,
55
+ })
56
+
57
+ // Fetch services
58
+ const { data: services = [] } = useQuery({
59
+ queryKey: ['booking-services', user?.tenant_id],
60
+ queryFn: () => bookingsApi.getServices(),
61
+ enabled: !!user && !authLoading,
62
+ })
63
+
64
+ // React Query for appointments
65
  const { data: appointments = [], isLoading } = useQuery({
66
  queryKey: ['appointments', user?.tenant_id],
67
  queryFn: () => bookingsApi.getAppointments(),
 
70
  refetchOnMount: 'always',
71
  })
72
 
73
+ // Extract booking settings
74
+ const bookingSettings = tenantData?.booking_settings || {
75
+ working_days: ['mon', 'tue', 'wed', 'thu', 'fri'],
76
+ working_hours: { start: '09:00', end: '18:00' },
77
+ slot_duration: 30,
78
+ timezone: 'Europe/Moscow'
79
+ }
80
+
81
+ // Calculate stats
82
+ const stats = useMemo(() => calculateStats(appointments), [appointments])
83
+
84
  const handleDateSelect = (date: Date) => {
85
  setSelectedDate(date)
86
  }
87
 
 
88
  const handleCloseDetails = () => {
89
  setSelectedAppointment(null)
90
  }
91
 
 
92
  const handleDelete = (appointmentId: string) => {
93
  queryClient.invalidateQueries({ queryKey: ['appointments'] })
94
  setSelectedAppointment(null)
95
  }
96
 
 
97
  const handleStatusChange = (appointmentId: string, newStatus: string) => {
98
  queryClient.invalidateQueries({ queryKey: ['appointments'] })
 
99
  if (selectedAppointment?.id === appointmentId) {
100
  setSelectedAppointment({ ...selectedAppointment, status: newStatus })
101
  }
102
  }
103
 
104
+ const handleCreateSuccess = () => {
105
+ setShowCreateModal(false)
106
+ queryClient.invalidateQueries({ queryKey: ['appointments'] })
107
+ }
108
+
109
  return (
110
  <div className="min-h-screen p-3 md:p-6 lg:p-10 font-['Inter']">
111
  <div className="max-w-[1600px] mx-auto min-h-[calc(100vh-24px)] md:h-[calc(100vh-80px)] flex flex-col">
112
 
113
+ {/* Header with Stats */}
114
+ <div className="flex flex-col gap-4 mb-4 md:mb-6 flex-shrink-0">
115
+ {/* Title Row */}
116
+ <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
117
+ <div className="flex items-center gap-3 md:gap-4">
118
+ <div className="w-10 h-10 md:w-12 md:h-12 rounded-xl md:rounded-2xl bg-indigo-500/10 flex items-center justify-center border border-indigo-500/20">
119
+ <CalendarIcon className="w-5 h-5 md:w-6 md:h-6 text-indigo-400" />
 
 
 
 
120
  </div>
121
+ <div>
122
+ <h1 className="text-xl md:text-3xl font-bold text-white tracking-tight">Календарь</h1>
123
+ <div className="flex items-center gap-2 text-xs md:text-sm text-slate-400 mt-0.5 md:mt-1">
124
+ <span className="w-1.5 h-1.5 md:w-2 md:h-2 rounded-full bg-emerald-500"></span>
125
+ <span>Онлайн запись активна</span>
126
+ </div>
127
+ </div>
128
+ </div>
129
+
130
+ <div className="flex gap-2 md:gap-3 w-full sm:w-auto">
131
+ <Link
132
+ href="/settings/brain"
133
+ className="flex-1 sm:flex-initial px-3 md:px-5 py-2 md:py-2.5 bg-white/5 border border-white/10 text-slate-300 font-medium rounded-lg md:rounded-xl hover:bg-white/10 transition-colors flex items-center justify-center gap-2 text-sm"
134
+ >
135
+ <Settings className="w-4 h-4" />
136
+ <span className="hidden sm:inline">Настройки</span>
137
+ </Link>
138
+ <button
139
+ onClick={() => setShowCreateModal(true)}
140
+ className="flex-1 sm:flex-initial px-3 md:px-5 py-2 md:py-2.5 bg-indigo-600 text-white font-bold rounded-lg md:rounded-xl hover:bg-indigo-700 shadow-lg shadow-indigo-500/20 transition-all flex items-center justify-center gap-2 text-sm"
141
+ >
142
+ <Plus className="w-4 h-4 md:w-5 md:h-5" />
143
+ <span className="hidden sm:inline">Новая запись</span>
144
+ <span className="sm:hidden">Запись</span>
145
+ </button>
146
  </div>
147
  </div>
148
 
149
+ {/* Stats Row */}
150
+ <div className="grid grid-cols-3 gap-2 md:gap-4">
151
+ <div className="bg-white/5 border border-white/10 rounded-xl p-3 md:p-4">
152
+ <div className="flex items-center gap-2 text-slate-400 text-xs md:text-sm mb-1">
153
+ <Clock className="w-3.5 h-3.5" />
154
+ <span>Сегодня</span>
155
+ </div>
156
+ <div className="text-xl md:text-2xl font-bold text-white">{stats.today}</div>
157
+ </div>
158
+ <div className="bg-white/5 border border-white/10 rounded-xl p-3 md:p-4">
159
+ <div className="flex items-center gap-2 text-slate-400 text-xs md:text-sm mb-1">
160
+ <Users className="w-3.5 h-3.5" />
161
+ <span>Неделя</span>
162
+ </div>
163
+ <div className="text-xl md:text-2xl font-bold text-white">{stats.thisWeek}</div>
164
+ </div>
165
+ <div className="bg-white/5 border border-white/10 rounded-xl p-3 md:p-4">
166
+ <div className="flex items-center gap-2 text-slate-400 text-xs md:text-sm mb-1">
167
+ <TrendingUp className="w-3.5 h-3.5" />
168
+ <span>Месяц</span>
169
+ </div>
170
+ <div className="text-xl md:text-2xl font-bold text-white">{stats.thisMonth}</div>
171
+ </div>
172
  </div>
173
  </div>
174
 
175
+ {/* Content Grid */}
176
  <div className="flex-1 grid grid-cols-1 lg:grid-cols-12 gap-4 md:gap-6 min-h-0">
177
+ {/* Left: Main Calendar */}
 
178
  <div className="lg:col-span-8 h-full flex flex-col min-h-0">
179
  {isLoading ? (
180
  <div className="flex-1 flex items-center justify-center bg-surface-elevated border border-white/5 rounded-xl md:rounded-3xl min-h-[400px]">
 
186
  selectedDate={selectedDate}
187
  onSelectDate={handleDateSelect}
188
  onSelectAppointment={setSelectedAppointment}
189
+ workingDays={bookingSettings.working_days}
190
+ workingHours={bookingSettings.working_hours}
191
  />
192
  )}
193
  </div>
194
 
195
+ {/* Right: Details Panel */}
196
  <div className="hidden lg:block lg:col-span-4 h-full min-h-0">
197
  <AppointmentDetails
198
  appointment={selectedAppointment}
 
221
  className="absolute bottom-0 left-0 right-0 max-h-[80vh] overflow-y-auto rounded-t-3xl"
222
  onClick={(e) => e.stopPropagation()}
223
  >
 
224
  <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">
225
  <button onClick={handleCloseDetails} className="p-2 hover:bg-white/10 rounded-lg">
226
  <X className="w-5 h-5 text-slate-400" />
 
239
  </motion.div>
240
  )}
241
  </AnimatePresence>
242
+
243
+ {/* Create Appointment Modal */}
244
+ <AnimatePresence>
245
+ {showCreateModal && (
246
+ <CreateAppointmentModal
247
+ onClose={() => setShowCreateModal(false)}
248
+ onSuccess={handleCreateSuccess}
249
+ services={services}
250
+ bookingSettings={bookingSettings}
251
+ />
252
+ )}
253
+ </AnimatePresence>
254
  </div>
255
  </div>
256
  )
frontend/app/channels/page.tsx CHANGED
@@ -9,7 +9,7 @@ import { Loader2, CheckCircle2, AlertCircle, X, ExternalLink, Settings2, Key, Sm
9
  import { motion, AnimatePresence } from 'framer-motion'
10
  import { cn } from '@/lib/utils'
11
  import { useTranslation } from '@/lib/i18n'
12
- import GoogleSheetsCard from '@/components/GoogleSheetsCard'
13
 
14
  // Types
15
  type ChannelType = 'whatsapp' | 'instagram' | 'telegram'
@@ -196,8 +196,7 @@ export default function ChannelsPage() {
196
  </div>
197
  </div>
198
 
199
- {/* Google Sheets Integration */}
200
- <GoogleSheetsCard className="mt-6" />
201
 
202
  </div>
203
  </div>
 
9
  import { motion, AnimatePresence } from 'framer-motion'
10
  import { cn } from '@/lib/utils'
11
  import { useTranslation } from '@/lib/i18n'
12
+
13
 
14
  // Types
15
  type ChannelType = 'whatsapp' | 'instagram' | 'telegram'
 
196
  </div>
197
  </div>
198
 
199
+
 
200
 
201
  </div>
202
  </div>
frontend/components/bookings/CalendarView.tsx CHANGED
@@ -1,7 +1,7 @@
1
  'use client'
2
 
3
  import { useState, useEffect } from 'react'
4
- import { startOfMonth, endOfMonth, eachDayOfInterval, format, isSameMonth, isToday, isSameDay, startOfWeek, endOfWeek, addMonths, subMonths } from 'date-fns'
5
  import { ru } from 'date-fns/locale'
6
  import { cn } from '@/lib/utils'
7
  import { ChevronLeft, ChevronRight, Calendar as CalendarIcon } from 'lucide-react'
@@ -11,9 +11,23 @@ interface CalendarViewProps {
11
  selectedDate: Date
12
  onSelectDate: (date: Date) => void
13
  onSelectAppointment?: (appointment: any) => void
 
 
14
  }
15
 
16
- export function CalendarView({ appointments, selectedDate, onSelectDate, onSelectAppointment }: CalendarViewProps) {
 
 
 
 
 
 
 
 
 
 
 
 
17
  const [currentMonth, setCurrentMonth] = useState(new Date())
18
  const [isMobile, setIsMobile] = useState(false)
19
 
@@ -98,6 +112,10 @@ export function CalendarView({ appointments, selectedDate, onSelectDate, onSelec
98
  const isCurrentMonth = isSameMonth(day, currentMonth)
99
  const isDayToday = isToday(day)
100
 
 
 
 
 
101
  // Show ALL appointments for selected day, limited for others
102
  const maxVisibleAppointments = isSelected ? 100 : (isMobile ? 1 : 2)
103
  const visibleAppointments = dayAppointments.slice(0, maxVisibleAppointments)
@@ -108,10 +126,12 @@ export function CalendarView({ appointments, selectedDate, onSelectDate, onSelec
108
  key={day.toString()}
109
  onClick={() => handleDateSelect(day)}
110
  className={cn(
111
- "bg-[#1E1F2E] p-1 md:p-2 transition-all cursor-pointer relative group hover:bg-[#252636]",
112
  !isSelected && "min-h-[60px] md:min-h-[100px] lg:min-h-[120px]",
113
  isSelected && "min-h-[80px] md:min-h-[120px]",
114
- !isCurrentMonth && "bg-[#1E1F2E]/50 opacity-50",
 
 
115
  isSelected && "bg-[#2A2B3D] ring-2 ring-inset ring-indigo-500/70 z-10"
116
  )}
117
  >
 
1
  'use client'
2
 
3
  import { useState, useEffect } from 'react'
4
+ import { startOfMonth, endOfMonth, eachDayOfInterval, format, isSameMonth, isToday, isSameDay, startOfWeek, endOfWeek, addMonths, subMonths, getDay } from 'date-fns'
5
  import { ru } from 'date-fns/locale'
6
  import { cn } from '@/lib/utils'
7
  import { ChevronLeft, ChevronRight, Calendar as CalendarIcon } from 'lucide-react'
 
11
  selectedDate: Date
12
  onSelectDate: (date: Date) => void
13
  onSelectAppointment?: (appointment: any) => void
14
+ workingDays?: string[]
15
+ workingHours?: { start: string; end: string }
16
  }
17
 
18
+ // Map day index (0=Sunday) to day code
19
+ const DAY_INDEX_TO_CODE: Record<number, string> = {
20
+ 0: 'sun', 1: 'mon', 2: 'tue', 3: 'wed', 4: 'thu', 5: 'fri', 6: 'sat'
21
+ }
22
+
23
+ export function CalendarView({
24
+ appointments,
25
+ selectedDate,
26
+ onSelectDate,
27
+ onSelectAppointment,
28
+ workingDays = ['mon', 'tue', 'wed', 'thu', 'fri'],
29
+ workingHours = { start: '09:00', end: '18:00' }
30
+ }: CalendarViewProps) {
31
  const [currentMonth, setCurrentMonth] = useState(new Date())
32
  const [isMobile, setIsMobile] = useState(false)
33
 
 
112
  const isCurrentMonth = isSameMonth(day, currentMonth)
113
  const isDayToday = isToday(day)
114
 
115
+ // Check if this day is a working day
116
+ const dayCode = DAY_INDEX_TO_CODE[getDay(day)]
117
+ const isWorkingDay = workingDays.includes(dayCode)
118
+
119
  // Show ALL appointments for selected day, limited for others
120
  const maxVisibleAppointments = isSelected ? 100 : (isMobile ? 1 : 2)
121
  const visibleAppointments = dayAppointments.slice(0, maxVisibleAppointments)
 
126
  key={day.toString()}
127
  onClick={() => handleDateSelect(day)}
128
  className={cn(
129
+ "p-1 md:p-2 transition-all cursor-pointer relative group",
130
  !isSelected && "min-h-[60px] md:min-h-[100px] lg:min-h-[120px]",
131
  isSelected && "min-h-[80px] md:min-h-[120px]",
132
+ // Working vs non-working day background
133
+ isWorkingDay ? "bg-[#1E1F2E] hover:bg-[#252636]" : "bg-[#16171f] hover:bg-[#1a1b24]",
134
+ !isCurrentMonth && "opacity-50",
135
  isSelected && "bg-[#2A2B3D] ring-2 ring-inset ring-indigo-500/70 z-10"
136
  )}
137
  >
frontend/components/bookings/CreateAppointmentModal.tsx ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use client'
2
+
3
+ import { useState } from 'react'
4
+ import { motion } from 'framer-motion'
5
+ import { X, Loader2, Calendar, Clock, User, Phone, Mail, FileText } from 'lucide-react'
6
+ import { bookingsApi } from '@/lib/api'
7
+ import { useToast } from '@/contexts/ToastContext'
8
+ import { format, addDays, setHours, setMinutes, parse } from 'date-fns'
9
+ import { ru } from 'date-fns/locale'
10
+
11
+ interface CreateAppointmentModalProps {
12
+ onClose: () => void
13
+ onSuccess: () => void
14
+ services: any[]
15
+ bookingSettings: {
16
+ working_days: string[]
17
+ working_hours: { start: string; end: string }
18
+ slot_duration: number
19
+ timezone?: string
20
+ }
21
+ }
22
+
23
+ export function CreateAppointmentModal({
24
+ onClose,
25
+ onSuccess,
26
+ services,
27
+ bookingSettings
28
+ }: CreateAppointmentModalProps) {
29
+ const toast = useToast()
30
+ const [loading, setLoading] = useState(false)
31
+
32
+ const [formData, setFormData] = useState({
33
+ date: format(new Date(), 'yyyy-MM-dd'),
34
+ time: bookingSettings.working_hours?.start || '09:00',
35
+ serviceId: services[0]?.id || '',
36
+ clientName: '',
37
+ clientPhone: '',
38
+ clientEmail: '',
39
+ notes: ''
40
+ })
41
+
42
+ // Generate time slots based on working hours and slot duration
43
+ const generateTimeSlots = () => {
44
+ const slots: string[] = []
45
+ const startHour = parseInt(bookingSettings.working_hours?.start?.split(':')[0] || '9')
46
+ const endHour = parseInt(bookingSettings.working_hours?.end?.split(':')[0] || '18')
47
+ const duration = bookingSettings.slot_duration || 30
48
+
49
+ for (let hour = startHour; hour < endHour; hour++) {
50
+ for (let minute = 0; minute < 60; minute += duration) {
51
+ slots.push(`${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`)
52
+ }
53
+ }
54
+ return slots
55
+ }
56
+
57
+ const timeSlots = generateTimeSlots()
58
+
59
+ const handleSubmit = async (e: React.FormEvent) => {
60
+ e.preventDefault()
61
+
62
+ if (!formData.clientName.trim()) {
63
+ toast.error('Введите имя клиента')
64
+ return
65
+ }
66
+
67
+ setLoading(true)
68
+ try {
69
+ // Parse date and time
70
+ const [year, month, day] = formData.date.split('-').map(Number)
71
+ const [hour, minute] = formData.time.split(':').map(Number)
72
+
73
+ const startTime = new Date(year, month - 1, day, hour, minute)
74
+ const selectedService = services.find(s => s.id === formData.serviceId)
75
+ const durationMinutes = selectedService?.duration_minutes || bookingSettings.slot_duration || 30
76
+ const endTime = new Date(startTime.getTime() + durationMinutes * 60 * 1000)
77
+
78
+ await bookingsApi.createAppointment({
79
+ service_id: formData.serviceId || undefined,
80
+ start_time: startTime.toISOString(),
81
+ end_time: endTime.toISOString(),
82
+ notes: formData.notes || undefined,
83
+ customer_name: formData.clientName,
84
+ customer_phone: formData.clientPhone || undefined,
85
+ customer_email: formData.clientEmail || undefined
86
+ })
87
+
88
+ toast.success('Запись создана!')
89
+ onSuccess()
90
+ } catch (error: any) {
91
+ console.error('Create appointment error:', error)
92
+ toast.error(error.response?.data?.detail || 'Ошибка создания записи')
93
+ } finally {
94
+ setLoading(false)
95
+ }
96
+ }
97
+
98
+ return (
99
+ <motion.div
100
+ initial={{ opacity: 0 }}
101
+ animate={{ opacity: 1 }}
102
+ exit={{ opacity: 0 }}
103
+ className="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4"
104
+ onClick={onClose}
105
+ >
106
+ <motion.div
107
+ initial={{ scale: 0.95, opacity: 0 }}
108
+ animate={{ scale: 1, opacity: 1 }}
109
+ exit={{ scale: 0.95, opacity: 0 }}
110
+ className="bg-[#1E1F2E] rounded-2xl w-full max-w-md border border-white/10 shadow-xl"
111
+ onClick={(e) => e.stopPropagation()}
112
+ >
113
+ {/* Header */}
114
+ <div className="flex items-center justify-between p-4 border-b border-white/10">
115
+ <h2 className="text-lg font-bold text-white">Новая запись</h2>
116
+ <button
117
+ onClick={onClose}
118
+ className="p-2 hover:bg-white/10 rounded-lg transition-colors"
119
+ >
120
+ <X className="w-5 h-5 text-slate-400" />
121
+ </button>
122
+ </div>
123
+
124
+ {/* Form */}
125
+ <form onSubmit={handleSubmit} className="p-4 space-y-4">
126
+ {/* Date & Time */}
127
+ <div className="grid grid-cols-2 gap-3">
128
+ <div>
129
+ <label className="text-xs font-medium text-slate-400 mb-1 block">
130
+ <Calendar className="w-3.5 h-3.5 inline mr-1" />
131
+ Дата
132
+ </label>
133
+ <input
134
+ type="date"
135
+ value={formData.date}
136
+ onChange={(e) => setFormData({ ...formData, date: e.target.value })}
137
+ className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
138
+ />
139
+ </div>
140
+ <div>
141
+ <label className="text-xs font-medium text-slate-400 mb-1 block">
142
+ <Clock className="w-3.5 h-3.5 inline mr-1" />
143
+ Время
144
+ </label>
145
+ <select
146
+ value={formData.time}
147
+ onChange={(e) => setFormData({ ...formData, time: e.target.value })}
148
+ className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
149
+ >
150
+ {timeSlots.map(slot => (
151
+ <option key={slot} value={slot}>{slot}</option>
152
+ ))}
153
+ </select>
154
+ </div>
155
+ </div>
156
+
157
+ {/* Service */}
158
+ {services.length > 0 && (
159
+ <div>
160
+ <label className="text-xs font-medium text-slate-400 mb-1 block">Услуга</label>
161
+ <select
162
+ value={formData.serviceId}
163
+ onChange={(e) => setFormData({ ...formData, serviceId: e.target.value })}
164
+ className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
165
+ >
166
+ <option value="">Без услуги</option>
167
+ {services.map((service: any) => (
168
+ <option key={service.id} value={service.id}>
169
+ {service.name} ({service.duration_minutes} мин)
170
+ </option>
171
+ ))}
172
+ </select>
173
+ </div>
174
+ )}
175
+
176
+ {/* Client Name */}
177
+ <div>
178
+ <label className="text-xs font-medium text-slate-400 mb-1 block">
179
+ <User className="w-3.5 h-3.5 inline mr-1" />
180
+ Имя клиента *
181
+ </label>
182
+ <input
183
+ type="text"
184
+ value={formData.clientName}
185
+ onChange={(e) => setFormData({ ...formData, clientName: e.target.value })}
186
+ placeholder="Иван Иванов"
187
+ className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
188
+ />
189
+ </div>
190
+
191
+ {/* Phone & Email */}
192
+ <div className="grid grid-cols-2 gap-3">
193
+ <div>
194
+ <label className="text-xs font-medium text-slate-400 mb-1 block">
195
+ <Phone className="w-3.5 h-3.5 inline mr-1" />
196
+ Телефон
197
+ </label>
198
+ <input
199
+ type="tel"
200
+ value={formData.clientPhone}
201
+ onChange={(e) => setFormData({ ...formData, clientPhone: e.target.value })}
202
+ placeholder="+7 999 123 45 67"
203
+ className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
204
+ />
205
+ </div>
206
+ <div>
207
+ <label className="text-xs font-medium text-slate-400 mb-1 block">
208
+ <Mail className="w-3.5 h-3.5 inline mr-1" />
209
+ Email
210
+ </label>
211
+ <input
212
+ type="email"
213
+ value={formData.clientEmail}
214
+ onChange={(e) => setFormData({ ...formData, clientEmail: e.target.value })}
215
+ placeholder="email@example.com"
216
+ className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
217
+ />
218
+ </div>
219
+ </div>
220
+
221
+ {/* Notes */}
222
+ <div>
223
+ <label className="text-xs font-medium text-slate-400 mb-1 block">
224
+ <FileText className="w-3.5 h-3.5 inline mr-1" />
225
+ Заметки
226
+ </label>
227
+ <textarea
228
+ value={formData.notes}
229
+ onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
230
+ placeholder="Дополнительная информация..."
231
+ rows={2}
232
+ className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 resize-none"
233
+ />
234
+ </div>
235
+
236
+ {/* Submit */}
237
+ <button
238
+ type="submit"
239
+ disabled={loading}
240
+ className="w-full py-3 bg-indigo-600 text-white font-bold rounded-xl hover:bg-indigo-700 transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
241
+ >
242
+ {loading ? (
243
+ <>
244
+ <Loader2 className="w-4 h-4 animate-spin" />
245
+ Создание...
246
+ </>
247
+ ) : (
248
+ 'Создать запись'
249
+ )}
250
+ </button>
251
+ </form>
252
+ </motion.div>
253
+ </motion.div>
254
+ )
255
+ }