-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtemp_original_beosztas.tsx
More file actions
1439 lines (1329 loc) · 139 KB
/
temp_original_beosztas.tsx
File metadata and controls
1439 lines (1329 loc) · 139 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use client"
import { useState, useMemo, use, useEffect } from "react"
import { AppSidebar } from "@/components/app-sidebar"
import { SiteHeader } from "@/components/site-header"
import { useApiQuery, useApiMutation } from "@/lib/api-helpers"
import { apiClient } from "@/lib/api"
import { useAuth } from "@/contexts/auth-context"
import { usePermissions } from "@/contexts/permissions-context"
import type { SzerepkorSchema, BeosztasWithAvailabilitySchema } from "@/lib/types"
import { ApiErrorBoundary } from "@/components/api-error-boundary"
import { ApiErrorFallback } from "@/components/api-error-fallback"
import { StabBadge, UserStabBadge } from "@/components/stab-badge"
import { UserAvatar } from "@/components/user-avatar"
import { RemoveStudentConfirmation } from "@/components/remove-student-confirmation"
import {
SidebarInset,
SidebarProvider,
} from "@/components/ui/sidebar"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator"
import { toast } from "sonner"
import {
Calendar,
MapPin,
Clock,
Users,
ArrowLeft,
Edit,
Loader2,
Save,
X,
Settings,
UserPlus,
Search,
Filter,
CheckCircle,
AlertCircle,
Info,
CheckSquare,
Square,
} from "lucide-react"
import Link from "next/link"
import { format } from "date-fns"
import { hu } from "date-fns/locale"
import { notFound } from "next/navigation"
interface PageProps {
params: Promise<{
id: string
}>
}
// Date helper for better formatting
const formatSessionDate = (dateStr: string) => {
try {
const date = new Date(dateStr)
return format(date, 'yyyy. MMMM dd. (EEEE)', { locale: hu })
} catch {
return dateStr
}
}
// Time helper
const formatTime = (timeStr: string) => {
try {
const [hours, minutes] = timeStr.split(':')
return `${hours}:${minutes}`
} catch {
return timeStr
}
}
interface CrewMember {
id: number
name: string
role: string
roleId: number
class: string
stab: string
phone?: string
email?: string
firstName?: string
lastName?: string
username?: string
}
// Helper component for availability status with enhanced details
const AvailabilityIndicator = ({ userId, availabilityData, showInEditMode = false }: {
userId: number,
availabilityData: BeosztasWithAvailabilitySchema['user_availability'] | undefined,
showInEditMode?: boolean
}) => {
if (!availabilityData) return null
// Find user in availability data
const userAvailable = availabilityData.users_available?.find((u) => u.user.id === userId)
const userOnVacation = availabilityData.users_on_vacation?.find((u) => u.user.id === userId)
const userWithRadio = availabilityData.users_with_radio_session?.find((u) => u.user.id === userId)
// Check for conflicts in available users too
const conflicts = userOnVacation?.availability?.conflicts || userWithRadio?.availability?.conflicts || userAvailable?.availability?.conflicts || []
const hasConflicts = conflicts.length > 0
if (userOnVacation) {
const vacationConflict = conflicts.find((c) => c.type === 'vacation')
const tooltipText = vacationConflict && vacationConflict.start_date && vacationConflict.end_date
? `T├ívoll├ęt: ${vacationConflict.reason}\n${new Date(vacationConflict.start_date).toLocaleDateString('hu-HU')} - ${new Date(vacationConflict.end_date).toLocaleDateString('hu-HU')}`
: 'Szabadság'
return (
<div className={`flex items-center gap-1 ${showInEditMode ? 'px-2 py-1 rounded-md bg-orange-500/10 border border-orange-500/20' : ''}`} title={tooltipText}>
<AlertCircle className="h-4 w-4 text-orange-500" />
<span className="text-xs font-medium text-orange-600">T├ívoll├ęt</span>
</div>
)
}
if (userWithRadio) {
const radioConflict = conflicts.find((c) => c.type === 'radio_session')
const tooltipText = radioConflict && radioConflict.date
? `R├ídi├│s ├Âsszej├ítsz├ís: ${radioConflict.radio_stab}\n${radioConflict.date} ${radioConflict.time_from} - ${radioConflict.time_to}`
: 'Rádió'
return (
<div className={`flex items-center gap-1 ${showInEditMode ? 'px-2 py-1 rounded-md bg-blue-500/10 border border-blue-500/20' : ''}`} title={tooltipText}>
<AlertCircle className="h-4 w-4 text-blue-500" />
<span className="text-xs font-medium text-blue-600">Rádiós</span>
</div>
)
}
if (userAvailable && !hasConflicts) {
return (
<div className={`flex items-center gap-1 ${showInEditMode ? 'px-2 py-1 rounded-md bg-green-500/10 border border-green-500/20' : ''}`} title="El├ęrhet┼Ĺ">
<CheckCircle className="h-4 w-4 text-green-500" />
<span className="text-xs font-medium text-green-600">El├ęrhet┼Ĺ</span>
</div>
)
}
return null
}
export default function BeosztasDetailPage({ params }: PageProps) {
const { id } = use(params)
const [isEditMode, setIsEditMode] = useState(false)
const [selectedCrewMember, setSelectedCrewMember] = useState<CrewMember | null>(null)
const [searchTerm, setSearchTerm] = useState("")
const [roleFilter, setRoleFilter] = useState<string>("all")
const [stabFilter, setStabFilter] = useState<string>("all")
const [editedCrew, setEditedCrew] = useState<CrewMember[]>([])
const [showAddMemberDialog, setShowAddMemberDialog] = useState(false)
const [selectedNewUser, setSelectedNewUser] = useState<string>("")
const [selectedNewRole, setSelectedNewRole] = useState<string>("")
// Context hooks
const { isAuthenticated } = useAuth()
const { hasPermission } = usePermissions()
// Permission checks
const canEditAssignments = hasPermission('can_manage_forgatas') || hasPermission('is_admin') || hasPermission('is_teacher_admin')
// API queries
const sessionQuery = useApiQuery(
() => isAuthenticated ? apiClient.getFilmingSession(parseInt(id)) : Promise.resolve(null),
[isAuthenticated, id]
)
// Use new availability-aware assignment endpoint
const assignmentQuery = useApiQuery(
() => isAuthenticated ? apiClient.getFilmingAssignmentAvailability(parseInt(id)) : Promise.resolve(null),
[isAuthenticated, id]
)
// Get roles grouped by year for better organization
const rolesQuery = useApiQuery(
() => isAuthenticated ? apiClient.getRoles() : Promise.resolve([]),
[isAuthenticated]
)
const usersQuery = useApiQuery(
() => isAuthenticated ? apiClient.getAllUsersDetailed() : Promise.resolve([]),
[isAuthenticated]
)
// Get role statistics for selected crew member
const userStatsQuery = useApiQuery(
() => {
if (!isAuthenticated || !selectedCrewMember) return Promise.resolve(null)
return apiClient.getUserRoleStatistics(selectedCrewMember.id)
},
[isAuthenticated, selectedCrewMember]
)
const { data: session, loading: sessionLoading, error } = sessionQuery
const { data: assignmentWithAvailability, loading: assignmentLoading } = assignmentQuery
const { data: availableRoles = [], loading: rolesLoading } = rolesQuery
const { data: allUsers = [], loading: usersLoading } = usersQuery
const { data: userStats, loading: userStatsLoading } = userStatsQuery
// Get absences for finalized assignments (after data is available)
const absencesQuery = useApiQuery(
() => {
if (!isAuthenticated || !assignmentWithAvailability?.id || !assignmentWithAvailability?.kesz) return Promise.resolve([])
return apiClient.getFilmingAssignmentAbsences(assignmentWithAvailability.id)
},
[isAuthenticated, assignmentWithAvailability?.id, assignmentWithAvailability?.kesz]
)
const { data: absences = [], loading: absencesLoading } = absencesQuery
// Mutations for marking assignment as done/draft
const markAsDoneMutation = useApiMutation(
(assignmentId: number) => apiClient.markFilmingAssignmentDone(assignmentId)
)
const markAsDraftMutation = useApiMutation(
(assignmentId: number) => apiClient.markFilmingAssignmentDraft(assignmentId)
)
// Handlers for status changes
const handleMarkAsDone = async () => {
if (!assignment?.id) return
try {
// First save any crew changes if in edit mode
if (isEditMode && editedCrew.length !== crew.length ||
isEditMode && editedCrew.some(editedMember =>
!crew.find(originalMember =>
originalMember.id === editedMember.id && originalMember.roleId === editedMember.roleId
)
)) {
// Convert editedCrew to the format expected by the API
const student_role_pairs = editedCrew.map(member => ({
user_id: member.id,
szerepkor_id: member.roleId
}))
await updateAssignmentMutation.execute({
student_role_pairs,
kesz: true // Mark as done
})
toast.success('Beoszt├ís m├│dos├şt├ísai mentve ├ęs lez├írva')
} else {
await markAsDoneMutation.execute(assignment.id)
toast.success('Beosztás sikeresen lezárva')
}
// Refetch the assignment data
window.location.reload() // Simple refresh for now
} catch (error) {
toast.error(`Hiba a beosztás lezárásakor: ${error instanceof Error ? error.message : 'Ismeretlen hiba'}`)
}
}
const handleMarkAsDraft = async () => {
if (!assignment?.id) return
try {
await markAsDraftMutation.execute(assignment.id)
toast.success('Beoszt├ís vissza├íll├ştva m├│dos├şt├ísra')
// Refetch the assignment data
window.location.reload() // Simple refresh for now
} catch (error) {
toast.error(`Hiba a beoszt├ís vissza├íll├şt├ísakor: ${error instanceof Error ? error.message : 'Ismeretlen hiba'}`)
}
}
// Extract assignment from availability data with memoization
const assignment = useMemo(() => {
if (!assignmentWithAvailability) return null
return {
id: assignmentWithAvailability.id,
forgatas: assignmentWithAvailability.forgatas,
szerepkor_relaciok: assignmentWithAvailability.szerepkor_relaciok,
kesz: assignmentWithAvailability.kesz,
author: assignmentWithAvailability.author,
stab: assignmentWithAvailability.stab,
created_at: assignmentWithAvailability.created_at,
student_count: assignmentWithAvailability.student_count,
roles_summary: assignmentWithAvailability.roles_summary
}
}, [assignmentWithAvailability])
// Extract availability data
const availabilityData = useMemo(() =>
assignmentWithAvailability?.user_availability,
[assignmentWithAvailability]
)
// User queries - fetch detailed user info for crew members
const userQueries = useApiQuery(
() => {
if (!isAuthenticated || !assignment?.szerepkor_relaciok) return Promise.resolve([])
return Promise.all(
assignment.szerepkor_relaciok.map((relation: any) => // eslint-disable-line @typescript-eslint/no-explicit-any
apiClient.getUserDetails(relation.user.id)
)
)
},
[isAuthenticated, assignment]
)
const { data: userDetailsList = [], loading: usersDetailsLoading } = userQueries
// Update assignment mutation
const updateAssignmentMutation = useApiMutation(
(data: { student_role_pairs: { user_id: number, szerepkor_id: number }[], kesz?: boolean }) =>
apiClient.updateFilmingAssignment(assignment!.id, data)
)
// Computed values - get crew from assignment with detailed user info
const crew: CrewMember[] = useMemo(() => {
if (!assignment || !assignment.szerepkor_relaciok || !userDetailsList) return []
// Convert role relations to crew members with detailed user info
return assignment.szerepkor_relaciok.map((relation: any) => { // eslint-disable-line @typescript-eslint/no-explicit-any
const userDetails = userDetailsList.find((user: any) => user.id === relation.user.id) // eslint-disable-line @typescript-eslint/no-explicit-any
return {
id: relation.user.id,
name: relation.user.full_name || `${relation.user.last_name} ${relation.user.first_name}`,
role: relation.szerepkor.name,
roleId: relation.szerepkor.id,
class: userDetails?.osztaly_name || 'N/A',
stab: userDetails?.stab_name || 'N/A',
phone: userDetails?.telefonszam || '',
email: userDetails?.email || '',
firstName: relation.user.first_name || userDetails?.first_name || '',
lastName: relation.user.last_name || userDetails?.last_name || '',
username: relation.user.username || userDetails?.username || ''
}
})
}, [assignment, userDetailsList])
// Working crew - either edited crew in edit mode or original crew
const workingCrew = useMemo(() => {
return isEditMode ? editedCrew : crew
}, [isEditMode, editedCrew, crew])
// Initialize edited crew when entering edit mode
useEffect(() => {
if (isEditMode && crew.length > 0) {
setEditedCrew([...crew])
}
}, [isEditMode, crew])
// Available users for adding (exclude current crew members)
const availableUsers = useMemo(() => {
const currentUserIds = workingCrew.map(member => member.id)
return (allUsers || []).filter((user: any) => // eslint-disable-line @typescript-eslint/no-explicit-any
!currentUserIds.includes(user.id) && user.is_active
)
}, [allUsers, workingCrew])
// Filtered crew for display
const filteredCrew = useMemo(() => {
return workingCrew.filter(member => {
const matchesSearch = member.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
member.role.toLowerCase().includes(searchTerm.toLowerCase()) ||
member.class.toLowerCase().includes(searchTerm.toLowerCase())
const matchesRole = roleFilter === "all" || member.role === roleFilter
const matchesStab = stabFilter === "all" || member.stab === stabFilter
return matchesSearch && matchesRole && matchesStab
})
}, [workingCrew, searchTerm, roleFilter, stabFilter])
// Get unique roles and stabs for filtering
const uniqueRoles = useMemo(() => [...new Set(workingCrew.map(member => member.role))], [workingCrew])
const uniqueStabs = useMemo(() => [...new Set(workingCrew.map(member => member.stab))], [workingCrew])
// Crew management functions
const handleRoleChange = (memberId: number, newRoleId: string) => {
const roleId = parseInt(newRoleId)
const role = availableRoles?.find(r => r.id === roleId)
if (!role) return
setEditedCrew(prev => prev.map(member =>
member.id === memberId
? { ...member, roleId, role: role.name }
: member
))
}
const handleRemoveMember = (memberId: number) => {
setEditedCrew(prev => prev.filter(member => member.id !== memberId))
}
// Helper function to check user availability when adding
const checkUserAvailabilityForAdd = async (userId: number) => {
if (!availabilityData || !assignment?.forgatas) {
return { hasConflict: false, message: '' }
}
// Check existing availability data if user is already there
const existingOnVacation = availabilityData.users_on_vacation?.find(u => u.user.id === userId)
const existingWithRadio = availabilityData.users_with_radio_session?.find(u => u.user.id === userId)
if (existingOnVacation) {
const conflicts = existingOnVacation.availability?.conflicts || []
const vacationConflict = conflicts.find((c) => c.type === 'vacation')
return {
hasConflict: true,
message: vacationConflict && vacationConflict.start_date && vacationConflict.end_date
? `T├ívoll├ęt: ${vacationConflict.reason}\n${new Date(vacationConflict.start_date).toLocaleDateString('hu-HU')} - ${new Date(vacationConflict.end_date).toLocaleDateString('hu-HU')}`
: 'A felhasználó távol lesz'
}
}
if (existingWithRadio) {
const conflicts = existingWithRadio.availability?.conflicts || []
const radioConflict = conflicts.find((c) => c.type === 'radio_session')
return {
hasConflict: true,
message: radioConflict ?
`R├ídi├│s ├Âsszej├ítsz├ís: ${radioConflict.radio_stab}\n${radioConflict.date} ${radioConflict.time_from} - ${radioConflict.time_to}` :
'A felhaszn├íl├│ r├ídi├│s ├Âsszej├ítsz├íson vesz r├ęszt'
}
}
// For users not in the current availability data, we could call the API to check
// but for simplicity, we'll assume no conflict
return { hasConflict: false, message: '' }
}
const handleSaveChanges = async () => {
if (!assignment?.id || !isEditMode) return
// Check for conflicts before saving
const membersWithConflicts = editedCrew.filter(member => {
const userOnVacation = availabilityData?.users_on_vacation?.find((u) => u.user.id === member.id)
const userWithRadio = availabilityData?.users_with_radio_session?.find((u) => u.user.id === member.id)
return userOnVacation || userWithRadio
})
if (membersWithConflicts.length > 0) {
const conflictDetails = membersWithConflicts.map(m => {
const userOnVacation = availabilityData?.users_on_vacation?.find((u) => u.user.id === m.id)
const userWithRadio = availabilityData?.users_with_radio_session?.find((u) => u.user.id === m.id)
let conflictType = ''
if (userOnVacation) conflictType = 'T├ívoll├ęt'
else if (userWithRadio) conflictType = 'R├ídi├│s ├Âsszej├ítsz├ís'
return `${m.name} - ${conflictType}`
}).join('\n')
const confirmSave = window.confirm(
`Figyelem! A k├Âvetkez┼Ĺ st├íbtagoknak konfliktusuk van:\n\n${conflictDetails}\n\nBiztosan v├ęgleges├şted a beoszt├íst ezekkel a konfliktusokkal?`
)
if (!confirmSave) {
return
}
}
try {
console.log('Saving and finalizing assignment...')
console.log('Original crew:', crew)
console.log('Edited crew:', editedCrew)
// Convert editedCrew to the format expected by the API
const student_role_pairs = editedCrew.map(member => ({
user_id: member.id,
szerepkor_id: member.roleId
}))
console.log('Student role pairs to send:', student_role_pairs)
// Save and mark as done (finalize) in one action
const result = await updateAssignmentMutation.execute({
student_role_pairs,
kesz: true // Always finalize on save
})
console.log('Save result:', result)
toast.success('Beoszt├ís sikeresen v├ęgleges├ştve!')
// Refetch the assignment data
window.location.reload() // Simple refresh for now
} catch (error) {
console.error('Save error:', error)
toast.error(`Hiba a ment├ęs sor├ín: ${error instanceof Error ? error.message : 'Ismeretlen hiba'}`)
}
}
const handleAddMember = async () => {
if (!selectedNewUser || !selectedNewRole) return
const userId = parseInt(selectedNewUser)
const roleId = parseInt(selectedNewRole)
const user = availableUsers.find((u: any) => u.id === userId) // eslint-disable-line @typescript-eslint/no-explicit-any
const role = availableRoles?.find(r => r.id === roleId)
if (!user || !role) return
// Check if user has conflicts
const userConflicts = await checkUserAvailabilityForAdd(userId)
if (userConflicts.hasConflict) {
const confirmAdd = window.confirm(
`Figyelem! ${user.full_name || user.username} felhasználónak konfliktusa van:\n\n${userConflicts.message}\n\nBiztosan hozzáadod?`
)
if (!confirmAdd) {
return
}
}
// Get detailed user info
try {
const userDetails = await apiClient.getUserDetails(userId)
const newMember: CrewMember = {
id: user.id,
name: user.full_name || `${user.last_name} ${user.first_name}`,
role: role.name,
roleId: role.id,
class: userDetails?.osztaly_name || 'N/A',
stab: userDetails?.stab_name || 'N/A',
phone: userDetails?.telefonszam || '',
email: userDetails?.email || '',
firstName: user.first_name || userDetails?.first_name || '',
lastName: user.last_name || userDetails?.last_name || '',
username: user.username || userDetails?.username || ''
}
setEditedCrew(prev => [...prev, newMember])
setSelectedNewUser("")
setSelectedNewRole("")
setShowAddMemberDialog(false)
toast.success(`${newMember.name} hozzáadva a stábhoz`)
} catch (error) {
console.error('Failed to add member:', error)
toast.error("Hiba t├Ârt├ęnt a tag hozz├íad├ísa k├Âzben")
}
}
// Loading state
const loading = sessionLoading || assignmentLoading || rolesLoading || usersLoading || usersDetailsLoading
if (loading) {
return (
<SidebarProvider>
<AppSidebar variant="inset" />
<SidebarInset>
<SiteHeader />
<div className="flex items-center justify-center py-12">
<Loader2 className="h-6 w-6 animate-spin mr-2" />
Beoszt├ís bet├Âlt├ęse...
</div>
</SidebarInset>
</SidebarProvider>
)
}
if (error || !session) {
notFound()
}
// Handle save assignment
const handleSaveAssignment = async () => {
if (!assignment) return
try {
// Convert edited crew to student_role_pairs format
const student_role_pairs = workingCrew.map(member => ({
user_id: member.id,
szerepkor_id: member.roleId
}))
await updateAssignmentMutation.execute({
student_role_pairs,
kesz: assignment.kesz
})
toast.success("Beosztás sikeresen mentve!")
setIsEditMode(false)
setEditedCrew([]) // Clear edited crew
// Refresh the data
window.location.reload()
} catch (error) {
console.error('Failed to save assignment:', error)
toast.error("Hiba t├Ârt├ęnt a beoszt├ís ment├ęse k├Âzben")
}
}
// Get assignment status info
const getAssignmentStatusInfo = () => {
if (!assignment) {
return {
status: "missing",
color: "bg-orange-500/10 text-orange-400 border-orange-500/20",
icon: AlertCircle,
text: "Nincs beoszt├ís l├ętrehozva"
}
}
if (assignment.kesz) {
return {
status: "finalized",
color: "bg-green-500/10 text-green-400 border-green-500/20",
icon: CheckCircle,
text: "V├ęgleges beoszt├ís"
}
}
return {
status: "draft",
color: "bg-blue-500/10 text-blue-400 border-blue-500/20",
icon: Info,
text: "Tervezet beosztás"
}
}
const statusInfo = getAssignmentStatusInfo()
const StatusIcon = statusInfo.icon
return (
<ApiErrorBoundary fallback={ApiErrorFallback}>
<SidebarProvider>
<AppSidebar variant="inset" />
<SidebarInset>
<SiteHeader />
<div className="flex-1 space-y-4 md:space-y-6 p-3 sm:p-4 md:p-6 animate-in fade-in-50 duration-500">
{/* Header */}
<div className="space-y-3 sm:space-y-0 sm:flex sm:items-center sm:gap-4">
<Link href={`/app/forgatasok/${id}`} className="inline-block">
<Button variant="outline" size="sm" className="bg-transparent w-full sm:w-auto">
<ArrowLeft className="h-4 w-4 mr-2" />
Vissza a forgatáshoz
</Button>
</Link>
<div className="flex-1 min-w-0">
<div className="flex items-start sm:items-center gap-3 mb-2">
<Users className="h-5 w-5 sm:h-6 sm:w-6 text-purple-400 flex-shrink-0 mt-1 sm:mt-0" />
<div className="min-w-0 flex-1">
<h1 className="text-xl sm:text-2xl md:text-3xl font-bold tracking-tight bg-gradient-to-r from-primary to-primary/70 bg-clip-text text-transparent break-words">
Beosztás - {session.name}
</h1>
</div>
</div>
<p className="text-sm md:text-base text-muted-foreground">St├íb beoszt├ís ├ęs szerepk├Âr├Âk kezel├ęse</p>
</div>
{canEditAssignments && assignment && (
<div className="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
{isEditMode ? (
<>
<Button onClick={handleSaveChanges} disabled={updateAssignmentMutation.loading} className="w-full sm:w-auto">
{updateAssignmentMutation.loading ? (
<Loader2 className="h-4 w-4 animate-spin mr-2" />
) : (
<CheckCircle className="h-4 w-4 mr-2" />
)}
Ment├ęs ├ęs V├ęgleges├şt├ęs
</Button>
<Button variant="outline" onClick={() => {
setIsEditMode(false)
setEditedCrew([]) // Reset edited crew
}} className="w-full sm:w-auto">
<X className="h-4 w-4 mr-2" />
M├ęgse
</Button>
</>
) : (
// Only show edit button if assignment is not marked as done
!assignment.kesz && (
<Button onClick={() => setIsEditMode(true)} className="w-full sm:w-auto">
<Edit className="h-4 w-4 mr-2" />
Szerkeszt├ęs
</Button>
)
)}
</div>
)}
</div>
<div className="grid gap-4 md:gap-6 xl:grid-cols-4">
{/* Main Content */}
<div className="xl:col-span-3 space-y-4 md:space-y-6">
{/* Session Info Summary */}
<Card className="border-border/50 bg-card/50 backdrop-blur-sm">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base sm:text-lg">
<Info className="h-5 w-5 text-blue-400" />
Forgatás Információk
</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4">
<div className="flex items-center gap-3 p-3 rounded-lg bg-background/50 border border-border/50">
<Calendar className="h-4 w-4 text-green-400 flex-shrink-0" />
<div className="min-w-0 flex-1">
<div className="text-sm text-muted-foreground">Dátum</div>
<div className="font-medium text-sm sm:text-base truncate">{formatSessionDate(session.date)}</div>
</div>
</div>
<div className="flex items-center gap-3 p-3 rounded-lg bg-background/50 border border-border/50">
<Clock className="h-4 w-4 text-orange-400 flex-shrink-0" />
<div className="min-w-0 flex-1">
<div className="text-sm text-muted-foreground">Id┼Ĺpont</div>
<div className="font-medium text-sm sm:text-base">
{formatTime(session.time_from)} - {formatTime(session.time_to)}
</div>
</div>
</div>
<div className="flex items-center gap-3 p-3 rounded-lg bg-background/50 border border-border/50 sm:col-span-2 lg:col-span-1">
<MapPin className="h-4 w-4 text-blue-400 flex-shrink-0" />
<div className="min-w-0 flex-1">
<div className="text-sm text-muted-foreground">Helysz├şn</div>
<div className="font-medium text-sm sm:text-base truncate">{session.location?.name || 'Nincs megadva'}</div>
</div>
</div>
</div>
</CardContent>
</Card>
{/* Availability Summary */}
{availabilityData && (
<Card className="border-border/50 bg-card/50 backdrop-blur-sm">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base sm:text-lg">
<Users className="h-5 w-5 text-green-400" />
El├ęrhet┼Ĺs├ęg ├üttekint├ęs
</CardTitle>
<CardDescription className="text-sm">Di├íkok el├ęrhet┼Ĺs├ęge ├ęs konfliktusai</CardDescription>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4">
<div className="flex items-center gap-3 p-3 rounded-lg bg-green-500/10 border border-green-500/30">
<CheckCircle className="h-4 w-4 text-green-400 flex-shrink-0" />
<div className="min-w-0 flex-1">
<div className="text-sm text-muted-foreground">El├ęrhet┼Ĺ</div>
<div className="font-medium text-green-400 text-sm sm:text-base">
{availabilityData.summary.available_count} diák
</div>
</div>
</div>
<div className="flex items-center gap-3 p-3 rounded-lg bg-orange-500/10 border border-orange-500/30">
<AlertCircle className="h-4 w-4 text-orange-400 flex-shrink-0" />
<div className="min-w-0 flex-1">
<div className="text-sm text-muted-foreground">T├ívoll├ęt</div>
<div className="font-medium text-orange-400 text-sm sm:text-base">
{availabilityData.summary.vacation_count} diák
</div>
</div>
</div>
<div className="flex items-center gap-3 p-3 rounded-lg bg-blue-500/10 border border-blue-500/30 sm:col-span-2 lg:col-span-1">
<AlertCircle className="h-4 w-4 text-blue-400 flex-shrink-0" />
<div className="min-w-0 flex-1">
<div className="text-sm text-muted-foreground">Rádiós konfliktus</div>
<div className="font-medium text-blue-400 text-sm sm:text-base">
{availabilityData.summary.radio_session_count} diák
</div>
</div>
</div>
</div>
</CardContent>
</Card>
)}
{/* Assignment Status & Controls */}
<Card className="border-border/50 bg-card/50 backdrop-blur-sm">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base sm:text-lg">
<Settings className="h-5 w-5 text-purple-400" />
Beosztás Állapot
</CardTitle>
</CardHeader>
<CardContent>
<div className={`p-3 rounded-lg border ${statusInfo.color}`}>
<div className="space-y-3 sm:space-y-0 sm:flex sm:items-center sm:justify-between">
<div className="flex items-center gap-2">
<StatusIcon className="h-4 w-4 flex-shrink-0" />
<span className="font-medium text-sm sm:text-base">{statusInfo.text}</span>
{assignment && (
<Badge variant="secondary" className="text-xs">
{crew.length} f┼Ĺ
</Badge>
)}
</div>
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-2">
{assignment?.stab && (
<StabBadge stab={assignment.stab} showMemberCount />
)}
{canEditAssignments && assignment && (
<div className="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
{!isEditMode ? (
// Only show edit button if assignment is not marked as done
!assignment.kesz && (
<Button
onClick={() => setIsEditMode(true)}
variant="outline"
size="sm"
className="flex items-center gap-1 w-full sm:w-auto text-xs sm:text-sm"
>
<Edit className="h-4 w-4" />
Szerkeszt├ęs
</Button>
)
) : (
<Badge variant="outline" className="px-2 py-1 text-xs">
<Edit className="h-3 w-3 mr-1" />
Szerkeszt├ęsi m├│d
</Badge>
)}
{/* Only show mark as done/draft buttons when not in edit mode */}
{!isEditMode && (
<div className="flex gap-2 w-full sm:w-auto">
{assignment.kesz ? (
<Button
onClick={handleMarkAsDraft}
disabled={markAsDraftMutation.loading}
variant="outline"
size="sm"
className="flex items-center gap-1 flex-1 sm:flex-none text-xs sm:text-sm"
>
{markAsDraftMutation.loading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Square className="h-4 w-4" />
)}
M├│dos├şt├ís
</Button>
) : (
<Button
onClick={handleMarkAsDone}
disabled={markAsDoneMutation.loading}
variant="default"
size="sm"
className="flex items-center gap-1 flex-1 sm:flex-none text-xs sm:text-sm"
>
{markAsDoneMutation.loading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<CheckSquare className="h-4 w-4" />
)}
Lezár
</Button>
)}
</div>
)}
</div>
)}
</div>
</div>
{assignment && assignment.roles_summary && assignment.roles_summary.length > 0 && (
<div className="mt-3 flex flex-wrap gap-1">
{assignment.roles_summary.map((role: any, index: number) => ( // eslint-disable-line @typescript-eslint/no-explicit-any
<Badge key={index} variant="outline" className="text-xs">
{role.role}: {role.count}
</Badge>
))}
</div>
)}
</div>
</CardContent>
</Card>
{/* Generated Absences */}
{assignment?.kesz && (
<Card className="border-border/50 bg-card/50 backdrop-blur-sm">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base sm:text-lg">
<Calendar className="h-5 w-5 text-orange-400" />
Automatikusan L├ętrehozott Hi├ínyz├ísok
</CardTitle>
<CardDescription className="text-sm">
A v├ęgleges├ştett beoszt├ís alapj├ín automatikusan l├ętrehozott hi├ínyz├ísok
</CardDescription>
</CardHeader>
<CardContent>
{absencesLoading ? (
<div className="flex items-center justify-center py-4">
<Loader2 className="h-4 w-4 animate-spin mr-2" />
<span className="text-sm text-muted-foreground">Hi├ínyz├ísok bet├Âlt├ęse...</span>
</div>
) : !absences || absences.length === 0 ? (
<div className="text-center py-4 text-muted-foreground">
<AlertCircle className="h-6 w-6 mx-auto mb-2" />
<div className="text-sm">Nincsenek hiányzások</div>
<div className="text-xs">Lehet, hogy m├ęg nem lettek l├ętrehozva</div>
</div>
) : (
<div className="space-y-3">
<div className="text-sm text-muted-foreground mb-3">
{absences.length} hi├ínyz├ís l├ętrehozva {assignment.student_count} di├íkhoz
</div>
<div className="space-y-2 max-h-48 overflow-y-auto">
{absences.map((absence: any) => ( // eslint-disable-line @typescript-eslint/no-explicit-any
<div key={absence.id} className="flex items-start sm:items-center gap-3 p-2 rounded-lg bg-background/50 border border-border/50">
<UserAvatar
email={absence.student.email || ''}
firstName={absence.student.first_name || ''}
lastName={absence.student.last_name || ''}
username={absence.student.username || ''}
customSize={32}
className="border border-border/50 flex-shrink-0"
fallbackClassName="bg-gradient-to-br from-primary/20 to-primary/10 text-xs font-semibold"
/>
<div className="flex-1 min-w-0">
<div className="text-sm font-medium truncate">
{absence.student.full_name || `${absence.student.last_name} ${absence.student.first_name}`}
</div>
<div className="text-xs text-muted-foreground">
{formatTime(absence.time_from)} - {formatTime(absence.time_to)}
</div>
</div>
<div className="flex flex-col sm:flex-row items-end sm:items-center gap-1 sm:gap-2 flex-shrink-0">
<Badge variant={absence.excused ? "default" : absence.unexcused ? "destructive" : "secondary"} className="text-xs">
{absence.excused ? "Igazolt" : absence.unexcused ? "Igazolatlan" : "F├╝gg┼Ĺben"}
</Badge>
{absence.affected_classes && absence.affected_classes.length > 0 && (
<div className="text-xs text-muted-foreground" title={`Érintett órák: ${absence.affected_classes.join(', ')}`}>
{absence.affected_classes.length} ├│ra
</div>
)}
</div>
</div>
))}
</div>
</div>
)}
</CardContent>
</Card>
)}
{/* Crew Management */}
{assignment && (
<Card className="border-border/50 bg-card/50 backdrop-blur-sm">
<CardHeader>
<div className="flex items-center justify-between flex-wrap gap-3">
<div>
<CardTitle className="flex items-center gap-2 text-base sm:text-lg">
<Users className="h-5 w-5 text-purple-400" />
St├íb Beoszt├ís ({filteredCrew.length}/{workingCrew.length} f┼Ĺ)
</CardTitle>
<CardDescription className="text-sm">
Forgat├ísban r├ęsztvev┼Ĺ di├íkok ├ęs szerepk├Âr├╝k
</CardDescription>
</div>
{isEditMode && !assignment.kesz && (
<div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 w-full sm:w-auto">
<Button
size="sm"
variant="default"
onClick={handleSaveChanges}
disabled={updateAssignmentMutation.loading}
className="w-full sm:w-auto text-xs sm:text-sm"
>
{updateAssignmentMutation.loading ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<CheckCircle className="h-4 w-4 mr-2" />
)}
Ment├ęs ├ęs V├ęgleges├şt├ęs
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => {
setIsEditMode(false)
setEditedCrew([])
}}
className="w-full sm:w-auto text-xs sm:text-sm"
>
<X className="h-4 w-4 mr-2" />
M├ęgse
</Button>
<Button size="sm" onClick={() => setShowAddMemberDialog(true)} className="w-full sm:w-auto text-xs sm:text-sm">
<UserPlus className="h-4 w-4 mr-2" />
<span className="hidden sm:inline">Új tag hozzáadása</span>
<span className="sm:hidden">Hozzáadás</span>
</Button>
</div>
)}
</div>
</CardHeader>
<CardContent className="space-y-4">
{/* Search and Filters */}
<div className="flex flex-col gap-3">
<div className="w-full">
<div className="relative">
<Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Keres├ęs n├ęv, szerepk├Âr vagy oszt├íly szerint..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-10 text-sm"
/>
</div>
</div>
<div className="flex flex-col sm:flex-row gap-2">