Spaces:
Sleeping

axeronis commited on
Commit
89a38ed
·
1 Parent(s): e3cd75f

fix: booking panel - dynamic date, working buttons, PATCH API

Browse files
backend/app/api/bookings.py CHANGED
@@ -87,6 +87,38 @@ async def cancel_appointment(
87
  return {"ok": True}
88
 
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  # -----------------------------------------------------------------------------
91
  # SERVICES
92
  # -----------------------------------------------------------------------------
 
87
  return {"ok": True}
88
 
89
 
90
+ from pydantic import BaseModel
91
+
92
+ class AppointmentUpdateRequest(BaseModel):
93
+ status: Optional[str] = None
94
+ notes: Optional[str] = None
95
+
96
+ @router.patch("/{appointment_id}")
97
+ async def update_appointment(
98
+ appointment_id: UUID,
99
+ update_data: AppointmentUpdateRequest,
100
+ session: AsyncSession = Depends(get_session),
101
+ current_user: User = Depends(get_current_user)
102
+ ):
103
+ """Update appointment status or notes."""
104
+ appointment = await session.get(Appointment, appointment_id)
105
+ if not appointment or appointment.tenant_id != current_user.tenant_id:
106
+ raise HTTPException(status_code=404, detail="Appointment not found")
107
+
108
+ if update_data.status:
109
+ try:
110
+ appointment.status = AppointmentStatus(update_data.status)
111
+ except ValueError:
112
+ raise HTTPException(status_code=400, detail=f"Invalid status: {update_data.status}")
113
+
114
+ if update_data.notes is not None:
115
+ appointment.notes = update_data.notes
116
+
117
+ session.add(appointment)
118
+ await session.commit()
119
+ await session.refresh(appointment)
120
+ return appointment
121
+
122
  # -----------------------------------------------------------------------------
123
  # SERVICES
124
  # -----------------------------------------------------------------------------
frontend/components/bookings/AppointmentDetails.tsx CHANGED
@@ -1,16 +1,22 @@
1
  'use client'
2
 
3
- import { format } from 'date-fns'
4
  import { ru } from 'date-fns/locale'
5
  import { User, Phone, Mail, Clock, Calendar, CheckCircle2, Circle, XCircle, AlertCircle, FileText } from 'lucide-react'
6
  import { cn } from '@/lib/utils'
 
 
7
 
8
  interface AppointmentDetailsProps {
9
  appointment: any
10
  onClose?: () => void
 
11
  }
12
 
13
- export function AppointmentDetails({ appointment, onClose }: AppointmentDetailsProps) {
 
 
 
14
  if (!appointment) {
15
  return (
16
  <div className="h-full bg-[#1E1F2E] border border-white/5 rounded-3xl p-8 flex flex-col items-center justify-center text-center shadow-2xl">
@@ -25,9 +31,27 @@ export function AppointmentDetails({ appointment, onClose }: AppointmentDetailsP
25
  )
26
  }
27
 
28
- const { lead, service, start_time, status, notes } = appointment
29
  const startDate = new Date(start_time)
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  const statusConfig = {
32
  'scheduled': { label: 'Запланировано', color: 'text-indigo-400', bg: 'bg-indigo-500/10', border: 'border-indigo-500/20', icon: Circle },
33
  'completed': { label: 'Завершено', color: 'text-emerald-400', bg: 'bg-emerald-500/10', border: 'border-emerald-500/20', icon: CheckCircle2 },
@@ -38,24 +62,53 @@ export function AppointmentDetails({ appointment, onClose }: AppointmentDetailsP
38
  const currentStatus = statusConfig[status as keyof typeof statusConfig] || statusConfig['scheduled']
39
  const StatusIcon = currentStatus.icon
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  return (
42
  <div className="h-full bg-[#1E1F2E] border border-white/5 rounded-3xl p-6 shadow-2xl flex flex-col gap-6 overflow-y-auto">
43
  {/* Header / Client Info */}
44
  <div className="bg-white/5 rounded-2xl p-5 border border-white/5">
45
  <div className="flex items-center gap-4 mb-4">
46
  <div className="w-14 h-14 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center text-white text-xl font-bold shadow-lg shadow-indigo-500/20">
47
- {lead?.name?.charAt(0) || 'C'}
48
  </div>
49
  <div>
50
- <h2 className="text-xl font-bold text-white mb-1">{lead?.name || 'Клиент'}</h2>
51
- <span className="text-sm text-slate-400">Последнее сообщение: Вчера</span>
52
  </div>
53
  </div>
54
 
55
  <div className="space-y-3 pt-2">
56
  <div className="flex items-center gap-3 text-sm text-slate-300">
57
  <User className="w-4 h-4 text-slate-500" />
58
- <span>{lead?.name || 'Не указано'}</span>
59
  </div>
60
  {lead?.phone && (
61
  <div className="flex items-center gap-3 text-sm text-slate-300">
@@ -106,9 +159,15 @@ export function AppointmentDetails({ appointment, onClose }: AppointmentDetailsP
106
  <StatusIcon className="w-4 h-4" />
107
  {currentStatus.label}
108
  </span>
109
- <button className="text-xs text-slate-400 hover:text-white transition-colors underline">
110
- Изменить
111
- </button>
 
 
 
 
 
 
112
  </div>
113
  </div>
114
 
@@ -116,14 +175,23 @@ export function AppointmentDetails({ appointment, onClose }: AppointmentDetailsP
116
  <div className="h-px w-full bg-white/10 my-2" />
117
 
118
  {/* Actions */}
119
- <div className="grid grid-cols-2 gap-3 mt-auto">
120
- <button className="p-3 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-white text-sm font-medium transition-all">
121
- Перенести
122
- </button>
123
- <button 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">
124
- Отменить
125
- </button>
126
- </div>
 
 
 
 
 
 
 
 
 
127
  </div>
128
  )
129
  }
 
1
  'use client'
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 } from 'lucide-react'
6
  import { cn } from '@/lib/utils'
7
+ import { useState } from 'react'
8
+ import { useToast } from '@/components/ui/use-toast'
9
 
10
  interface AppointmentDetailsProps {
11
  appointment: any
12
  onClose?: () => void
13
+ onStatusChange?: (appointmentId: string, newStatus: string) => void
14
  }
15
 
16
+ export function AppointmentDetails({ appointment, onClose, onStatusChange }: AppointmentDetailsProps) {
17
+ const { showSuccess, showError } = useToast()
18
+ const [isUpdating, setIsUpdating] = useState(false)
19
+
20
  if (!appointment) {
21
  return (
22
  <div className="h-full bg-[#1E1F2E] border border-white/5 rounded-3xl p-8 flex flex-col items-center justify-center text-center shadow-2xl">
 
31
  )
32
  }
33
 
34
+ const { id, lead, service, start_time, status, notes } = appointment
35
  const startDate = new Date(start_time)
36
 
37
+ // Extract client name from notes if lead.name is missing
38
+ // Notes format: "ClientName | Topic"
39
+ const extractedName = notes?.split('|')?.[0]?.trim()
40
+ const clientName = lead?.name || extractedName || 'Клиент'
41
+ const clientInitial = clientName.charAt(0).toUpperCase()
42
+
43
+ // Dynamic last message time
44
+ const getLastMessageText = () => {
45
+ const lastActivity = lead?.updated_at ? new Date(lead.updated_at) : startDate
46
+ if (isToday(lastActivity)) {
47
+ return `Сегодня в ${format(lastActivity, 'HH:mm')}`
48
+ } else if (isYesterday(lastActivity)) {
49
+ return `Вчера в ${format(lastActivity, 'HH:mm')}`
50
+ } else {
51
+ return formatDistanceToNow(lastActivity, { addSuffix: true, locale: ru })
52
+ }
53
+ }
54
+
55
  const statusConfig = {
56
  'scheduled': { label: 'Запланировано', color: 'text-indigo-400', bg: 'bg-indigo-500/10', border: 'border-indigo-500/20', icon: Circle },
57
  'completed': { label: 'Завершено', color: 'text-emerald-400', bg: 'bg-emerald-500/10', border: 'border-emerald-500/20', icon: CheckCircle2 },
 
62
  const currentStatus = statusConfig[status as keyof typeof statusConfig] || statusConfig['scheduled']
63
  const StatusIcon = currentStatus.icon
64
 
65
+ const handleStatusChange = async (newStatus: string) => {
66
+ if (isUpdating) return
67
+ setIsUpdating(true)
68
+ try {
69
+ const token = localStorage.getItem('access_token')
70
+ const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/bookings/${id}`, {
71
+ method: 'PATCH',
72
+ headers: {
73
+ 'Content-Type': 'application/json',
74
+ 'Authorization': `Bearer ${token}`
75
+ },
76
+ body: JSON.stringify({ status: newStatus })
77
+ })
78
+ if (response.ok) {
79
+ showSuccess('Статус обновлён')
80
+ onStatusChange?.(id, newStatus)
81
+ } else {
82
+ showError('Ошибка обновления статуса')
83
+ }
84
+ } catch (error) {
85
+ showError('Ошибка сети')
86
+ } finally {
87
+ setIsUpdating(false)
88
+ }
89
+ }
90
+
91
+ const handleCancel = () => handleStatusChange('cancelled')
92
+ const handleComplete = () => handleStatusChange('completed')
93
+
94
  return (
95
  <div className="h-full bg-[#1E1F2E] border border-white/5 rounded-3xl p-6 shadow-2xl flex flex-col gap-6 overflow-y-auto">
96
  {/* Header / Client Info */}
97
  <div className="bg-white/5 rounded-2xl p-5 border border-white/5">
98
  <div className="flex items-center gap-4 mb-4">
99
  <div className="w-14 h-14 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center text-white text-xl font-bold shadow-lg shadow-indigo-500/20">
100
+ {clientInitial}
101
  </div>
102
  <div>
103
+ <h2 className="text-xl font-bold text-white mb-1">{clientName}</h2>
104
+ <span className="text-sm text-slate-400">{getLastMessageText()}</span>
105
  </div>
106
  </div>
107
 
108
  <div className="space-y-3 pt-2">
109
  <div className="flex items-center gap-3 text-sm text-slate-300">
110
  <User className="w-4 h-4 text-slate-500" />
111
+ <span>{clientName}</span>
112
  </div>
113
  {lead?.phone && (
114
  <div className="flex items-center gap-3 text-sm text-slate-300">
 
159
  <StatusIcon className="w-4 h-4" />
160
  {currentStatus.label}
161
  </span>
162
+ {status === 'scheduled' && (
163
+ <button
164
+ onClick={handleComplete}
165
+ disabled={isUpdating}
166
+ className="text-xs text-emerald-400 hover:text-emerald-300 transition-colors underline disabled:opacity-50"
167
+ >
168
+ Завершить
169
+ </button>
170
+ )}
171
  </div>
172
  </div>
173
 
 
175
  <div className="h-px w-full bg-white/10 my-2" />
176
 
177
  {/* Actions */}
178
+ {status === 'scheduled' && (
179
+ <div className="grid grid-cols-2 gap-3 mt-auto">
180
+ <button
181
+ onClick={() => showSuccess('Функция переноса в разработке')}
182
+ className="p-3 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-white text-sm font-medium transition-all"
183
+ >
184
+ Перенести
185
+ </button>
186
+ <button
187
+ onClick={handleCancel}
188
+ disabled={isUpdating}
189
+ 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"
190
+ >
191
+ {isUpdating ? 'Отмена...' : 'Отменить'}
192
+ </button>
193
+ </div>
194
+ )}
195
  </div>
196
  )
197
  }