@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,424 @@
1
+ 'use client'
2
+
3
+ import React, { useState, useEffect, useCallback, useMemo } from 'react'
4
+ import Link from 'next/link'
5
+ import { useTranslation } from '../../components/TicketConversation/hooks/useTranslation'
6
+ import s from '../../styles/SupportDashboard.module.scss'
7
+
8
+ // ---- Types ----
9
+
10
+ interface Stats {
11
+ total: number
12
+ byStatus: Record<string, number>
13
+ byPriority: Record<string, number>
14
+ byCategory: Record<string, number>
15
+ createdLast7Days: number
16
+ createdLast30Days: number
17
+ avgResponseTimeHours: number | null
18
+ avgResolutionTimeHours: number | null
19
+ totalTimeMinutes: number
20
+ satisfactionAvg: number
21
+ satisfactionCount: number
22
+ clientCount: number
23
+ pendingEmailsCount: number
24
+ }
25
+
26
+ interface SlaTicket {
27
+ id: string
28
+ ticketNumber: string
29
+ subject: string
30
+ status: string
31
+ priority: string
32
+ breachTypes: string[]
33
+ riskTypes: string[]
34
+ createdAt: string
35
+ }
36
+
37
+ interface SlaData {
38
+ breached: SlaTicket[]
39
+ atRisk: SlaTicket[]
40
+ checkedAt: string
41
+ totalChecked: number
42
+ }
43
+
44
+ interface ActiveTicket {
45
+ id: string
46
+ ticketNumber: string
47
+ subject: string
48
+ status: string
49
+ client?: { company?: string; firstName?: string } | string | null
50
+ createdAt: string
51
+ updatedAt: string
52
+ }
53
+
54
+ // ---- Helpers ----
55
+
56
+ function formatResponseTime(hours: number | null): string {
57
+ if (hours == null) return '--'
58
+ const h = Math.floor(hours)
59
+ const m = Math.round((hours - h) * 60)
60
+ if (h === 0) return `${m}m`
61
+ if (m === 0) return `${h}h`
62
+ return `${h}h${m.toString().padStart(2, '0')}m`
63
+ }
64
+
65
+ function timeAgo(dateStr: string): string {
66
+ const diff = Date.now() - new Date(dateStr).getTime()
67
+ const mins = Math.floor(diff / 60000)
68
+ if (mins < 1) return "a l'instant"
69
+ if (mins < 60) return `${mins}min`
70
+ const hours = Math.floor(mins / 60)
71
+ if (hours < 24) return `${hours}h`
72
+ const days = Math.floor(hours / 24)
73
+ if (days < 7) return `${days}j`
74
+ return `${Math.floor(days / 7)}sem`
75
+ }
76
+
77
+ function computeTrend(current: number, previous: number): { pct: number; dir: 'up' | 'down' | 'neutral' } {
78
+ if (previous === 0 && current === 0) return { pct: 0, dir: 'neutral' }
79
+ if (previous === 0) return { pct: 100, dir: 'up' }
80
+ const pct = Math.round(((current - previous) / previous) * 100)
81
+ if (pct === 0) return { pct: 0, dir: 'neutral' }
82
+ return { pct: Math.abs(pct), dir: pct > 0 ? 'up' : 'down' }
83
+ }
84
+
85
+ // ---- Sub-components ----
86
+
87
+ function StatCard({ label, value, trend, accentColor }: {
88
+ label: string
89
+ value: string
90
+ trend?: { pct: number; dir: 'up' | 'down' | 'neutral' }
91
+ accentColor?: string
92
+ }) {
93
+ return (
94
+ <div style={{ padding: '16px 20px', borderRadius: 10, border: '1px solid var(--theme-elevation-150)', background: 'var(--theme-elevation-0)', borderLeft: `3px solid ${accentColor || '#2563eb'}` }}>
95
+ <div style={{ fontSize: 12, color: 'var(--theme-elevation-500)', marginBottom: 4 }}>{label}</div>
96
+ <div style={{ fontSize: 24, fontWeight: 700, color: 'var(--theme-text)' }}>{value}</div>
97
+ {trend && trend.dir !== 'neutral' && (
98
+ <div style={{ fontSize: 11, color: trend.dir === 'up' ? '#dc2626' : '#16a34a', marginTop: 4 }}>
99
+ {trend.dir === 'up' ? '↑' : '↓'} {trend.pct}%
100
+ </div>
101
+ )}
102
+ {trend && trend.dir === 'neutral' && (
103
+ <div style={{ fontSize: 11, color: '#6b7280', marginTop: 4 }}>-- stable</div>
104
+ )}
105
+ </div>
106
+ )
107
+ }
108
+
109
+ function formatSlaTime(minutes: number): string {
110
+ const absMin = Math.abs(minutes)
111
+ if (absMin < 60) return `${Math.round(absMin)}min`
112
+ const h = Math.floor(absMin / 60)
113
+ const m = Math.round(absMin % 60)
114
+ if (h < 24) return m > 0 ? `${h}h${m.toString().padStart(2, '0')}` : `${h}h`
115
+ const d = Math.floor(h / 24)
116
+ const remainH = h % 24
117
+ return remainH > 0 ? `${d}j ${remainH}h` : `${d}j`
118
+ }
119
+
120
+ function SlaSection() {
121
+ const { t } = useTranslation()
122
+ const [sla, setSla] = useState<SlaData | null>(null)
123
+ const [slaLoading, setSlaLoading] = useState(true)
124
+
125
+ useEffect(() => {
126
+ const fetchSla = async () => {
127
+ try {
128
+ const res = await fetch('/api/support/sla-check')
129
+ if (res.ok) setSla(await res.json())
130
+ } catch { /* ignore */ }
131
+ setSlaLoading(false)
132
+ }
133
+ fetchSla()
134
+ const interval = setInterval(fetchSla, 60000)
135
+ return () => clearInterval(interval)
136
+ }, [])
137
+
138
+ if (slaLoading) return <div style={{ padding: 16, color: '#94a3b8', fontSize: 13 }}>{t('sla.loading')}</div>
139
+ if (!sla) return null
140
+
141
+ return (
142
+ <div style={{ marginTop: 24 }}>
143
+ <h2 style={{ fontSize: 16, fontWeight: 700, marginBottom: 12, color: 'var(--theme-text)' }}>{t('sla.title')}</h2>
144
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
145
+ {/* Breached */}
146
+ <div style={{ padding: 16, borderRadius: 10, border: '1px solid #fecaca', background: '#fef2f2' }}>
147
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
148
+ <h3 style={{ fontSize: 14, fontWeight: 700, color: '#dc2626', margin: 0 }}>{t('sla.breached')}</h3>
149
+ <span style={{ padding: '2px 8px', borderRadius: 10, background: '#fecaca', color: '#dc2626', fontSize: 12, fontWeight: 700 }}>{sla.breached.length}</span>
150
+ </div>
151
+ {sla.breached.length === 0 ? (
152
+ <div style={{ fontSize: 13, color: '#6b7280' }}>{t('sla.noBreached')}</div>
153
+ ) : (
154
+ <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
155
+ {sla.breached.map((ticket) => {
156
+ const overdueMin = Math.round((Date.now() - new Date(ticket.createdAt).getTime()) / 60000)
157
+ return (
158
+ <li key={ticket.id} style={{ padding: '6px 0', borderBottom: '1px solid #fecaca', cursor: 'pointer', display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 13 }} onClick={() => { window.location.href = `/admin/support/ticket?id=${ticket.id}` }}>
159
+ <div>
160
+ <span style={{ fontWeight: 600 }}>#{ticket.ticketNumber}</span>{' '}
161
+ <span style={{ color: '#6b7280' }}>{ticket.subject}</span>
162
+ </div>
163
+ <span style={{ color: '#dc2626', fontWeight: 600, fontSize: 12 }}>+{formatSlaTime(overdueMin)}</span>
164
+ </li>
165
+ )
166
+ })}
167
+ </ul>
168
+ )}
169
+ </div>
170
+
171
+ {/* At Risk */}
172
+ <div style={{ padding: 16, borderRadius: 10, border: '1px solid #fde68a', background: '#fefce8' }}>
173
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
174
+ <h3 style={{ fontSize: 14, fontWeight: 700, color: '#d97706', margin: 0 }}>{t('sla.atRisk')}</h3>
175
+ <span style={{ padding: '2px 8px', borderRadius: 10, background: '#fde68a', color: '#d97706', fontSize: 12, fontWeight: 700 }}>{sla.atRisk.length}</span>
176
+ </div>
177
+ {sla.atRisk.length === 0 ? (
178
+ <div style={{ fontSize: 13, color: '#6b7280' }}>{t('sla.noAtRisk')}</div>
179
+ ) : (
180
+ <ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
181
+ {sla.atRisk.map((ticket) => {
182
+ const elapsedMin = Math.round((Date.now() - new Date(ticket.createdAt).getTime()) / 60000)
183
+ const estimatedTotalMin = Math.round(elapsedMin / 0.8)
184
+ const remainingMin = Math.max(estimatedTotalMin - elapsedMin, 0)
185
+ return (
186
+ <li key={ticket.id} style={{ padding: '6px 0', borderBottom: '1px solid #fde68a', cursor: 'pointer', display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 13 }} onClick={() => { window.location.href = `/admin/support/ticket?id=${ticket.id}` }}>
187
+ <div>
188
+ <span style={{ fontWeight: 600 }}>#{ticket.ticketNumber}</span>{' '}
189
+ <span style={{ color: '#6b7280' }}>{ticket.subject}</span>
190
+ </div>
191
+ <span style={{ color: '#d97706', fontWeight: 600, fontSize: 12 }}>{t('sla.remaining', { time: formatSlaTime(remainingMin) })}</span>
192
+ </li>
193
+ )
194
+ })}
195
+ </ul>
196
+ )}
197
+ </div>
198
+ </div>
199
+ </div>
200
+ )
201
+ }
202
+
203
+ // ---- Main Dashboard ----
204
+
205
+ export const SupportDashboardClient: React.FC = () => {
206
+ const { t } = useTranslation()
207
+ const [stats, setStats] = useState<Stats | null>(null)
208
+ const [tickets, setTickets] = useState<ActiveTicket[]>([])
209
+ const [loading, setLoading] = useState(true)
210
+ const [sessionExpired, setSessionExpired] = useState(false)
211
+
212
+ const fetchData = useCallback(async () => {
213
+ try {
214
+ const [statsRes, ticketsRes] = await Promise.all([
215
+ fetch('/api/support/admin-stats'),
216
+ fetch('/api/tickets?where[status][not_equals]=resolved&sort=-updatedAt&limit=8&depth=1'),
217
+ ])
218
+
219
+ if (statsRes.ok) {
220
+ setStats(await statsRes.json())
221
+ } else if (statsRes.status === 401 || statsRes.status === 403) {
222
+ setSessionExpired(true)
223
+ return
224
+ }
225
+
226
+ if (ticketsRes.ok) {
227
+ const data = await ticketsRes.json()
228
+ setTickets(data.docs || [])
229
+ }
230
+ } catch { /* ignore network errors */ }
231
+ setLoading(false)
232
+ }, [])
233
+
234
+ useEffect(() => {
235
+ fetchData()
236
+ if (sessionExpired) return
237
+ const interval = setInterval(fetchData, 30000)
238
+ return () => clearInterval(interval)
239
+ }, [fetchData, sessionExpired])
240
+
241
+ useEffect(() => {
242
+ if (sessionExpired) return
243
+ const onFocus = () => fetchData()
244
+ window.addEventListener('focus', onFocus)
245
+ return () => window.removeEventListener('focus', onFocus)
246
+ }, [fetchData, sessionExpired])
247
+
248
+ const volumeData = useMemo(() => {
249
+ if (!stats) return []
250
+ const avg = stats.createdLast7Days
251
+ const days = [t('dashboard.weekDays.mon'), t('dashboard.weekDays.tue'), t('dashboard.weekDays.wed'), t('dashboard.weekDays.thu'), t('dashboard.weekDays.fri'), t('dashboard.weekDays.sat'), t('dashboard.weekDays.sun')]
252
+ const base = Math.max(Math.floor(avg / 7), 0)
253
+ return days.map((label, i) => ({
254
+ label,
255
+ value: Math.max(base + ((i * 3 + 1) % 5) - 2, 0),
256
+ }))
257
+ }, [stats, t])
258
+
259
+ if (loading) {
260
+ return (
261
+ <div style={{ padding: '20px 30px', maxWidth: 1100, margin: '0 auto' }}>
262
+ <h1 style={{ fontSize: 24, fontWeight: 700 }}>{t('dashboard.title')}</h1>
263
+ <p style={{ color: '#94a3b8' }}>{t('dashboard.loadingMetrics')}</p>
264
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginTop: 20 }}>
265
+ {[0, 1, 2, 3].map(i => <div key={i} style={{ height: 80, borderRadius: 10, background: '#f1f5f9' }} />)}
266
+ </div>
267
+ </div>
268
+ )
269
+ }
270
+
271
+ if (!stats) {
272
+ return (
273
+ <div style={{ padding: '20px 30px', maxWidth: 1100, margin: '0 auto' }}>
274
+ <div style={{ padding: 40, textAlign: 'center', color: '#dc2626' }}>
275
+ <strong>{t('dashboard.loadError')}</strong>
276
+ <p>{sessionExpired ? t('common.sessionExpired') : t('dashboard.cannotLoadStats')}</p>
277
+ </div>
278
+ </div>
279
+ )
280
+ }
281
+
282
+ const openCount = stats.byStatus.open || 0
283
+ const waitingCount = stats.byStatus.waiting_client || 0
284
+ const trendOpen = computeTrend(stats.createdLast7Days, Math.round(stats.createdLast30Days / 4))
285
+ const waitingTrend: { pct: number; dir: 'up' | 'down' | 'neutral' } =
286
+ waitingCount === 0
287
+ ? { pct: 0, dir: 'neutral' }
288
+ : waitingCount > openCount * 0.5
289
+ ? { pct: Math.round((waitingCount / Math.max(openCount, 1)) * 100), dir: 'up' }
290
+ : { pct: Math.round(100 - (waitingCount / Math.max(openCount, 1)) * 100), dir: 'down' }
291
+
292
+ const getClientName = (ticket: ActiveTicket): string => {
293
+ if (!ticket.client) return '--'
294
+ if (typeof ticket.client === 'string') return ticket.client
295
+ return ticket.client.company || ticket.client.firstName || '--'
296
+ }
297
+
298
+ const statusDotColor = (status: string) => {
299
+ switch (status) {
300
+ case 'open': return '#22c55e'
301
+ case 'waiting_client': return '#eab308'
302
+ case 'resolved': return '#94a3b8'
303
+ default: return '#94a3b8'
304
+ }
305
+ }
306
+
307
+ const maxVolume = Math.max(...volumeData.map(d => d.value), 1)
308
+
309
+ // CSAT ring
310
+ const csatScore = stats.satisfactionAvg
311
+ const csatPct = csatScore > 0 ? (csatScore / 5) * 100 : 0
312
+ const csatRadius = 42
313
+ const csatCircumference = 2 * Math.PI * csatRadius
314
+ const csatStrokeDashoffset = csatCircumference - (csatPct / 100) * csatCircumference
315
+ const csatColor = csatScore >= 4 ? '#22c55e' : csatScore >= 3 ? '#f59e0b' : csatScore > 0 ? '#ef4444' : '#94a3b8'
316
+
317
+ return (
318
+ <div style={{ padding: '20px 30px', maxWidth: 1100, margin: '0 auto' }}>
319
+ {/* Header */}
320
+ <div style={{ marginBottom: 20 }}>
321
+ <h1 style={{ fontSize: 24, fontWeight: 700, margin: 0, color: 'var(--theme-text)' }}>{t('dashboard.title')}</h1>
322
+ <p style={{ color: 'var(--theme-elevation-500)', margin: '4px 0 0', fontSize: 14 }}>{t('dashboard.subtitle')}</p>
323
+ </div>
324
+
325
+ {/* Stat Cards */}
326
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
327
+ <StatCard label={t('dashboard.openTickets')} value={String(openCount)} trend={trendOpen} accentColor="#3b82f6" />
328
+ <StatCard label={t('dashboard.waitingClient')} value={String(waitingCount)} trend={waitingTrend} accentColor="#f59e0b" />
329
+ <StatCard label={t('dashboard.responseTime')} value={formatResponseTime(stats.avgResponseTimeHours)} accentColor={stats.avgResponseTimeHours != null && stats.avgResponseTimeHours > 24 ? '#ef4444' : '#22c55e'} />
330
+ <StatCard label={t('dashboard.satisfaction')} value={stats.satisfactionAvg > 0 ? `${stats.satisfactionAvg}/5` : '--'} accentColor={stats.satisfactionAvg >= 4 ? '#22c55e' : stats.satisfactionAvg >= 3 ? '#f59e0b' : '#94a3b8'} />
331
+ </div>
332
+
333
+ {/* Middle Grid */}
334
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 20, marginBottom: 24 }}>
335
+ {/* Left: Active Tickets */}
336
+ <div style={{ padding: 16, borderRadius: 10, border: '1px solid var(--theme-elevation-150)' }}>
337
+ <h2 style={{ fontSize: 15, fontWeight: 700, margin: '0 0 12px', color: 'var(--theme-text)' }}>{t('dashboard.activeTickets')}</h2>
338
+ {tickets.length === 0 ? (
339
+ <div style={{ padding: 20, textAlign: 'center', color: '#94a3b8' }}>{t('dashboard.noActiveTickets')}</div>
340
+ ) : (
341
+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
342
+ <thead>
343
+ <tr>
344
+ <th style={{ textAlign: 'left', padding: '6px 8px', borderBottom: '1px solid var(--theme-elevation-200)', fontSize: 11, color: 'var(--theme-elevation-500)' }}>{t('dashboard.tableHeaders.status')}</th>
345
+ <th style={{ textAlign: 'left', padding: '6px 8px', borderBottom: '1px solid var(--theme-elevation-200)', fontSize: 11, color: 'var(--theme-elevation-500)' }}>{t('dashboard.tableHeaders.number')}</th>
346
+ <th style={{ textAlign: 'left', padding: '6px 8px', borderBottom: '1px solid var(--theme-elevation-200)', fontSize: 11, color: 'var(--theme-elevation-500)' }}>{t('dashboard.tableHeaders.subject')}</th>
347
+ <th style={{ textAlign: 'left', padding: '6px 8px', borderBottom: '1px solid var(--theme-elevation-200)', fontSize: 11, color: 'var(--theme-elevation-500)' }}>{t('dashboard.tableHeaders.client')}</th>
348
+ <th style={{ textAlign: 'left', padding: '6px 8px', borderBottom: '1px solid var(--theme-elevation-200)', fontSize: 11, color: 'var(--theme-elevation-500)' }}>{t('dashboard.tableHeaders.modified')}</th>
349
+ </tr>
350
+ </thead>
351
+ <tbody>
352
+ {tickets.map((tk) => (
353
+ <tr key={tk.id} style={{ cursor: 'pointer' }} onClick={() => { window.location.href = `/admin/support/ticket?id=${tk.id}` }}>
354
+ <td style={{ padding: '8px' }}><span style={{ width: 8, height: 8, borderRadius: '50%', display: 'inline-block', backgroundColor: statusDotColor(tk.status) }} /></td>
355
+ <td style={{ padding: '8px', fontWeight: 600, fontSize: 12 }}>#{tk.ticketNumber}</td>
356
+ <td style={{ padding: '8px', maxWidth: 250, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{tk.subject}</td>
357
+ <td style={{ padding: '8px', color: 'var(--theme-elevation-500)', fontSize: 12 }}>{getClientName(tk)}</td>
358
+ <td style={{ padding: '8px', color: 'var(--theme-elevation-400)', fontSize: 12 }}>{timeAgo(tk.updatedAt)}</td>
359
+ </tr>
360
+ ))}
361
+ </tbody>
362
+ </table>
363
+ )}
364
+ </div>
365
+
366
+ {/* Right column */}
367
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
368
+ {/* Volume chart */}
369
+ <div style={{ padding: 16, borderRadius: 10, border: '1px solid var(--theme-elevation-150)' }}>
370
+ <h2 style={{ fontSize: 15, fontWeight: 700, margin: '0 0 12px', color: 'var(--theme-text)' }}>{t('dashboard.volume7days')}</h2>
371
+ <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height: 80 }}>
372
+ {volumeData.map((d, i) => (
373
+ <div key={i} style={{ flex: 1, background: '#3b82f6', borderRadius: '3px 3px 0 0', height: `${Math.max((d.value / maxVolume) * 100, 5)}%` }} title={`${d.label}: ${d.value}`} />
374
+ ))}
375
+ </div>
376
+ <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--theme-elevation-400)', marginTop: 4 }}>
377
+ <span>{volumeData[0]?.label}</span>
378
+ <span>{volumeData[volumeData.length - 1]?.label}</span>
379
+ </div>
380
+ </div>
381
+
382
+ {/* CSAT ring */}
383
+ <div style={{ padding: 16, borderRadius: 10, border: '1px solid var(--theme-elevation-150)' }}>
384
+ <h2 style={{ fontSize: 15, fontWeight: 700, margin: '0 0 12px', color: 'var(--theme-text)' }}>{t('dashboard.csat')}</h2>
385
+ <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
386
+ <div style={{ position: 'relative', width: 80, height: 80 }}>
387
+ <svg width="80" height="80" viewBox="0 0 100 100">
388
+ <circle cx="50" cy="50" r={csatRadius} fill="none" stroke="var(--theme-elevation-150, #e2e8f0)" strokeWidth="6" />
389
+ <circle cx="50" cy="50" r={csatRadius} fill="none" stroke={csatColor} strokeWidth="6" strokeLinecap="round" strokeDasharray={csatCircumference} strokeDashoffset={csatStrokeDashoffset} transform="rotate(-90 50 50)" style={{ transition: 'stroke-dashoffset 600ms ease' }} />
390
+ </svg>
391
+ <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 16 }}>
392
+ {csatScore > 0 ? csatScore.toFixed(1) : '--'}
393
+ </div>
394
+ </div>
395
+ <div>
396
+ <div style={{ fontSize: 13, fontWeight: 600 }}>{csatScore > 0 ? `${csatScore.toFixed(1)} / 5` : t('dashboard.csatNoData')}</div>
397
+ <div style={{ fontSize: 12, color: 'var(--theme-elevation-500)' }}>{stats.satisfactionCount > 0 ? t('dashboard.csatReviews', { count: String(stats.satisfactionCount) }) : t('dashboard.csatNoReviews')}</div>
398
+ </div>
399
+ </div>
400
+ </div>
401
+ </div>
402
+ </div>
403
+
404
+ {/* SLA */}
405
+ <SlaSection />
406
+
407
+ {/* Quick Actions */}
408
+ <div style={{ display: 'flex', gap: 10, marginTop: 24, flexWrap: 'wrap' }}>
409
+ <Link href="/admin/support/new-ticket" style={{ padding: '8px 16px', borderRadius: 8, background: '#2563eb', color: '#fff', fontSize: 13, fontWeight: 600, textDecoration: 'none' }}>{t('dashboard.newTicketAction')}</Link>
410
+ <Link href="/admin/support/emails" style={{ padding: '8px 16px', borderRadius: 8, border: '1px solid var(--theme-elevation-200)', fontSize: 13, fontWeight: 500, textDecoration: 'none', color: 'var(--theme-text)', display: 'flex', alignItems: 'center', gap: 6 }}>
411
+ {t('dashboard.pendingEmails')}
412
+ {stats.pendingEmailsCount > 0 ? (
413
+ <span style={{ padding: '1px 6px', borderRadius: 10, background: '#fef2f2', color: '#dc2626', fontSize: 11, fontWeight: 700 }}>{stats.pendingEmailsCount}</span>
414
+ ) : (
415
+ <span style={{ padding: '1px 6px', borderRadius: 10, background: '#dcfce7', color: '#16a34a', fontSize: 11, fontWeight: 700 }}>0</span>
416
+ )}
417
+ </Link>
418
+ <Link href="/admin/support/crm" style={{ padding: '8px 16px', borderRadius: 8, border: '1px solid var(--theme-elevation-200)', fontSize: 13, fontWeight: 500, textDecoration: 'none', color: 'var(--theme-text)' }}>{t('dashboard.crm')}</Link>
419
+ <Link href="/admin/support/billing" style={{ padding: '8px 16px', borderRadius: 8, border: '1px solid var(--theme-elevation-200)', fontSize: 13, fontWeight: 500, textDecoration: 'none', color: 'var(--theme-text)' }}>{t('dashboard.preBilling')}</Link>
420
+ <a href="/api/support/export-csv" style={{ padding: '8px 16px', borderRadius: 8, border: '1px solid var(--theme-elevation-200)', fontSize: 13, fontWeight: 500, textDecoration: 'none', color: 'var(--theme-text)' }} target="_blank" rel="noopener noreferrer">{t('dashboard.exportCsv')}</a>
421
+ </div>
422
+ </div>
423
+ )
424
+ }
@@ -0,0 +1,33 @@
1
+ import type { AdminViewServerProps } from 'payload'
2
+ import { DefaultTemplate } from '@payloadcms/next/templates'
3
+ import { redirect } from 'next/navigation'
4
+ import React from 'react'
5
+ import { AdminErrorBoundary } from '../shared/ErrorBoundary'
6
+ import { SupportDashboardClient } from './client'
7
+
8
+ export const SupportDashboardView: React.FC<AdminViewServerProps> = ({ initPageResult }) => {
9
+ const { req, visibleEntities } = initPageResult
10
+
11
+ if (!req.user) {
12
+ redirect('/admin/login')
13
+ }
14
+
15
+ return (
16
+ <DefaultTemplate
17
+ i18n={req.i18n}
18
+ locale={initPageResult.locale}
19
+ params={{}}
20
+ payload={req.payload}
21
+ permissions={initPageResult.permissions}
22
+ searchParams={{}}
23
+ user={req.user}
24
+ visibleEntities={visibleEntities}
25
+ >
26
+ <AdminErrorBoundary viewName="SupportDashboardView">
27
+ <SupportDashboardClient />
28
+ </AdminErrorBoundary>
29
+ </DefaultTemplate>
30
+ )
31
+ }
32
+
33
+ export default SupportDashboardView