@consilioweb/payload-support 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +525 -0
  3. package/dist/client.cjs +7 -0
  4. package/dist/client.d.cts +3 -0
  5. package/dist/client.d.ts +3 -0
  6. package/dist/client.js +5 -0
  7. package/dist/index.cjs +7766 -0
  8. package/dist/index.d.cts +384 -0
  9. package/dist/index.d.ts +384 -0
  10. package/dist/index.js +7730 -0
  11. package/dist/views.d.cts +30 -0
  12. package/dist/views.d.ts +30 -0
  13. package/package.json +131 -0
  14. package/src/client.ts +1 -0
  15. package/src/collections/AuthLogs.ts +65 -0
  16. package/src/collections/CannedResponses.ts +69 -0
  17. package/src/collections/ChatMessages.ts +98 -0
  18. package/src/collections/EmailLogs.ts +94 -0
  19. package/src/collections/KnowledgeBase.ts +99 -0
  20. package/src/collections/Macros.ts +98 -0
  21. package/src/collections/PendingEmails.ts +122 -0
  22. package/src/collections/SatisfactionSurveys.ts +98 -0
  23. package/src/collections/SlaPolicies.ts +123 -0
  24. package/src/collections/SupportClients.ts +210 -0
  25. package/src/collections/TicketActivityLog.ts +81 -0
  26. package/src/collections/TicketMessages.ts +364 -0
  27. package/src/collections/TicketStatuses.ts +108 -0
  28. package/src/collections/Tickets.ts +704 -0
  29. package/src/collections/TimeEntries.ts +105 -0
  30. package/src/collections/WebhookEndpoints.ts +96 -0
  31. package/src/collections/index.ts +16 -0
  32. package/src/components/TicketConversation/components/AISummaryPanel.tsx +85 -0
  33. package/src/components/TicketConversation/components/ActionPanels.tsx +140 -0
  34. package/src/components/TicketConversation/components/ActivityLog.tsx +39 -0
  35. package/src/components/TicketConversation/components/ClientBar.tsx +37 -0
  36. package/src/components/TicketConversation/components/ClientHistory.tsx +117 -0
  37. package/src/components/TicketConversation/components/CodeBlock.tsx +186 -0
  38. package/src/components/TicketConversation/components/CodeBlockInserter.tsx +166 -0
  39. package/src/components/TicketConversation/components/QuickActions.tsx +82 -0
  40. package/src/components/TicketConversation/components/TicketHeader.tsx +91 -0
  41. package/src/components/TicketConversation/components/TimeTrackingPanel.tsx +161 -0
  42. package/src/components/TicketConversation/config.ts +82 -0
  43. package/src/components/TicketConversation/constants.ts +74 -0
  44. package/src/components/TicketConversation/context.ts +63 -0
  45. package/src/components/TicketConversation/hooks/useAI.ts +180 -0
  46. package/src/components/TicketConversation/hooks/useMessageActions.ts +131 -0
  47. package/src/components/TicketConversation/hooks/useReply.ts +190 -0
  48. package/src/components/TicketConversation/hooks/useTicketActions.ts +205 -0
  49. package/src/components/TicketConversation/hooks/useTimeTracking.ts +107 -0
  50. package/src/components/TicketConversation/hooks/useTranslation.ts +116 -0
  51. package/src/components/TicketConversation/index.tsx +1110 -0
  52. package/src/components/TicketConversation/locales/en.json +878 -0
  53. package/src/components/TicketConversation/locales/fr.json +878 -0
  54. package/src/components/TicketConversation/types.ts +54 -0
  55. package/src/components/TicketConversation/utils.ts +25 -0
  56. package/src/endpoints/admin-chat-stream.ts +238 -0
  57. package/src/endpoints/admin-chat.ts +263 -0
  58. package/src/endpoints/admin-stats.ts +200 -0
  59. package/src/endpoints/ai.ts +199 -0
  60. package/src/endpoints/apply-macro.ts +144 -0
  61. package/src/endpoints/auth-2fa.ts +163 -0
  62. package/src/endpoints/auto-close.ts +175 -0
  63. package/src/endpoints/billing.ts +167 -0
  64. package/src/endpoints/bulk-action.ts +103 -0
  65. package/src/endpoints/chat-stream.ts +127 -0
  66. package/src/endpoints/chat.ts +188 -0
  67. package/src/endpoints/chatbot.ts +113 -0
  68. package/src/endpoints/delete-account.ts +129 -0
  69. package/src/endpoints/email-stats.ts +109 -0
  70. package/src/endpoints/export-csv.ts +84 -0
  71. package/src/endpoints/export-data.ts +104 -0
  72. package/src/endpoints/import-conversation.ts +307 -0
  73. package/src/endpoints/index.ts +154 -0
  74. package/src/endpoints/login.ts +92 -0
  75. package/src/endpoints/merge-clients.ts +132 -0
  76. package/src/endpoints/merge-tickets.ts +137 -0
  77. package/src/endpoints/oauth-google.ts +179 -0
  78. package/src/endpoints/pending-emails-process.ts +224 -0
  79. package/src/endpoints/presence.ts +104 -0
  80. package/src/endpoints/process-scheduled.ts +144 -0
  81. package/src/endpoints/purge-logs.ts +58 -0
  82. package/src/endpoints/resend-notification.ts +99 -0
  83. package/src/endpoints/round-robin-config.ts +92 -0
  84. package/src/endpoints/satisfaction.ts +93 -0
  85. package/src/endpoints/search.ts +106 -0
  86. package/src/endpoints/seed-kb.ts +153 -0
  87. package/src/endpoints/settings.ts +144 -0
  88. package/src/endpoints/signature.ts +93 -0
  89. package/src/endpoints/sla-check.ts +124 -0
  90. package/src/endpoints/split-ticket.ts +131 -0
  91. package/src/endpoints/statuses.ts +45 -0
  92. package/src/endpoints/track-open.ts +154 -0
  93. package/src/endpoints/typing.ts +101 -0
  94. package/src/endpoints/user-prefs.ts +125 -0
  95. package/src/hooks/checkSLA.ts +414 -0
  96. package/src/hooks/ticketStatusEmail.ts +182 -0
  97. package/src/index.ts +51 -0
  98. package/src/plugin.ts +157 -0
  99. package/src/portal/LiveChat.tsx +1353 -0
  100. package/src/portal/auth/ChatWidget.tsx +350 -0
  101. package/src/portal/auth/ChatbotWidget.tsx +285 -0
  102. package/src/portal/auth/SupportHeader.tsx +409 -0
  103. package/src/portal/auth/dashboard/DashboardClient.tsx +650 -0
  104. package/src/portal/auth/dashboard/page.tsx +84 -0
  105. package/src/portal/auth/faq/FAQSearch.tsx +117 -0
  106. package/src/portal/auth/faq/page.tsx +199 -0
  107. package/src/portal/auth/layout.tsx +61 -0
  108. package/src/portal/auth/profile/page.tsx +705 -0
  109. package/src/portal/auth/tickets/detail/CloseTicketButton.tsx +74 -0
  110. package/src/portal/auth/tickets/detail/CollapsibleMessages.tsx +46 -0
  111. package/src/portal/auth/tickets/detail/MarkSolutionButton.tsx +50 -0
  112. package/src/portal/auth/tickets/detail/MessageActions.tsx +158 -0
  113. package/src/portal/auth/tickets/detail/PrintButton.tsx +16 -0
  114. package/src/portal/auth/tickets/detail/ReadReceipt.tsx +34 -0
  115. package/src/portal/auth/tickets/detail/ReopenTicketButton.tsx +74 -0
  116. package/src/portal/auth/tickets/detail/SatisfactionForm.tsx +156 -0
  117. package/src/portal/auth/tickets/detail/TicketPolling.tsx +57 -0
  118. package/src/portal/auth/tickets/detail/TicketReplyForm.tsx +294 -0
  119. package/src/portal/auth/tickets/detail/TypingIndicator.tsx +58 -0
  120. package/src/portal/auth/tickets/detail/page.tsx +738 -0
  121. package/src/portal/auth/tickets/new/page.tsx +515 -0
  122. package/src/portal/forgot-password/page.tsx +114 -0
  123. package/src/portal/layout.tsx +26 -0
  124. package/src/portal/locales/en.json +374 -0
  125. package/src/portal/locales/fr.json +374 -0
  126. package/src/portal/login/page.tsx +351 -0
  127. package/src/portal/page.tsx +162 -0
  128. package/src/portal/register/page.tsx +281 -0
  129. package/src/portal/reset-password/page.tsx +152 -0
  130. package/src/styles/BillingView.module.scss +311 -0
  131. package/src/styles/ChatView.module.scss +438 -0
  132. package/src/styles/CommandPalette.module.scss +160 -0
  133. package/src/styles/CrmView.module.scss +554 -0
  134. package/src/styles/EmailTracking.module.scss +238 -0
  135. package/src/styles/ImportConversation.module.scss +267 -0
  136. package/src/styles/Layout.module.scss +55 -0
  137. package/src/styles/Logs.module.scss +164 -0
  138. package/src/styles/NewTicket.module.scss +143 -0
  139. package/src/styles/PendingEmails.module.scss +629 -0
  140. package/src/styles/SupportDashboard.module.scss +649 -0
  141. package/src/styles/TicketDetail.module.scss +1043 -0
  142. package/src/styles/TicketInbox.module.scss +296 -0
  143. package/src/styles/TicketingSettings.module.scss +358 -0
  144. package/src/styles/TimeDashboard.module.scss +287 -0
  145. package/src/styles/_tokens.scss +78 -0
  146. package/src/styles/theme.css +633 -0
  147. package/src/types.ts +255 -0
  148. package/src/utils/adminNotification.ts +38 -0
  149. package/src/utils/auth.ts +46 -0
  150. package/src/utils/emailTemplate.ts +343 -0
  151. package/src/utils/fireWebhooks.ts +84 -0
  152. package/src/utils/index.ts +22 -0
  153. package/src/utils/rateLimiter.ts +52 -0
  154. package/src/utils/readSettings.ts +67 -0
  155. package/src/utils/slugs.ts +54 -0
  156. package/src/utils/webhookDispatcher.ts +120 -0
  157. package/src/views/BillingView/client.tsx +137 -0
  158. package/src/views/BillingView/index.tsx +33 -0
  159. package/src/views/ChatView/client.tsx +294 -0
  160. package/src/views/ChatView/index.tsx +33 -0
  161. package/src/views/CrmView/client.tsx +206 -0
  162. package/src/views/CrmView/index.tsx +33 -0
  163. package/src/views/EmailTrackingView/client.tsx +124 -0
  164. package/src/views/EmailTrackingView/index.tsx +33 -0
  165. package/src/views/ImportConversationView/client.tsx +133 -0
  166. package/src/views/ImportConversationView/index.tsx +33 -0
  167. package/src/views/LogsView/client.tsx +151 -0
  168. package/src/views/LogsView/index.tsx +30 -0
  169. package/src/views/NewTicketView/client.tsx +227 -0
  170. package/src/views/NewTicketView/index.tsx +30 -0
  171. package/src/views/PendingEmailsView/client.tsx +177 -0
  172. package/src/views/PendingEmailsView/index.tsx +33 -0
  173. package/src/views/SupportDashboardView/client.tsx +424 -0
  174. package/src/views/SupportDashboardView/index.tsx +33 -0
  175. package/src/views/TicketDetailView/client.tsx +775 -0
  176. package/src/views/TicketDetailView/index.tsx +33 -0
  177. package/src/views/TicketInboxView/client.tsx +313 -0
  178. package/src/views/TicketInboxView/index.tsx +30 -0
  179. package/src/views/TicketingSettingsView/client.tsx +866 -0
  180. package/src/views/TicketingSettingsView/index.tsx +33 -0
  181. package/src/views/TimeDashboardView/client.tsx +144 -0
  182. package/src/views/TimeDashboardView/index.tsx +33 -0
  183. package/src/views/shared/AdminViewHeader.tsx +69 -0
  184. package/src/views/shared/ErrorBoundary.tsx +68 -0
  185. package/src/views/shared/Skeleton.tsx +125 -0
  186. package/src/views/shared/adminTokens.ts +37 -0
  187. package/src/views/shared/config.ts +82 -0
  188. package/src/views/shared/index.ts +6 -0
  189. package/src/views.ts +16 -0
@@ -0,0 +1,775 @@
1
+ 'use client'
2
+
3
+ import React, { useState, useEffect, useCallback, useRef } from 'react'
4
+ import { useSearchParams } from 'next/navigation'
5
+ import Link from 'next/link'
6
+ import { getFeatures } from '../shared/config'
7
+ import { useTranslation } from '../../components/TicketConversation/hooks/useTranslation'
8
+ import s from '../../styles/TicketDetail.module.scss'
9
+
10
+ interface Message {
11
+ id: string | number; body: string; bodyHtml?: string; authorType: 'client' | 'admin' | 'email'
12
+ isInternal?: boolean; isSolution?: boolean; createdAt: string; fromChat?: boolean
13
+ attachments?: Array<{ file: { id: number; url?: string; filename?: string; mimeType?: string } | number }>
14
+ }
15
+ interface ClientInfo { id: number; company: string; firstName: string; lastName: string; email: string; phone?: string }
16
+ interface TimeEntry { id: string | number; duration: number; description?: string; date: string }
17
+ interface ActivityEntry { id: string | number; action: string; detail?: string; actorType?: string; createdAt: string }
18
+
19
+ const STATUS: Record<string, { label: string; bg: string; color: string }> = {
20
+ open: { label: 'Ouvert', bg: '#dbeafe', color: '#1e40af' },
21
+ waiting_client: { label: 'En attente', bg: '#fef3c7', color: '#92400e' },
22
+ resolved: { label: 'Resolu', bg: '#dcfce7', color: '#166534' },
23
+ }
24
+
25
+ function timeAgo(d: string): string {
26
+ const date = new Date(d), now = new Date()
27
+ if (date.toDateString() === now.toDateString()) return date.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' })
28
+ const y = new Date(now); y.setDate(y.getDate() - 1)
29
+ if (date.toDateString() === y.toDateString()) return `Hier, ${date.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' })}`
30
+ return date.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' })
31
+ }
32
+
33
+ function dateLabel(d: string): string {
34
+ const date = new Date(d), now = new Date()
35
+ if (date.toDateString() === now.toDateString()) return "Aujourd'hui"
36
+ const y = new Date(now); y.setDate(y.getDate() - 1)
37
+ if (date.toDateString() === y.toDateString()) return 'Hier'
38
+ return date.toLocaleDateString('fr-FR', { day: 'numeric', month: 'long' })
39
+ }
40
+
41
+ export const TicketDetailClient: React.FC = () => {
42
+ const { t } = useTranslation()
43
+ const searchParams = useSearchParams()
44
+ const ticketId = searchParams.get('id')
45
+ const features = getFeatures()
46
+ const threadEndRef = useRef<HTMLDivElement>(null)
47
+ const dropdownRef = useRef<HTMLDivElement>(null)
48
+ const fileInputRef = useRef<HTMLInputElement>(null)
49
+
50
+ const [ticket, setTicket] = useState<Record<string, unknown> | null>(null)
51
+ const [messages, setMessages] = useState<Message[]>([])
52
+ const [client, setClient] = useState<ClientInfo | null>(null)
53
+ const [timeEntries, setTimeEntries] = useState<TimeEntry[]>([])
54
+ const [activityLog, setActivityLog] = useState<ActivityEntry[]>([])
55
+ const [cannedResponses, setCannedResponses] = useState<Array<{ id: string | number; title: string; body: string }>>([])
56
+ const [loading, setLoading] = useState(true)
57
+
58
+ const [replyBody, setReplyBody] = useState('')
59
+ const [isInternal, setIsInternal] = useState(false)
60
+ const [notifyClient, setNotifyClient] = useState(true)
61
+ const [sending, setSending] = useState(false)
62
+
63
+ const [showMenu, setShowMenu] = useState(false)
64
+ const [clientTyping, setClientTyping] = useState(false)
65
+ const [aiReplying, setAiReplying] = useState(false)
66
+ const [aiRewriting, setAiRewriting] = useState(false)
67
+ const [sentiment, setSentiment] = useState<{ emoji: string; label: string; color: string } | null>(null)
68
+ const [statusUpdating, setStatusUpdating] = useState(false)
69
+ const [showActivity, setShowActivity] = useState(false)
70
+ const [timerRunning, setTimerRunning] = useState(() => {
71
+ if (typeof window === 'undefined' || !ticketId) return false
72
+ return localStorage.getItem(`timer-run-${ticketId}`) === '1'
73
+ })
74
+ const [timerSeconds, setTimerSeconds] = useState(() => {
75
+ if (typeof window === 'undefined' || !ticketId) return 0
76
+ const s = Number(localStorage.getItem(`timer-sec-${ticketId}`) || 0)
77
+ const t = Number(localStorage.getItem(`timer-ts-${ticketId}`) || 0)
78
+ const running = localStorage.getItem(`timer-run-${ticketId}`) === '1'
79
+ return running && t ? s + Math.floor((Date.now() - t) / 1000) : s
80
+ })
81
+ const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)
82
+
83
+ // Presence / collision detection
84
+ const [otherViewers, setOtherViewers] = useState<Array<{ name: string; email: string }>>([])
85
+
86
+ // Macros
87
+ const [macros, setMacros] = useState<Array<{ id: number; name: string }>>([])
88
+ const [applyingMacro, setApplyingMacro] = useState(false)
89
+
90
+ // Undo toast state
91
+ const [undoToast, setUndoToast] = useState<{ msgId: string | number; timer: ReturnType<typeof setTimeout> } | null>(null)
92
+
93
+ // Split modal state
94
+ const [splitModal, setSplitModal] = useState<{ messageId: string | number; preview: string } | null>(null)
95
+ const [splitSubject, setSplitSubject] = useState('')
96
+
97
+ // File upload state
98
+ const [pendingFiles, setPendingFiles] = useState<File[]>([])
99
+ const [composerDragOver, setComposerDragOver] = useState(false)
100
+
101
+ // Tags state
102
+ const [tags, setTags] = useState<string[]>([])
103
+ const [addingTag, setAddingTag] = useState(false)
104
+ const [newTagValue, setNewTagValue] = useState('')
105
+
106
+ // ---- DATA FETCHING ----
107
+ const fetchAll = useCallback(async () => {
108
+ if (!ticketId) return
109
+ try {
110
+ const [mr, tr, ter, ar, cr] = await Promise.all([
111
+ fetch(`/api/ticket-messages?where[ticket][equals]=${ticketId}&sort=createdAt&limit=200&depth=1`, { credentials: 'include' }),
112
+ fetch(`/api/tickets/${ticketId}?depth=1`, { credentials: 'include' }),
113
+ fetch(`/api/time-entries?where[ticket][equals]=${ticketId}&sort=-date&limit=50&depth=0`, { credentials: 'include' }),
114
+ fetch(`/api/ticket-activity-log?where[ticket][equals]=${ticketId}&sort=-createdAt&limit=30&depth=0`, { credentials: 'include' }),
115
+ fetch('/api/canned-responses?sort=sortOrder&limit=50&depth=0', { credentials: 'include' }),
116
+ ])
117
+ if (mr.ok) { const d = await mr.json(); setMessages(d.docs || []) }
118
+ if (tr.ok) {
119
+ const d = await tr.json()
120
+ setTicket(d)
121
+ if (d.client && typeof d.client === 'object') setClient(d.client)
122
+ if (Array.isArray(d.tags)) setTags(d.tags.map((t: { tag?: string } | string) => typeof t === 'object' ? (t.tag || '') : t).filter(Boolean))
123
+ }
124
+ if (ter.ok) { const d = await ter.json(); setTimeEntries(d.docs || []) }
125
+ if (ar.ok) { const d = await ar.json(); setActivityLog(d.docs || []) }
126
+ if (cr.ok) { const d = await cr.json(); setCannedResponses(d.docs || []) }
127
+ } catch { /* silent */ }
128
+ setLoading(false)
129
+ }, [ticketId])
130
+
131
+ useEffect(() => { fetchAll() }, [fetchAll])
132
+ useEffect(() => {
133
+ if (!ticketId || loading) return
134
+ const iv = setInterval(async () => {
135
+ try {
136
+ const [mr, tr] = await Promise.all([
137
+ fetch(`/api/ticket-messages?where[ticket][equals]=${ticketId}&sort=createdAt&limit=200&depth=1`, { credentials: 'include' }),
138
+ fetch(`/api/tickets/${ticketId}?depth=0`, { credentials: 'include' }),
139
+ ])
140
+ if (mr.ok) { const d = await mr.json(); setMessages(d.docs || []) }
141
+ if (tr.ok) { const d = await tr.json(); setTicket((p) => p ? { ...p, ...d } : d) }
142
+ } catch { /* */ }
143
+ }, 10000)
144
+ return () => clearInterval(iv)
145
+ }, [ticketId, loading])
146
+ useEffect(() => {
147
+ if (!ticketId) return
148
+ fetch(`/api/tickets/${ticketId}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ lastAdminReadAt: new Date().toISOString() }) }).catch(() => {})
149
+ }, [ticketId, messages.length])
150
+ useEffect(() => {
151
+ if (!ticketId) return
152
+ const iv = setInterval(async () => {
153
+ try { const r = await fetch(`/api/support/typing?ticketId=${ticketId}`, { credentials: 'include' }); if (r.ok) { const d = await r.json(); setClientTyping(d.typing) } } catch (err) { console.warn('[support] typing poll error:', err) }
154
+ }, 2000)
155
+ return () => clearInterval(iv)
156
+ }, [ticketId])
157
+ useEffect(() => {
158
+ if (!features.ai || messages.length === 0) return
159
+ const last = [...messages].reverse().find((m) => m.authorType === 'client' || m.authorType === 'email')
160
+ if (!last) return
161
+ fetch('/api/support/ai', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ action: 'sentiment', text: last.body.slice(0, 500) }) })
162
+ .then((r) => r.json()).then((d) => {
163
+ const raw = (d.sentiment || '').toLowerCase()
164
+ const map: Record<string, { emoji: string; label: string; color: string }> = {
165
+ 'frustre': { emoji: ':(', label: 'Frustre', color: '#dc2626' },
166
+ 'mecontent': { emoji: ':(', label: 'Mecontent', color: '#ea580c' },
167
+ 'urgent': { emoji: '!', label: 'Urgent', color: '#dc2626' },
168
+ 'neutre': { emoji: '-', label: 'Neutre', color: '#6b7280' },
169
+ 'satisfait': { emoji: ':)', label: 'Satisfait', color: '#16a34a' },
170
+ }
171
+ const m = Object.keys(map).find((k) => raw.includes(k))
172
+ setSentiment(m ? map[m] : { emoji: '-', label: 'Neutre', color: '#6b7280' })
173
+ }).catch(() => {})
174
+ }, [messages.length, features.ai]) // eslint-disable-line react-hooks/exhaustive-deps
175
+ useEffect(() => { threadEndRef.current?.scrollIntoView({ behavior: 'smooth' }) }, [messages.length])
176
+ useEffect(() => {
177
+ if (timerRunning) {
178
+ localStorage.setItem(`timer-run-${ticketId}`, '1')
179
+ localStorage.setItem(`timer-ts-${ticketId}`, String(Date.now()))
180
+ localStorage.setItem(`timer-sec-${ticketId}`, String(timerSeconds))
181
+ timerRef.current = setInterval(() => {
182
+ setTimerSeconds((p) => {
183
+ const next = p + 1
184
+ localStorage.setItem(`timer-sec-${ticketId}`, String(next))
185
+ localStorage.setItem(`timer-ts-${ticketId}`, String(Date.now()))
186
+ return next
187
+ })
188
+ }, 1000)
189
+ } else {
190
+ localStorage.setItem(`timer-run-${ticketId}`, '0')
191
+ localStorage.setItem(`timer-sec-${ticketId}`, String(timerSeconds))
192
+ if (timerRef.current) clearInterval(timerRef.current)
193
+ }
194
+ return () => { if (timerRef.current) clearInterval(timerRef.current) }
195
+ }, [timerRunning, ticketId]) // eslint-disable-line react-hooks/exhaustive-deps
196
+
197
+ // Presence
198
+ useEffect(() => {
199
+ if (!ticketId) return
200
+ const join = () => fetch('/api/support/presence', {
201
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include',
202
+ body: JSON.stringify({ ticketId: Number(ticketId), action: 'join' }),
203
+ }).catch(() => {})
204
+ join()
205
+ const heartbeat = setInterval(join, 20_000)
206
+ return () => {
207
+ clearInterval(heartbeat)
208
+ fetch('/api/support/presence', {
209
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include',
210
+ body: JSON.stringify({ ticketId: Number(ticketId), action: 'leave' }),
211
+ }).catch(() => {})
212
+ }
213
+ }, [ticketId])
214
+
215
+ useEffect(() => {
216
+ if (!ticketId) return
217
+ const poll = setInterval(async () => {
218
+ try {
219
+ const r = await fetch(`/api/support/presence?ticketId=${ticketId}`, { credentials: 'include' })
220
+ if (r.ok) { const d = await r.json(); setOtherViewers(d.viewers || []) }
221
+ } catch { /* silent */ }
222
+ }, 5_000)
223
+ return () => clearInterval(poll)
224
+ }, [ticketId])
225
+
226
+ // Fetch macros
227
+ useEffect(() => {
228
+ fetch('/api/macros?where[isActive][equals]=true&depth=0&limit=50', { credentials: 'include' })
229
+ .then((r) => r.ok ? r.json() : null)
230
+ .then((d) => { if (d?.docs) setMacros(d.docs.map((m: { id: number; name: string }) => ({ id: m.id, name: m.name }))) })
231
+ .catch(() => {})
232
+ }, [])
233
+
234
+ // Close dropdown on outside click
235
+ useEffect(() => {
236
+ if (!showMenu) return
237
+ const handler = (e: MouseEvent) => {
238
+ if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
239
+ setShowMenu(false)
240
+ }
241
+ }
242
+ document.addEventListener('mousedown', handler)
243
+ return () => document.removeEventListener('mousedown', handler)
244
+ }, [showMenu])
245
+
246
+ // Keyboard shortcuts
247
+ useEffect(() => {
248
+ const handler = (e: KeyboardEvent) => {
249
+ const mod = e.metaKey || e.ctrlKey
250
+ if (mod && e.key === 'Enter') {
251
+ e.preventDefault()
252
+ const sendBtn = document.querySelector('[data-action="send-reply"]') as HTMLButtonElement | null
253
+ if (sendBtn && !sendBtn.disabled) sendBtn.click()
254
+ }
255
+ if (mod && e.shiftKey && e.key.toLowerCase() === 'n') {
256
+ e.preventDefault()
257
+ setIsInternal((prev) => !prev)
258
+ }
259
+ if (e.key === 'Escape') {
260
+ setShowMenu(false)
261
+ setSplitModal(null)
262
+ }
263
+ }
264
+ document.addEventListener('keydown', handler)
265
+ return () => document.removeEventListener('keydown', handler)
266
+ }, [])
267
+
268
+ // ---- HANDLERS ----
269
+ const handleSend = async () => {
270
+ if (!replyBody.trim() || !ticketId) return
271
+ setSending(true)
272
+ try {
273
+ // Upload pending files first
274
+ const uploadedLinks: string[] = []
275
+ for (const file of pendingFiles) {
276
+ const formData = new FormData()
277
+ formData.append('file', file)
278
+ formData.append('_payload', JSON.stringify({ alt: file.name }))
279
+ try {
280
+ const ur = await fetch('/api/media', { method: 'POST', credentials: 'include', body: formData })
281
+ if (ur.ok) {
282
+ const ud = await ur.json()
283
+ if (ud.doc?.url) uploadedLinks.push(`[${ud.doc.filename || file.name}](${ud.doc.url})`)
284
+ }
285
+ } catch { /* silent */ }
286
+ }
287
+ const finalBody = uploadedLinks.length > 0 ? `${replyBody.trim()}\n\n${uploadedLinks.join('\n')}` : replyBody.trim()
288
+
289
+ const res = await fetch('/api/ticket-messages', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include',
290
+ body: JSON.stringify({ ticket: Number(ticketId), body: finalBody, authorType: 'admin', isInternal, skipNotification: isInternal || !notifyClient }) })
291
+ if (res.ok) { setReplyBody(''); setIsInternal(false); setPendingFiles([]); fetchAll() }
292
+ } catch (err) { console.warn('[support] send reply error:', err) } finally { setSending(false) }
293
+ }
294
+
295
+ const handleStatusChange = async (v: string) => {
296
+ if (!ticketId) return; setStatusUpdating(true)
297
+ try { await fetch(`/api/tickets/${ticketId}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ status: v }) }); fetchAll() } catch (err) { console.warn('[support] status change error:', err) } finally { setStatusUpdating(false) }
298
+ }
299
+
300
+ const handleFieldPatch = async (field: string, value: string) => {
301
+ if (!ticketId) return
302
+ try {
303
+ await fetch(`/api/tickets/${ticketId}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ [field]: value }) })
304
+ fetchAll()
305
+ } catch { /* silent */ }
306
+ }
307
+
308
+ const handleDeleteMessage = (msgId: string | number) => {
309
+ if (undoToast) clearTimeout(undoToast.timer)
310
+ const timer = setTimeout(() => {
311
+ fetch(`/api/ticket-messages/${msgId}`, { method: 'DELETE', credentials: 'include' }).then(() => fetchAll())
312
+ setUndoToast(null)
313
+ }, 5000)
314
+ setUndoToast({ msgId, timer })
315
+ }
316
+
317
+ const handleUndoDelete = () => {
318
+ if (undoToast) {
319
+ clearTimeout(undoToast.timer)
320
+ setUndoToast(null)
321
+ }
322
+ }
323
+
324
+ const handleSplitConfirm = async () => {
325
+ if (!splitModal || !splitSubject.trim()) return
326
+ try {
327
+ const r = await fetch('/api/support/split-ticket', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ messageId: splitModal.messageId, subject: splitSubject }) })
328
+ const d = await r.json()
329
+ if (d.ticketNumber) { fetchAll() }
330
+ } catch { /* silent */ }
331
+ setSplitModal(null)
332
+ setSplitSubject('')
333
+ }
334
+
335
+ const handleAiSuggest = async () => {
336
+ if (messages.length === 0) return; setAiReplying(true)
337
+ try {
338
+ const r = await fetch('/api/support/ai', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include',
339
+ body: JSON.stringify({ action: 'suggest_reply', messages: messages.slice(-10).map((m) => ({ authorType: m.authorType, body: m.body })), clientName: `${client?.firstName || ''} ${client?.lastName || ''}`.trim(), clientCompany: client?.company }) })
340
+ if (r.ok) { const d = await r.json(); if (d.reply) { setReplyBody(d.reply) } }
341
+ } catch (err) { console.warn('[support] AI suggest error:', err) } finally { setAiReplying(false) }
342
+ }
343
+
344
+ const handleAiRewrite = async () => {
345
+ if (!replyBody.trim()) return; setAiRewriting(true)
346
+ try {
347
+ const r = await fetch('/api/support/ai', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ action: 'rewrite', text: replyBody }) })
348
+ if (r.ok) { const d = await r.json(); if (d.rewritten) { setReplyBody(d.rewritten) } }
349
+ } catch (err) { console.warn('[support] AI rewrite error:', err) } finally { setAiRewriting(false) }
350
+ }
351
+
352
+ const handleTimerSave = async () => {
353
+ if (!ticketId || timerSeconds < 60) return
354
+ try { await fetch('/api/time-entries', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ ticket: Number(ticketId), duration: Math.round(timerSeconds / 60), date: new Date().toISOString(), description: 'Timer' }) }); setTimerSeconds(0); setTimerRunning(false); fetchAll() } catch (err) { console.warn('[support] timer save error:', err) }
355
+ }
356
+
357
+ const handleApplyMacro = async (macroId: number) => {
358
+ if (!ticketId || applyingMacro) return
359
+ setApplyingMacro(true)
360
+ try {
361
+ const r = await fetch('/api/support/apply-macro', {
362
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include',
363
+ body: JSON.stringify({ macroId, ticketId: Number(ticketId) }),
364
+ })
365
+ if (r.ok) { fetchAll() }
366
+ } catch (err) { console.warn('[support] apply macro error:', err) } finally { setApplyingMacro(false) }
367
+ }
368
+
369
+ const handleFileSelect = (files: FileList | null) => {
370
+ if (!files) return
371
+ setPendingFiles((prev) => [...prev, ...Array.from(files)])
372
+ }
373
+
374
+ const handleFileDrop = (e: React.DragEvent) => {
375
+ e.preventDefault()
376
+ setComposerDragOver(false)
377
+ handleFileSelect(e.dataTransfer.files)
378
+ }
379
+
380
+ const handleRemoveTag = async (tag: string) => {
381
+ const newTags = tags.filter((t) => t !== tag)
382
+ setTags(newTags)
383
+ if (ticketId) {
384
+ await fetch(`/api/tickets/${ticketId}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ tags: newTags.map((t) => ({ tag: t })) }) }).catch(() => {})
385
+ }
386
+ }
387
+
388
+ const handleAddTag = async () => {
389
+ if (!newTagValue.trim()) { setAddingTag(false); return }
390
+ const tag = newTagValue.trim()
391
+ if (tags.includes(tag)) { setAddingTag(false); setNewTagValue(''); return }
392
+ const newTags = [...tags, tag]
393
+ setTags(newTags)
394
+ setAddingTag(false)
395
+ setNewTagValue('')
396
+ if (ticketId) {
397
+ await fetch(`/api/tickets/${ticketId}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ tags: newTags.map((t) => ({ tag: t })) }) }).catch(() => {})
398
+ }
399
+ }
400
+
401
+ // ---- RENDER ----
402
+ if (!ticketId) return <div style={{ padding: 60, textAlign: 'center', color: '#94a3b8', fontSize: 14 }}>{t('detail.selectTicket')}</div>
403
+ if (loading) return <div style={{ padding: 60, textAlign: 'center', color: '#94a3b8', fontSize: 14 }}>{t('common.loading')}</div>
404
+ if (!ticket) return <div style={{ padding: 60, textAlign: 'center', color: '#94a3b8', fontSize: 14 }}>{t('detail.notFound')}</div>
405
+
406
+ const st = STATUS[(ticket.status as string) || 'open'] || STATUS.open
407
+ const totalMin = timeEntries.reduce((a, e) => a + (e.duration || 0), 0)
408
+ const initials = client ? `${(client.firstName?.[0] || '').toUpperCase()}${(client.lastName?.[0] || '').toUpperCase()}` : '?'
409
+
410
+ const S: Record<string, React.CSSProperties> = {
411
+ page: { padding: '16px 20px', maxWidth: 1200, margin: '0 auto' },
412
+ topBar: { display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12, padding: '8px 0', borderBottom: '1px solid var(--theme-elevation-200)' },
413
+ backLink: { fontSize: 18, textDecoration: 'none', color: 'var(--theme-elevation-500)', padding: '4px 8px' },
414
+ ticketNumber: { fontWeight: 700, fontSize: 14, color: 'var(--theme-elevation-400)' },
415
+ ticketSubject: { fontWeight: 600, fontSize: 15, color: 'var(--theme-text)', flex: 1 },
416
+ statusChip: { padding: '4px 10px', borderRadius: 6, border: 'none', fontWeight: 600, fontSize: 12, cursor: 'pointer' },
417
+ layout: { display: 'grid', gridTemplateColumns: '1fr 280px', gap: 20 },
418
+ thread: { display: 'flex', flexDirection: 'column' as const, gap: 12, maxHeight: 'calc(100vh - 400px)', overflowY: 'auto' as const, padding: '8px 0' },
419
+ message: { display: 'flex', gap: 10, padding: '12px 14px', borderRadius: 10, border: '1px solid var(--theme-elevation-150)', position: 'relative' as const },
420
+ avatar: { width: 32, height: 32, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 11, fontWeight: 700, flexShrink: 0 },
421
+ messageBody: { fontSize: 14, lineHeight: 1.6, color: 'var(--theme-text)', whiteSpace: 'pre-wrap' as const },
422
+ composer: { marginTop: 12, border: '1px solid var(--theme-elevation-200)', borderRadius: 10, padding: 12 },
423
+ composerInternal: { borderColor: '#fbbf24', background: '#fefce8' },
424
+ textarea: { width: '100%', minHeight: 100, padding: 10, border: 'none', outline: 'none', resize: 'vertical' as const, fontSize: 14, fontFamily: 'inherit', background: 'transparent', color: 'var(--theme-text)' },
425
+ composerFooter: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 8 },
426
+ sendBtn: { padding: '8px 16px', borderRadius: 6, border: 'none', background: '#2563eb', color: '#fff', fontWeight: 600, fontSize: 13, cursor: 'pointer' },
427
+ sidebar: { display: 'flex', flexDirection: 'column' as const, gap: 16 },
428
+ sideSection: { padding: '12px 14px', borderRadius: 10, border: '1px solid var(--theme-elevation-150)', fontSize: 13 },
429
+ sideSectionTitle: { fontSize: 12, fontWeight: 700, textTransform: 'uppercase' as const, color: 'var(--theme-elevation-500)', marginBottom: 8, display: 'flex', justifyContent: 'space-between', alignItems: 'center' },
430
+ sideField: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '4px 0' },
431
+ sideLabel: { fontSize: 12, color: 'var(--theme-elevation-500)' },
432
+ sideSelect: { padding: '2px 6px', borderRadius: 4, border: '1px solid var(--theme-elevation-200)', fontSize: 12, background: 'var(--theme-elevation-0)', color: 'var(--theme-text)' },
433
+ sideValue: { fontSize: 12, fontWeight: 500, color: 'var(--theme-text)' },
434
+ badge: { padding: '2px 6px', borderRadius: 4, fontSize: 10, fontWeight: 600 },
435
+ tagChip: { display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 8px', borderRadius: 4, background: 'var(--theme-elevation-100)', fontSize: 11, fontWeight: 500 },
436
+ tagRemove: { background: 'none', border: 'none', cursor: 'pointer', fontSize: 14, color: 'var(--theme-elevation-400)', padding: 0 },
437
+ tagInput: { padding: '2px 6px', borderRadius: 4, border: '1px solid var(--theme-elevation-200)', fontSize: 11, width: 80 },
438
+ tagAddBtn: { padding: '2px 8px', borderRadius: 4, border: '1px dashed var(--theme-elevation-300)', background: 'none', fontSize: 11, cursor: 'pointer', color: 'var(--theme-elevation-400)' },
439
+ toolbarBtn: { padding: '4px 10px', borderRadius: 4, border: '1px solid var(--theme-elevation-200)', background: 'var(--theme-elevation-0)', fontSize: 11, fontWeight: 700, cursor: 'pointer', color: 'var(--theme-text)' },
440
+ dateSeparator: { textAlign: 'center' as const, padding: '8px 0', fontSize: 11, color: 'var(--theme-elevation-400)' },
441
+ }
442
+
443
+ return (
444
+ <div style={S.page}>
445
+ {/* TOP BAR */}
446
+ <div style={S.topBar}>
447
+ <Link href="/admin/support/inbox" style={S.backLink} aria-label="Retour">&larr;</Link>
448
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1 }}>
449
+ <span style={S.ticketNumber}>{ticket.ticketNumber as string}</span>
450
+ <span style={S.ticketSubject}>{ticket.subject as string}</span>
451
+ </div>
452
+ <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
453
+ <select style={{ ...S.statusChip, background: st.bg, color: st.color }} value={(ticket.status as string) || 'open'} onChange={(e) => handleStatusChange(e.target.value)} disabled={statusUpdating}>
454
+ <option value="open">{t('detail.statusOpen')}</option>
455
+ <option value="waiting_client">{t('detail.statusWaiting')}</option>
456
+ <option value="resolved">{t('detail.statusResolved')}</option>
457
+ </select>
458
+ {sentiment && features.ai && (
459
+ <span style={{ ...S.badge, background: `${sentiment.color}12`, color: sentiment.color }}>
460
+ {sentiment.emoji} {sentiment.label}
461
+ </span>
462
+ )}
463
+ <div ref={dropdownRef} style={{ position: 'relative' }}>
464
+ <button onClick={() => setShowMenu(!showMenu)} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 18, color: 'var(--theme-elevation-500)' }}>&middot;&middot;&middot;</button>
465
+ {showMenu && (
466
+ <div style={{ position: 'absolute', right: 0, top: '100%', background: 'var(--theme-elevation-0)', border: '1px solid var(--theme-elevation-200)', borderRadius: 8, boxShadow: '0 4px 12px rgba(0,0,0,0.1)', zIndex: 50, minWidth: 160 }}>
467
+ <button style={{ display: 'block', width: '100%', padding: '8px 14px', border: 'none', background: 'none', cursor: 'pointer', textAlign: 'left', fontSize: 13, color: 'var(--theme-text)' }} onClick={() => { navigator.clipboard.writeText(window.location.href); setShowMenu(false) }}>{t('detail.copyLink')}</button>
468
+ <Link href={`/admin/collections/tickets/${ticketId}`} style={{ display: 'block', padding: '8px 14px', fontSize: 13, color: 'var(--theme-text)', textDecoration: 'none' }} onClick={() => setShowMenu(false)}>{t('detail.payloadView')}</Link>
469
+ <a href={`/support/tickets/${ticketId}`} target="_blank" rel="noopener noreferrer" style={{ display: 'block', padding: '8px 14px', fontSize: 13, color: 'var(--theme-text)', textDecoration: 'none' }} onClick={() => setShowMenu(false)}>{t('detail.clientView')}</a>
470
+ </div>
471
+ )}
472
+ </div>
473
+ </div>
474
+ </div>
475
+
476
+ {/* PRESENCE BANNER */}
477
+ {otherViewers.length > 0 && (
478
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 14px', marginBottom: 12, borderRadius: 8, background: '#fef3c7', border: '1px solid #fde68a', fontSize: 13, fontWeight: 500, color: '#92400e' }}>
479
+ {otherViewers.map((v) => v.name).join(', ')} {otherViewers.length === 1 ? 'est aussi en train de voir ce ticket' : 'sont aussi en train de voir ce ticket'}
480
+ </div>
481
+ )}
482
+
483
+ {/* LAYOUT */}
484
+ <div style={S.layout}>
485
+ {/* LEFT: Conversation */}
486
+ <div>
487
+ <div style={S.thread}>
488
+ {messages.map((msg, idx) => {
489
+ const prev = idx > 0 ? messages[idx - 1] : null
490
+ const showDate = msg.createdAt && (!prev?.createdAt || new Date(msg.createdAt).toDateString() !== new Date(prev.createdAt).toDateString())
491
+ const isAdmin = msg.authorType === 'admin'
492
+ const isPendingDelete = undoToast?.msgId === msg.id
493
+
494
+ return (
495
+ <React.Fragment key={msg.id}>
496
+ {showDate && <div style={S.dateSeparator}><span>{dateLabel(msg.createdAt)}</span></div>}
497
+ <div style={{ ...S.message, ...(msg.isInternal ? { borderColor: '#fbbf24', background: '#fefce8' } : {}), ...(isPendingDelete ? { opacity: 0.3, pointerEvents: 'none' as const } : {}) }}>
498
+ <div style={{ ...S.avatar, backgroundColor: isAdmin ? '#2563eb' : msg.authorType === 'email' ? '#ea580c' : '#7c3aed' }}>
499
+ {isAdmin ? 'CW' : initials}
500
+ </div>
501
+ <div style={{ flex: 1, minWidth: 0 }}>
502
+ <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 4 }}>
503
+ <span style={{ fontWeight: 600, fontSize: 13 }}>{isAdmin ? 'Support' : msg.authorType === 'email' ? 'Email' : client?.firstName || 'Client'}</span>
504
+ <span style={{ fontSize: 11, color: 'var(--theme-elevation-400)' }}>{timeAgo(msg.createdAt)}</span>
505
+ {msg.isInternal && <span style={{ ...S.badge, background: '#fef3c7', color: '#92400e' }}>Interne</span>}
506
+ {msg.isSolution && <span style={{ ...S.badge, background: '#dcfce7', color: '#166534' }}>Solution</span>}
507
+ </div>
508
+ {msg.bodyHtml ? (
509
+ <div style={S.messageBody} dangerouslySetInnerHTML={{ __html: msg.bodyHtml }} />
510
+ ) : (
511
+ <div style={S.messageBody}>{msg.body}</div>
512
+ )}
513
+ {Array.isArray(msg.attachments) && msg.attachments.length > 0 && (
514
+ <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 8 }}>
515
+ {msg.attachments.map((att, i) => {
516
+ const file = typeof att.file === 'object' ? att.file : null
517
+ if (!file) return null
518
+ return (file.mimeType || '').startsWith('image/')
519
+ ? <a key={i} href={file.url || '#'} target="_blank" rel="noopener noreferrer"><img src={file.url || ''} alt="" style={{ maxWidth: 200, maxHeight: 120, borderRadius: 6 }} /></a>
520
+ : <a key={i} href={file.url || '#'} target="_blank" rel="noopener noreferrer" style={{ fontSize: 12, color: '#2563eb' }}>PJ {file.filename || 'Fichier'}</a>
521
+ })}
522
+ </div>
523
+ )}
524
+ </div>
525
+ {/* Hover actions */}
526
+ <div style={{ position: 'absolute', top: 8, right: 8, display: 'flex', gap: 4, opacity: 0.6 }}>
527
+ <button style={{ ...S.toolbarBtn, color: '#dc2626', fontSize: 11 }} onClick={() => handleDeleteMessage(msg.id)}>{t('common.delete')}</button>
528
+ {features.splitTicket && !msg.isInternal && <button style={{ ...S.toolbarBtn, fontSize: 11 }} onClick={() => { setSplitModal({ messageId: msg.id, preview: msg.body.slice(0, 200) }); setSplitSubject(`Split: ${ticket.subject}`) }}>{t('actions.extractMessage')}</button>}
529
+ {isAdmin && !msg.isInternal && <button style={{ ...S.toolbarBtn, fontSize: 11 }} onClick={() => fetch('/api/support/resend-notification', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ messageId: msg.id }) })}>{t('actions.resendEmail')}</button>}
530
+ </div>
531
+ </div>
532
+ </React.Fragment>
533
+ )
534
+ })}
535
+ <div ref={threadEndRef} />
536
+ </div>
537
+
538
+ {clientTyping && (
539
+ <div style={{ padding: '8px 14px', fontSize: 13, color: 'var(--theme-elevation-400)' }}>
540
+ {client?.firstName || 'Client'} est en train d&apos;ecrire...
541
+ </div>
542
+ )}
543
+
544
+ {/* COMPOSER */}
545
+ <div
546
+ style={{ ...S.composer, ...(isInternal ? S.composerInternal : {}), ...(composerDragOver ? { borderColor: '#2563eb', background: '#eff6ff' } : {}) }}
547
+ onDragOver={(e) => { e.preventDefault(); setComposerDragOver(true) }}
548
+ onDragLeave={() => setComposerDragOver(false)}
549
+ onDrop={handleFileDrop}
550
+ >
551
+ <div style={{ display: 'flex', gap: 6, marginBottom: 8, flexWrap: 'wrap' }}>
552
+ {features.ai && (
553
+ <>
554
+ <button style={S.toolbarBtn} onClick={handleAiSuggest} disabled={aiReplying || messages.length === 0}>{aiReplying ? '...' : t('detail.iaSuggestion')}</button>
555
+ <button style={S.toolbarBtn} onClick={handleAiRewrite} disabled={aiRewriting || !replyBody.trim()}>{aiRewriting ? '...' : t('detail.rewrite')}</button>
556
+ </>
557
+ )}
558
+ <button style={S.toolbarBtn} onClick={() => fileInputRef.current?.click()}>{t('detail.file')}</button>
559
+ <input ref={fileInputRef} type="file" multiple style={{ display: 'none' }} onChange={(e) => handleFileSelect(e.target.files)} />
560
+ {macros.length > 0 && (
561
+ <select
562
+ style={{ ...S.sideSelect, marginLeft: 0 }}
563
+ onChange={(e) => { const id = Number(e.target.value); if (id) handleApplyMacro(id); e.target.value = '' }}
564
+ disabled={applyingMacro}
565
+ >
566
+ <option value="">{applyingMacro ? t('detail.applyingMacro') : t('detail.macros')}</option>
567
+ {macros.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}
568
+ </select>
569
+ )}
570
+ {features.canned && cannedResponses.length > 0 && (
571
+ <select style={S.sideSelect} onChange={(e) => {
572
+ const cr = cannedResponses.find((c) => String(c.id) === e.target.value)
573
+ if (cr) { let b = cr.body; if (client) { b = b.replace(/\{\{client\.firstName\}\}/g, client.firstName).replace(/\{\{client\.company\}\}/g, client.company) }; setReplyBody(b) }
574
+ e.target.value = ''
575
+ }}>
576
+ <option value="">{t('detail.cannedResponses')}</option>
577
+ {cannedResponses.map((cr) => <option key={cr.id} value={String(cr.id)}>{cr.title}</option>)}
578
+ </select>
579
+ )}
580
+ </div>
581
+ <textarea
582
+ style={S.textarea}
583
+ value={replyBody}
584
+ onChange={(e) => setReplyBody(e.target.value)}
585
+ placeholder={isInternal ? t('composer.placeholderInternal') : t('composer.placeholderReplyTo', { name: client?.firstName || 'client' })}
586
+ />
587
+ {pendingFiles.length > 0 && (
588
+ <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 6 }}>
589
+ {pendingFiles.map((f, i) => (
590
+ <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '2px 8px', borderRadius: 4, background: 'var(--theme-elevation-100)', fontSize: 11 }}>
591
+ <span>PJ {f.name}</span>
592
+ <button style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 14, color: 'var(--theme-elevation-400)' }} onClick={() => setPendingFiles((prev) => prev.filter((_, j) => j !== i))}>&times;</button>
593
+ </div>
594
+ ))}
595
+ </div>
596
+ )}
597
+ <div style={S.composerFooter}>
598
+ <div style={{ display: 'flex', gap: 12, alignItems: 'center', fontSize: 12 }}>
599
+ <label><input type="checkbox" checked={isInternal} onChange={(e) => setIsInternal(e.target.checked)} /> {t('detail.internalNote')}</label>
600
+ <label><input type="checkbox" checked={notifyClient} onChange={(e) => setNotifyClient(e.target.checked)} disabled={isInternal} /> {t('detail.notify')}</label>
601
+ </div>
602
+ <button style={{ ...S.sendBtn, ...(isInternal ? { background: '#d97706' } : {}) }} onClick={handleSend} disabled={sending || !replyBody.trim()} data-action="send-reply">
603
+ {sending ? t('detail.sending') : isInternal ? t('detail.sendNote') : t('detail.sendReply')}
604
+ </button>
605
+ </div>
606
+ </div>
607
+ </div>
608
+
609
+ {/* RIGHT: Sidebar */}
610
+ <div style={S.sidebar}>
611
+ {client && (
612
+ <div style={S.sideSection}>
613
+ <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 8 }}>
614
+ <div style={{ ...S.avatar, backgroundColor: '#7c3aed', width: 36, height: 36 }}>{initials}</div>
615
+ <div>
616
+ <div style={{ fontWeight: 600, fontSize: 13 }}>{client.firstName} {client.lastName}</div>
617
+ <div style={{ fontSize: 12, color: 'var(--theme-elevation-500)' }}>{client.company}</div>
618
+ <a href={`mailto:${client.email}`} style={{ fontSize: 11, color: '#2563eb' }}>{client.email}</a>
619
+ </div>
620
+ </div>
621
+ <div style={{ display: 'flex', gap: 6 }}>
622
+ <Link href={`/admin/collections/support-clients/${client.id}`} style={{ padding: '4px 10px', borderRadius: 4, border: '1px solid var(--theme-elevation-200)', fontSize: 11, textDecoration: 'none', color: 'var(--theme-text)' }}>{t('client.clientSheet')}</Link>
623
+ <button style={{ padding: '4px 10px', borderRadius: 4, border: '1px solid var(--theme-elevation-200)', fontSize: 11, background: 'none', cursor: 'pointer', color: 'var(--theme-text)' }} onClick={() => window.open(`/api/admin/impersonate?clientId=${client.id}`, '_blank')}>{t('client.clientPortal')}</button>
624
+ </div>
625
+ </div>
626
+ )}
627
+
628
+ {/* Editable sidebar fields */}
629
+ <div style={S.sideSection}>
630
+ <div style={S.sideSectionTitle}>{t('detail.details')}</div>
631
+ <div style={S.sideField}>
632
+ <span style={S.sideLabel}>{t('detail.priority')}</span>
633
+ <select style={S.sideSelect} value={(ticket.priority as string) || 'normal'} onChange={(e) => handleFieldPatch('priority', e.target.value)}>
634
+ <option value="low">{t('ticket.priority.low')}</option>
635
+ <option value="normal">{t('ticket.priority.normal')}</option>
636
+ <option value="high">{t('ticket.priority.high')}</option>
637
+ <option value="urgent">{t('ticket.priority.urgent')}</option>
638
+ </select>
639
+ </div>
640
+ <div style={S.sideField}>
641
+ <span style={S.sideLabel}>{t('detail.category')}</span>
642
+ <select style={S.sideSelect} value={(ticket.category as string) || ''} onChange={(e) => handleFieldPatch('category', e.target.value)}>
643
+ <option value="">--</option>
644
+ <option value="bug">{t('ticket.category.bug')}</option>
645
+ <option value="content">{t('ticket.category.content')}</option>
646
+ <option value="feature">{t('ticket.category.feature')}</option>
647
+ <option value="question">{t('ticket.category.question')}</option>
648
+ <option value="hosting">{t('ticket.category.hosting')}</option>
649
+ </select>
650
+ </div>
651
+ <div style={S.sideField}><span style={S.sideLabel}>{t('detail.source')}</span><span style={S.sideValue}>{(ticket.source as string) || t('ticket.source.portal')}</span></div>
652
+ <div style={S.sideField}><span style={S.sideLabel}>{t('detail.assigned')}</span><span style={S.sideValue}>{typeof ticket.assignedTo === 'object' && ticket.assignedTo ? (ticket.assignedTo as { firstName?: string }).firstName || 'Admin' : '--'}</span></div>
653
+ </div>
654
+
655
+ {/* Tags */}
656
+ <div style={S.sideSection}>
657
+ <div style={S.sideSectionTitle}>{t('detail.tags')}</div>
658
+ <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
659
+ {tags.map((tag) => (
660
+ <span key={tag} style={S.tagChip}>
661
+ {tag}
662
+ <button style={S.tagRemove} onClick={() => handleRemoveTag(tag)}>&times;</button>
663
+ </span>
664
+ ))}
665
+ {addingTag ? (
666
+ <input
667
+ style={S.tagInput}
668
+ value={newTagValue}
669
+ onChange={(e) => setNewTagValue(e.target.value)}
670
+ onKeyDown={(e) => { if (e.key === 'Enter') handleAddTag(); if (e.key === 'Escape') { setAddingTag(false); setNewTagValue('') } }}
671
+ onBlur={handleAddTag}
672
+ placeholder="Tag..."
673
+ autoFocus
674
+ />
675
+ ) : (
676
+ <button style={S.tagAddBtn} onClick={() => setAddingTag(true)}>+ Tag</button>
677
+ )}
678
+ </div>
679
+ </div>
680
+
681
+ {features.timeTracking && (
682
+ <div style={S.sideSection}>
683
+ <div style={S.sideSectionTitle}>{t('detail.time')} <span style={{ fontWeight: 700, fontSize: 13, color: '#d97706' }}>{totalMin > 0 ? `${Math.floor(totalMin / 60)}h${String(totalMin % 60).padStart(2, '0')} ${t('detail.total')}` : '0min'}</span></div>
684
+ <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
685
+ <span style={{ fontFamily: 'monospace', fontSize: 16, fontWeight: 700, color: timerRunning ? '#dc2626' : 'var(--theme-text)' }}>
686
+ {String(Math.floor(timerSeconds / 60)).padStart(2, '0')}:{String(timerSeconds % 60).padStart(2, '0')}
687
+ </span>
688
+ {!timerRunning ? (
689
+ <button style={{ ...S.toolbarBtn, color: '#dc2626', borderColor: '#dc2626' }} onClick={() => setTimerRunning(true)}>{timerSeconds > 0 ? 'Play' : 'Go'}</button>
690
+ ) : (
691
+ <button style={S.toolbarBtn} onClick={() => setTimerRunning(false)}>Pause</button>
692
+ )}
693
+ {timerSeconds >= 60 && !timerRunning && (
694
+ <button style={{ ...S.toolbarBtn, color: '#16a34a', borderColor: '#16a34a' }} onClick={() => { handleTimerSave(); localStorage.removeItem(`timer-sec-${ticketId}`); localStorage.removeItem(`timer-run-${ticketId}`) }}>Save {Math.round(timerSeconds / 60)}m</button>
695
+ )}
696
+ </div>
697
+ <div style={{ display: 'flex', gap: 6, marginTop: 8, alignItems: 'center' }}>
698
+ <input type="number" min="1" placeholder="min" style={{ width: 60, padding: '4px 8px', borderRadius: 6, border: '1px solid var(--theme-elevation-200)', fontSize: 12, color: 'var(--theme-text)', background: 'var(--theme-elevation-0)' }} id="manual-time-input" />
699
+ <button style={{ ...S.toolbarBtn, fontSize: 11 }} onClick={async () => {
700
+ const input = document.getElementById('manual-time-input') as HTMLInputElement
701
+ const mins = Number(input?.value)
702
+ if (!mins || mins < 1 || !ticketId) return
703
+ try {
704
+ await fetch('/api/time-entries', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ ticket: Number(ticketId), duration: mins, date: new Date().toISOString(), description: 'Saisie manuelle' }) })
705
+ if (input) input.value = ''
706
+ fetchAll()
707
+ } catch (err) { console.warn('[support] manual time entry error:', err) }
708
+ }}>+ Ajouter</button>
709
+ </div>
710
+ {timeEntries.length > 0 && (
711
+ <div style={{ marginTop: 8, fontSize: 11 }}>
712
+ {timeEntries.slice(0, 6).map((e) => (
713
+ <div key={e.id} style={{ display: 'flex', justifyContent: 'space-between', padding: '3px 0', color: 'var(--theme-elevation-500)' }}>
714
+ <span>{new Date(e.date).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' })}</span>
715
+ <span title={e.description} style={{ fontWeight: 600, cursor: e.description ? 'help' : 'default' }}>{e.duration}min</span>
716
+ </div>
717
+ ))}
718
+ </div>
719
+ )}
720
+ </div>
721
+ )}
722
+
723
+ {features.activityLog && (
724
+ <div style={S.sideSection}>
725
+ <div style={S.sideSectionTitle}>
726
+ <button onClick={() => setShowActivity(!showActivity)} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 12, fontWeight: 700, textTransform: 'uppercase' as const, color: 'var(--theme-elevation-500)' }}>
727
+ Activite {showActivity ? '&#9662;' : '&#9656;'}
728
+ </button>
729
+ </div>
730
+ {showActivity && activityLog.slice(0, 8).map((a) => (
731
+ <div key={a.id} style={{ display: 'flex', gap: 8, alignItems: 'flex-start', padding: '4px 0' }}>
732
+ <div style={{ width: 6, height: 6, borderRadius: '50%', marginTop: 4, flexShrink: 0, backgroundColor: a.actorType === 'admin' ? '#2563eb' : a.actorType === 'system' ? '#6b7280' : '#16a34a' }} />
733
+ <div>
734
+ <div style={{ fontSize: 12, color: 'var(--theme-text)' }}>{(a.detail || a.action).slice(0, 60)}</div>
735
+ <div style={{ fontSize: 11, color: 'var(--theme-elevation-400)' }}>{timeAgo(a.createdAt)}</div>
736
+ </div>
737
+ </div>
738
+ ))}
739
+ </div>
740
+ )}
741
+ </div>
742
+ </div>
743
+
744
+ {/* Undo delete toast */}
745
+ {undoToast && (
746
+ <div style={{ position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)', padding: '10px 20px', borderRadius: 8, background: '#1e293b', color: '#fff', fontSize: 13, display: 'flex', gap: 12, alignItems: 'center', zIndex: 100, boxShadow: '0 4px 12px rgba(0,0,0,0.2)' }} role="alert">
747
+ <span>{t('detail.messageDeleted')}</span>
748
+ <button onClick={handleUndoDelete} style={{ background: 'none', border: '1px solid rgba(255,255,255,0.3)', borderRadius: 4, padding: '4px 10px', color: '#fff', cursor: 'pointer', fontSize: 12, fontWeight: 600 }}>{t('detail.undo')}</button>
749
+ </div>
750
+ )}
751
+
752
+ {/* Split ticket modal */}
753
+ {splitModal && (
754
+ <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100 }} onClick={(e) => { if (e.target === e.currentTarget) { setSplitModal(null); setSplitSubject('') } }}>
755
+ <div style={{ background: 'var(--theme-elevation-0)', borderRadius: 12, padding: 24, maxWidth: 480, width: '100%', boxShadow: '0 8px 30px rgba(0,0,0,0.15)' }} role="dialog">
756
+ <h3 style={{ margin: '0 0 12px', fontSize: 16, fontWeight: 700 }}>{t('detail.extractTitle')}</h3>
757
+ <div style={{ padding: 10, background: 'var(--theme-elevation-50)', borderRadius: 6, fontSize: 13, color: 'var(--theme-elevation-500)', marginBottom: 12 }}>{splitModal.preview}</div>
758
+ <input
759
+ style={{ width: '100%', padding: '8px 12px', borderRadius: 6, border: '1px solid var(--theme-elevation-200)', fontSize: 13, marginBottom: 12, color: 'var(--theme-text)', background: 'var(--theme-elevation-0)' }}
760
+ value={splitSubject}
761
+ onChange={(e) => setSplitSubject(e.target.value)}
762
+ onKeyDown={(e) => { if (e.key === 'Enter') handleSplitConfirm() }}
763
+ placeholder={t('detail.extractSubjectPlaceholder')}
764
+ autoFocus
765
+ />
766
+ <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
767
+ <button style={{ padding: '6px 14px', borderRadius: 6, border: '1px solid var(--theme-elevation-200)', background: 'none', cursor: 'pointer', fontSize: 13, color: 'var(--theme-text)' }} onClick={() => { setSplitModal(null); setSplitSubject('') }}>{t('common.cancel')}</button>
768
+ <button style={{ ...S.sendBtn }} onClick={handleSplitConfirm} disabled={!splitSubject.trim()}>{t('ticket.createTicket')}</button>
769
+ </div>
770
+ </div>
771
+ </div>
772
+ )}
773
+ </div>
774
+ )
775
+ }