@consilioweb/payload-support 0.5.2 → 0.6.0

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 (85) hide show
  1. package/dist/components/TicketConversation/components/AISummaryPanel.js +76 -0
  2. package/dist/components/TicketConversation/components/ActionPanels.js +118 -0
  3. package/dist/components/TicketConversation/components/ActivityLog.js +23 -0
  4. package/dist/components/TicketConversation/components/ClientBar.js +42 -0
  5. package/dist/components/TicketConversation/components/ClientHistory.js +137 -0
  6. package/dist/components/TicketConversation/components/CodeBlock.js +152 -0
  7. package/dist/components/TicketConversation/components/CodeBlockInserter.js +155 -0
  8. package/dist/components/TicketConversation/components/QuickActions.js +65 -0
  9. package/dist/components/TicketConversation/components/TicketHeader.js +92 -0
  10. package/dist/components/TicketConversation/components/TimeTrackingPanel.js +133 -0
  11. package/dist/components/TicketConversation/config.js +41 -0
  12. package/dist/components/TicketConversation/constants.js +96 -0
  13. package/dist/components/TicketConversation/context.js +11 -0
  14. package/dist/components/TicketConversation/hooks/useAI.js +176 -0
  15. package/dist/components/TicketConversation/hooks/useMessageActions.js +135 -0
  16. package/dist/components/TicketConversation/hooks/useReply.js +187 -0
  17. package/dist/components/TicketConversation/hooks/useTicketActions.js +230 -0
  18. package/dist/components/TicketConversation/hooks/useTimeTracking.js +122 -0
  19. package/dist/components/TicketConversation/hooks/useTranslation.js +70 -0
  20. package/dist/components/TicketConversation/index.js +1123 -0
  21. package/dist/components/TicketConversation/locales/en.json +878 -0
  22. package/dist/components/TicketConversation/locales/fr.json +878 -0
  23. package/dist/components/TicketConversation/types.js +2 -0
  24. package/dist/components/TicketConversation/utils.js +25 -0
  25. package/dist/index.cjs +2 -2
  26. package/dist/index.js +2 -2
  27. package/dist/styles/BillingView.module.scss +311 -0
  28. package/dist/styles/ChatView.module.scss +438 -0
  29. package/dist/styles/CommandPalette.module.scss +160 -0
  30. package/dist/styles/CrmView.module.scss +554 -0
  31. package/dist/styles/EmailTracking.module.scss +238 -0
  32. package/dist/styles/ImportConversation.module.scss +267 -0
  33. package/dist/styles/Layout.module.scss +55 -0
  34. package/dist/styles/Logs.module.scss +164 -0
  35. package/dist/styles/NewTicket.module.scss +143 -0
  36. package/dist/styles/PendingEmails.module.scss +629 -0
  37. package/dist/styles/SupportDashboard.module.scss +649 -0
  38. package/dist/styles/TicketDetail.module.scss +1050 -0
  39. package/dist/styles/TicketInbox.module.scss +296 -0
  40. package/dist/styles/TicketingSettings.module.scss +358 -0
  41. package/dist/styles/TimeDashboard.module.scss +287 -0
  42. package/dist/styles/_tokens.scss +78 -0
  43. package/dist/styles/theme.css +633 -0
  44. package/dist/views/BillingView/client.js +204 -0
  45. package/dist/views/BillingView/index.js +29 -0
  46. package/dist/views/ChatView/client.js +252 -0
  47. package/dist/views/ChatView/index.js +29 -0
  48. package/dist/views/CrmView/client.js +232 -0
  49. package/dist/views/CrmView/index.js +29 -0
  50. package/dist/views/EmailTrackingView/client.js +154 -0
  51. package/dist/views/EmailTrackingView/index.js +29 -0
  52. package/dist/views/ImportConversationView/client.js +204 -0
  53. package/dist/views/ImportConversationView/index.js +29 -0
  54. package/dist/views/LogsView/client.js +148 -0
  55. package/dist/views/LogsView/index.js +27 -0
  56. package/dist/views/NewTicketView/client.js +224 -0
  57. package/dist/views/NewTicketView/index.js +27 -0
  58. package/dist/views/PendingEmailsView/client.js +172 -0
  59. package/dist/views/PendingEmailsView/index.js +29 -0
  60. package/dist/views/SupportDashboardView/client.js +296 -0
  61. package/dist/views/SupportDashboardView/index.js +29 -0
  62. package/dist/views/TicketDetailView/client.js +844 -0
  63. package/dist/views/TicketDetailView/index.js +29 -0
  64. package/dist/views/TicketInboxView/client.js +294 -0
  65. package/dist/views/TicketInboxView/index.js +27 -0
  66. package/dist/{views.css → views/TicketingSettingsView/TicketingSettings.module.scss} +138 -66
  67. package/dist/views/TicketingSettingsView/client.js +728 -0
  68. package/dist/views/TicketingSettingsView/index.js +29 -0
  69. package/dist/views/TimeDashboardView/client.js +164 -0
  70. package/dist/views/TimeDashboardView/index.js +29 -0
  71. package/dist/views/shared/AdminViewHeader.js +67 -0
  72. package/dist/views/shared/ErrorBoundary.js +50 -0
  73. package/dist/views/shared/Skeleton.js +72 -0
  74. package/dist/views/shared/adminTokens.js +32 -0
  75. package/dist/views/shared/config.js +41 -0
  76. package/dist/views/shared/index.js +6 -0
  77. package/package.json +8 -12
  78. package/src/collections/Tickets.ts +1 -1
  79. package/src/components/TicketConversation/index.tsx +21 -2
  80. package/src/plugin.ts +3 -2
  81. package/dist/views.cjs +0 -6172
  82. package/dist/views.d.cts +0 -30
  83. package/dist/views.d.ts +0 -30
  84. package/dist/views.js +0 -6153
  85. package/src/views.ts +0 -16
@@ -0,0 +1,204 @@
1
+ "use client";
2
+ import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
3
+ import React, { useState, useCallback } from 'react';
4
+ import { useTranslation } from '../../components/TicketConversation/hooks/useTranslation';
5
+
6
+ function formatDuration(minutes) {
7
+ const h = Math.floor(minutes / 60);
8
+ const m = minutes % 60;
9
+ if (h === 0) return `${m}min`;
10
+ if (m === 0) return `${h}h`;
11
+ return `${h}h ${m}min`;
12
+ }
13
+ function formatAmount(minutes, rate) {
14
+ return (minutes / 60 * rate).toFixed(2);
15
+ }
16
+ function getMonthRange(offset) {
17
+ const now = /* @__PURE__ */ new Date();
18
+ const start = new Date(now.getFullYear(), now.getMonth() + offset, 1);
19
+ const end = new Date(now.getFullYear(), now.getMonth() + offset + 1, 0);
20
+ return { from: start.toISOString().split("T")[0], to: end.toISOString().split("T")[0] };
21
+ }
22
+ function getQuarterRange(offset) {
23
+ const now = /* @__PURE__ */ new Date();
24
+ const q = Math.floor(now.getMonth() / 3) + offset;
25
+ const start = new Date(now.getFullYear(), q * 3, 1);
26
+ const end = new Date(now.getFullYear(), q * 3 + 3, 0);
27
+ return { from: start.toISOString().split("T")[0], to: end.toISOString().split("T")[0] };
28
+ }
29
+ const BillingClient = () => {
30
+ const { t } = useTranslation();
31
+ const [from, setFrom] = useState(() => getMonthRange(0).from);
32
+ const [to, setTo] = useState(() => getMonthRange(0).to);
33
+ const [projectId, setProjectId] = useState("");
34
+ const [rate, setRate] = useState(60);
35
+ const [data, setData] = useState(null);
36
+ const [loading, setLoading] = useState(false);
37
+ const [projects, setProjects] = useState([]);
38
+ const [projectsLoaded, setProjectsLoaded] = useState(false);
39
+ const [copied, setCopied] = useState(false);
40
+ const loadProjects = useCallback(async () => {
41
+ if (projectsLoaded) return;
42
+ try {
43
+ const res = await fetch("/api/projects?limit=100&depth=0&sort=name");
44
+ if (res.ok) {
45
+ const json = await res.json();
46
+ setProjects(json.docs?.map((p) => ({ id: p.id, name: p.name })) || []);
47
+ }
48
+ } catch (err) {
49
+ console.warn("[support] loadProjects error:", err);
50
+ }
51
+ setProjectsLoaded(true);
52
+ }, [projectsLoaded]);
53
+ React.useEffect(() => {
54
+ loadProjects();
55
+ }, [loadProjects]);
56
+ const fetchBilling = useCallback(async () => {
57
+ setLoading(true);
58
+ try {
59
+ const params = new URLSearchParams({ from, to });
60
+ if (projectId) params.set("projectId", projectId);
61
+ const res = await fetch(`/api/support/billing?${params}`);
62
+ if (res.ok) setData(await res.json());
63
+ } catch (err) {
64
+ console.warn("[support] fetchBilling error:", err);
65
+ }
66
+ setLoading(false);
67
+ }, [from, to, projectId]);
68
+ const setPeriod = (range) => {
69
+ setFrom(range.from);
70
+ setTo(range.to);
71
+ };
72
+ const copyRecap = useCallback(() => {
73
+ if (!data) return;
74
+ const lines = [`PRE-FACTURATION -- Du ${from} au ${to}`, `Taux horaire : ${rate} EUR/h`, "=".repeat(50)];
75
+ for (const group of data.groups) {
76
+ lines.push("", `PROJET : ${group.project?.name || "Sans projet"}`);
77
+ if (group.client?.company) lines.push(`Client : ${group.client.company}`);
78
+ for (const ticket of group.tickets) {
79
+ lines.push(` ${ticket.ticketNumber} -- ${ticket.subject}`);
80
+ for (const entry of ticket.entries) lines.push(` ${entry.date} | ${formatDuration(entry.duration)} | ${entry.description || "-"}`);
81
+ lines.push(` Sous-total : ${formatDuration(ticket.totalMinutes)} = ${formatAmount(ticket.totalMinutes, rate)} EUR`);
82
+ }
83
+ }
84
+ lines.push("", "=".repeat(50), `TOTAL : ${formatDuration(data.grandTotalMinutes)} = ${formatAmount(data.grandTotalMinutes, rate)} EUR`);
85
+ navigator.clipboard.writeText(lines.join("\n"));
86
+ setCopied(true);
87
+ setTimeout(() => setCopied(false), 2e3);
88
+ }, [data, from, to, rate]);
89
+ const S = {
90
+ page: { padding: "20px 30px", maxWidth: 1100, margin: "0 auto" },
91
+ filters: { marginBottom: 20 },
92
+ quickPeriod: { display: "flex", gap: 6, marginBottom: 8 },
93
+ btn: { padding: "6px 12px", borderRadius: 6, border: "1px solid var(--theme-elevation-200)", fontSize: 12, cursor: "pointer", background: "var(--theme-elevation-0)", color: "var(--theme-text)" },
94
+ btnPrimary: { padding: "6px 12px", borderRadius: 6, border: "none", fontSize: 12, cursor: "pointer", background: "#2563eb", color: "#fff", fontWeight: 600 },
95
+ filterRow: { display: "flex", gap: 12, alignItems: "flex-end", flexWrap: "wrap" },
96
+ fieldGroup: { display: "flex", flexDirection: "column", gap: 4 },
97
+ label: { fontSize: 11, fontWeight: 600, color: "var(--theme-elevation-500)" },
98
+ input: { padding: "6px 10px", borderRadius: 6, border: "1px solid var(--theme-elevation-200)", fontSize: 12, color: "var(--theme-text)", background: "var(--theme-elevation-0)" },
99
+ select: { padding: "6px 10px", borderRadius: 6, border: "1px solid var(--theme-elevation-200)", fontSize: 12, color: "var(--theme-text)", background: "var(--theme-elevation-0)" },
100
+ groupCard: { marginBottom: 16, borderRadius: 10, border: "1px solid var(--theme-elevation-150)", overflow: "hidden" },
101
+ groupHeader: { display: "flex", justifyContent: "space-between", padding: "12px 16px", background: "var(--theme-elevation-50)", borderBottom: "1px solid var(--theme-elevation-150)" },
102
+ table: { width: "100%", borderCollapse: "collapse", fontSize: 12 },
103
+ th: { textAlign: "left", padding: "6px 8px", borderBottom: "1px solid var(--theme-elevation-200)", fontSize: 11, color: "var(--theme-elevation-500)" },
104
+ td: { padding: "6px 8px", borderBottom: "1px solid var(--theme-elevation-100)" },
105
+ grandTotal: { padding: 16, borderRadius: 10, border: "2px solid #2563eb", display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 16 }
106
+ };
107
+ return /* @__PURE__ */ jsxs("div", { style: S.page, children: [
108
+ /* @__PURE__ */ jsxs("div", { style: { marginBottom: 16 }, children: [
109
+ /* @__PURE__ */ jsx("h1", { style: { fontSize: 22, fontWeight: 700, margin: 0 }, children: t("billing.title") }),
110
+ /* @__PURE__ */ jsx("p", { style: { fontSize: 13, color: "var(--theme-elevation-500)", margin: "4px 0 0" }, children: t("billing.subtitle") })
111
+ ] }),
112
+ /* @__PURE__ */ jsxs("div", { style: S.filters, children: [
113
+ /* @__PURE__ */ jsxs("div", { style: S.quickPeriod, children: [
114
+ /* @__PURE__ */ jsx("button", { style: S.btnPrimary, onClick: () => setPeriod(getMonthRange(0)), children: t("billing.filters.thisMonth") }),
115
+ /* @__PURE__ */ jsx("button", { style: S.btn, onClick: () => setPeriod(getMonthRange(-1)), children: t("billing.filters.lastMonth") }),
116
+ /* @__PURE__ */ jsx("button", { style: S.btn, onClick: () => setPeriod(getQuarterRange(0)), children: t("billing.filters.thisQuarter") })
117
+ ] }),
118
+ /* @__PURE__ */ jsxs("div", { style: S.filterRow, children: [
119
+ /* @__PURE__ */ jsxs("div", { style: S.fieldGroup, children: [
120
+ /* @__PURE__ */ jsx("label", { style: S.label, children: t("billing.filters.from") }),
121
+ /* @__PURE__ */ jsx("input", { type: "date", value: from, onChange: (e) => setFrom(e.target.value), style: S.input })
122
+ ] }),
123
+ /* @__PURE__ */ jsxs("div", { style: S.fieldGroup, children: [
124
+ /* @__PURE__ */ jsx("label", { style: S.label, children: t("billing.filters.to") }),
125
+ /* @__PURE__ */ jsx("input", { type: "date", value: to, onChange: (e) => setTo(e.target.value), style: S.input })
126
+ ] }),
127
+ /* @__PURE__ */ jsxs("div", { style: S.fieldGroup, children: [
128
+ /* @__PURE__ */ jsx("label", { style: S.label, children: t("billing.filters.project") }),
129
+ /* @__PURE__ */ jsxs("select", { value: projectId, onChange: (e) => setProjectId(e.target.value), style: S.select, children: [
130
+ /* @__PURE__ */ jsx("option", { value: "", children: t("common.all") }),
131
+ projects.map((p) => /* @__PURE__ */ jsx("option", { value: p.id, children: p.name }, p.id))
132
+ ] })
133
+ ] }),
134
+ /* @__PURE__ */ jsxs("div", { style: S.fieldGroup, children: [
135
+ /* @__PURE__ */ jsx("label", { style: S.label, children: t("billing.filters.hourlyRate") }),
136
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: 4, alignItems: "center" }, children: [
137
+ /* @__PURE__ */ jsx("input", { type: "number", value: rate, onChange: (e) => setRate(Number(e.target.value)), style: { ...S.input, width: 70 }, min: 0 }),
138
+ /* @__PURE__ */ jsx("span", { style: { fontSize: 11 }, children: t("billing.filters.rateUnit") })
139
+ ] })
140
+ ] }),
141
+ /* @__PURE__ */ jsx("button", { style: S.btnPrimary, onClick: fetchBilling, disabled: loading, children: loading ? t("billing.filters.loading") : t("billing.filters.load") })
142
+ ] })
143
+ ] }),
144
+ data && /* @__PURE__ */ jsx(Fragment, { children: data.groups.length === 0 ? /* @__PURE__ */ jsx("div", { style: { padding: 40, textAlign: "center", color: "#94a3b8" }, children: t("billing.empty") }) : /* @__PURE__ */ jsxs(Fragment, { children: [
145
+ data.groups.map((group, gi) => /* @__PURE__ */ jsxs("div", { style: S.groupCard, children: [
146
+ /* @__PURE__ */ jsxs("div", { style: S.groupHeader, children: [
147
+ /* @__PURE__ */ jsxs("div", { children: [
148
+ /* @__PURE__ */ jsx("span", { style: { fontWeight: 700 }, children: group.project?.name || "Sans projet" }),
149
+ group.client?.company && /* @__PURE__ */ jsxs("span", { style: { color: "var(--theme-elevation-500)" }, children: [
150
+ " -- ",
151
+ group.client.company
152
+ ] })
153
+ ] }),
154
+ /* @__PURE__ */ jsxs("div", { style: { textAlign: "right" }, children: [
155
+ /* @__PURE__ */ jsx("div", { style: { fontWeight: 700 }, children: formatDuration(group.totalMinutes) }),
156
+ /* @__PURE__ */ jsxs("div", { style: { fontSize: 12, color: "#2563eb", fontWeight: 600 }, children: [
157
+ formatAmount(group.totalMinutes, rate),
158
+ " EUR"
159
+ ] })
160
+ ] })
161
+ ] }),
162
+ /* @__PURE__ */ jsxs("table", { style: S.table, children: [
163
+ /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [
164
+ /* @__PURE__ */ jsx("th", { style: S.th, children: t("billing.table.ticketNumber") }),
165
+ /* @__PURE__ */ jsx("th", { style: S.th, children: t("billing.table.subject") }),
166
+ /* @__PURE__ */ jsx("th", { style: S.th, children: t("billing.table.date") }),
167
+ /* @__PURE__ */ jsx("th", { style: S.th, children: t("billing.table.duration") }),
168
+ /* @__PURE__ */ jsx("th", { style: S.th, children: t("billing.table.description") }),
169
+ /* @__PURE__ */ jsx("th", { style: { ...S.th, textAlign: "right" }, children: t("billing.table.amount") })
170
+ ] }) }),
171
+ /* @__PURE__ */ jsx("tbody", { children: group.tickets.map((ticket) => ticket.entries.map((entry, ei) => /* @__PURE__ */ jsxs("tr", { children: [
172
+ ei === 0 && /* @__PURE__ */ jsxs(Fragment, { children: [
173
+ /* @__PURE__ */ jsx("td", { style: { ...S.td, fontWeight: 600 }, rowSpan: ticket.entries.length, children: /* @__PURE__ */ jsx("a", { href: `/admin/support/ticket?id=${ticket.id}`, style: { color: "#2563eb", textDecoration: "none" }, children: ticket.ticketNumber }) }),
174
+ /* @__PURE__ */ jsx("td", { style: S.td, rowSpan: ticket.entries.length, children: ticket.subject })
175
+ ] }),
176
+ /* @__PURE__ */ jsx("td", { style: S.td, children: entry.date }),
177
+ /* @__PURE__ */ jsx("td", { style: S.td, children: formatDuration(entry.duration) }),
178
+ /* @__PURE__ */ jsx("td", { style: S.td, children: entry.description || "-" }),
179
+ /* @__PURE__ */ jsxs("td", { style: { ...S.td, textAlign: "right", fontWeight: 600 }, children: [
180
+ formatAmount(entry.duration, rate),
181
+ " EUR"
182
+ ] })
183
+ ] }, `${ticket.id}-${ei}`))) })
184
+ ] })
185
+ ] }, gi)),
186
+ /* @__PURE__ */ jsxs("div", { style: S.grandTotal, children: [
187
+ /* @__PURE__ */ jsxs("div", { children: [
188
+ /* @__PURE__ */ jsx("div", { style: { fontSize: 12, color: "var(--theme-elevation-500)" }, children: t("billing.totals.billableTicketsPlural", { count: String(data.groups.reduce((s2, g) => s2 + g.tickets.length, 0)) }) }),
189
+ /* @__PURE__ */ jsxs("div", { style: { fontSize: 18, fontWeight: 700 }, children: [
190
+ t("billing.totals.total"),
191
+ " : ",
192
+ formatDuration(data.grandTotalMinutes),
193
+ " = ",
194
+ formatAmount(data.grandTotalMinutes, rate),
195
+ " EUR"
196
+ ] })
197
+ ] }),
198
+ /* @__PURE__ */ jsx("button", { style: S.btnPrimary, onClick: copyRecap, children: copied ? t("billing.totals.copiedRecap") : t("billing.totals.copyRecap") })
199
+ ] })
200
+ ] }) })
201
+ ] });
202
+ };
203
+
204
+ export { BillingClient };
@@ -0,0 +1,29 @@
1
+ import { jsx } from 'react/jsx-runtime';
2
+ import { DefaultTemplate } from '@payloadcms/next/templates';
3
+ import { redirect } from 'next/navigation';
4
+ import { AdminErrorBoundary } from '../shared/ErrorBoundary';
5
+ import { BillingClient } from './client';
6
+
7
+ const BillingView = ({ initPageResult }) => {
8
+ const { req, visibleEntities } = initPageResult;
9
+ if (!req.user) {
10
+ redirect("/admin/login");
11
+ }
12
+ return /* @__PURE__ */ jsx(
13
+ DefaultTemplate,
14
+ {
15
+ i18n: req.i18n,
16
+ locale: initPageResult.locale,
17
+ params: {},
18
+ payload: req.payload,
19
+ permissions: initPageResult.permissions,
20
+ searchParams: {},
21
+ user: req.user,
22
+ visibleEntities,
23
+ children: /* @__PURE__ */ jsx(AdminErrorBoundary, { viewName: "BillingView", children: /* @__PURE__ */ jsx(BillingClient, {}) })
24
+ }
25
+ );
26
+ };
27
+ var BillingView_default = BillingView;
28
+
29
+ export { BillingView, BillingView_default as default };
@@ -0,0 +1,252 @@
1
+ "use client";
2
+ import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
3
+ import { useState, useRef, useCallback, useEffect } from 'react';
4
+ import { useTranslation } from '../../components/TicketConversation/hooks/useTranslation';
5
+
6
+ const ChatViewClient = () => {
7
+ const { t } = useTranslation();
8
+ const [sessions, setSessions] = useState({ active: [], closed: [] });
9
+ const [selectedSession, setSelectedSession] = useState(null);
10
+ const [messages, setMessages] = useState([]);
11
+ const [input, setInput] = useState("");
12
+ const [sending, setSending] = useState(false);
13
+ const [showClosed, setShowClosed] = useState(false);
14
+ const [loading, setLoading] = useState(true);
15
+ const [cannedResponses, setCannedResponses] = useState([]);
16
+ const messagesEndRef = useRef(null);
17
+ const lastFetchRef = useRef(null);
18
+ const [sessionExpired, setSessionExpired] = useState(false);
19
+ const sessionsESRef = useRef(null);
20
+ const messagesESRef = useRef(null);
21
+ const fetchSessions = useCallback(async () => {
22
+ try {
23
+ const res = await fetch("/api/support/admin-chat");
24
+ if (res.status === 401 || res.status === 403) {
25
+ setSessionExpired(true);
26
+ return;
27
+ }
28
+ if (res.ok) {
29
+ const data = await res.json();
30
+ setSessions({ active: data.active || [], closed: data.closed || [] });
31
+ }
32
+ } catch {
33
+ }
34
+ setLoading(false);
35
+ }, []);
36
+ useEffect(() => {
37
+ if (sessionExpired) return;
38
+ fetchSessions();
39
+ if (typeof EventSource !== "undefined") {
40
+ const es = new EventSource("/api/support/admin-chat-stream");
41
+ sessionsESRef.current = es;
42
+ es.onmessage = (event) => {
43
+ try {
44
+ const parsed = JSON.parse(event.data);
45
+ if (parsed.type === "sessions" && parsed.data) {
46
+ setSessions({ active: parsed.data.active || [], closed: parsed.data.closed || [] });
47
+ setLoading(false);
48
+ }
49
+ } catch {
50
+ }
51
+ };
52
+ es.onerror = () => {
53
+ es.close();
54
+ sessionsESRef.current = null;
55
+ const iv2 = setInterval(fetchSessions, 5e3);
56
+ return () => clearInterval(iv2);
57
+ };
58
+ return () => {
59
+ es.close();
60
+ sessionsESRef.current = null;
61
+ };
62
+ }
63
+ const iv = setInterval(fetchSessions, 5e3);
64
+ return () => clearInterval(iv);
65
+ }, [fetchSessions, sessionExpired]);
66
+ useEffect(() => {
67
+ fetch("/api/canned-responses?sort=sortOrder&limit=50&depth=0", { credentials: "include" }).then((res) => res.ok ? res.json() : null).then((data) => {
68
+ if (data?.docs) setCannedResponses(data.docs);
69
+ }).catch(() => {
70
+ });
71
+ }, []);
72
+ useEffect(() => {
73
+ if (!selectedSession) return;
74
+ const fetchMessages = async () => {
75
+ try {
76
+ const after = lastFetchRef.current || "";
77
+ const url = `/api/support/admin-chat?session=${selectedSession}${after ? `&after=${after}` : ""}`;
78
+ const res = await fetch(url);
79
+ if (res.ok) {
80
+ const data = await res.json();
81
+ if (!lastFetchRef.current) {
82
+ setMessages(data.messages || []);
83
+ } else if (data.messages?.length > 0) {
84
+ setMessages((prev) => {
85
+ const ids = new Set(prev.map((m) => m.id));
86
+ const newMsgs = data.messages.filter((m) => !ids.has(m.id));
87
+ return newMsgs.length > 0 ? [...prev, ...newMsgs] : prev;
88
+ });
89
+ }
90
+ if (data.messages?.length > 0) {
91
+ lastFetchRef.current = data.messages[data.messages.length - 1].createdAt;
92
+ }
93
+ }
94
+ } catch {
95
+ }
96
+ };
97
+ lastFetchRef.current = null;
98
+ fetchMessages();
99
+ if (typeof EventSource !== "undefined") {
100
+ const es = new EventSource(`/api/support/admin-chat-stream?session=${selectedSession}`);
101
+ messagesESRef.current = es;
102
+ es.onmessage = (event) => {
103
+ try {
104
+ const parsed = JSON.parse(event.data);
105
+ if (parsed.type === "messages" && parsed.data?.length > 0) {
106
+ setMessages((prev) => {
107
+ const ids = new Set(prev.map((m) => m.id));
108
+ const newMsgs = parsed.data.filter((m) => !ids.has(m.id));
109
+ return newMsgs.length > 0 ? [...prev, ...newMsgs] : prev;
110
+ });
111
+ }
112
+ } catch {
113
+ }
114
+ };
115
+ es.onerror = () => {
116
+ es.close();
117
+ messagesESRef.current = null;
118
+ const iv2 = setInterval(fetchMessages, 3e3);
119
+ fetchMessages._fallbackIv = iv2;
120
+ };
121
+ return () => {
122
+ es.close();
123
+ messagesESRef.current = null;
124
+ if (fetchMessages._fallbackIv) clearInterval(fetchMessages._fallbackIv);
125
+ };
126
+ }
127
+ const iv = setInterval(fetchMessages, 3e3);
128
+ return () => clearInterval(iv);
129
+ }, [selectedSession]);
130
+ useEffect(() => {
131
+ messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
132
+ }, [messages]);
133
+ const sendMessage = async (e) => {
134
+ e.preventDefault();
135
+ if (!input.trim() || !selectedSession || sending) return;
136
+ setSending(true);
137
+ try {
138
+ const res = await fetch("/api/support/admin-chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "send", session: selectedSession, message: input.trim() }) });
139
+ if (res.ok) {
140
+ const data = await res.json();
141
+ setMessages((prev) => [...prev, data.message]);
142
+ lastFetchRef.current = data.message.createdAt;
143
+ setInput("");
144
+ }
145
+ } catch {
146
+ }
147
+ setSending(false);
148
+ };
149
+ const closeSession = async () => {
150
+ if (!selectedSession) return;
151
+ try {
152
+ await fetch("/api/support/admin-chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "close", session: selectedSession }) });
153
+ setSelectedSession(null);
154
+ fetchSessions();
155
+ } catch {
156
+ }
157
+ };
158
+ const getClientName = (client) => {
159
+ if (typeof client === "number") return `Client #${client}`;
160
+ const parts = [client.firstName, client.lastName].filter(Boolean);
161
+ if (parts.length > 0) return parts.join(" ");
162
+ return client.email || `Client #${client.id}`;
163
+ };
164
+ const displayedSessions = showClosed ? sessions.closed : sessions.active;
165
+ const S = {
166
+ page: { padding: "20px 30px", maxWidth: 1200, margin: "0 auto" },
167
+ container: { display: "grid", gridTemplateColumns: "320px 1fr", gap: 16, minHeight: "calc(100vh - 300px)" },
168
+ sidebar: { borderRight: "1px solid var(--theme-elevation-200)" },
169
+ sessionItem: { display: "block", width: "100%", padding: "10px 14px", border: "none", background: "none", cursor: "pointer", textAlign: "left", borderBottom: "1px solid var(--theme-elevation-100)", fontSize: 13 },
170
+ sessionActive: { background: "var(--theme-elevation-50)" },
171
+ chatPanel: { display: "flex", flexDirection: "column" },
172
+ messagesArea: { flex: 1, overflowY: "auto", padding: "12px 0" },
173
+ bubble: { maxWidth: "70%", padding: "8px 12px", borderRadius: 10, marginBottom: 8, fontSize: 14 },
174
+ bubbleAgent: { background: "#dbeafe", color: "#1e3a5f", marginLeft: "auto" },
175
+ bubbleClient: { background: "var(--theme-elevation-100)", color: "var(--theme-text)" },
176
+ bubbleSystem: { margin: "4px auto", padding: "4px 12px", fontSize: 11, color: "#6b7280", textAlign: "center" },
177
+ composer: { borderTop: "1px solid var(--theme-elevation-200)", padding: "8px 0" },
178
+ composerInput: { flex: 1, padding: "8px 12px", borderRadius: 8, border: "1px solid var(--theme-elevation-200)", fontSize: 13, background: "var(--theme-elevation-0)", color: "var(--theme-text)" },
179
+ sendBtn: { padding: "8px 16px", borderRadius: 8, background: "#2563eb", color: "#fff", border: "none", fontWeight: 600, cursor: "pointer", fontSize: 13 },
180
+ tabsRow: { display: "flex", gap: 4, padding: "8px 14px", borderBottom: "1px solid var(--theme-elevation-200)" },
181
+ tab: { padding: "4px 10px", borderRadius: 6, border: "none", background: "none", cursor: "pointer", fontSize: 12, color: "var(--theme-elevation-500)" },
182
+ tabActive: { background: "var(--theme-elevation-100)", fontWeight: 700, color: "var(--theme-text)" }
183
+ };
184
+ return /* @__PURE__ */ jsxs("div", { style: S.page, children: [
185
+ /* @__PURE__ */ jsxs("div", { style: { marginBottom: 16 }, children: [
186
+ /* @__PURE__ */ jsx("h1", { style: { fontSize: 22, fontWeight: 700, margin: 0, color: "var(--theme-text)" }, children: t("chat.title") }),
187
+ /* @__PURE__ */ jsx("p", { style: { color: "var(--theme-elevation-500)", fontSize: 13, margin: "4px 0 0" }, children: sessions.active.length !== 1 ? t("chat.sessionCountPlural", { count: String(sessions.active.length) }) : t("chat.sessionCount", { count: String(sessions.active.length) }) })
188
+ ] }),
189
+ /* @__PURE__ */ jsxs("div", { style: S.container, children: [
190
+ /* @__PURE__ */ jsxs("div", { style: S.sidebar, children: [
191
+ /* @__PURE__ */ jsxs("div", { style: S.tabsRow, children: [
192
+ /* @__PURE__ */ jsxs("button", { onClick: () => setShowClosed(false), style: { ...S.tab, ...!showClosed ? S.tabActive : {} }, children: [
193
+ t("chat.tabs.active"),
194
+ " (",
195
+ sessions.active.length,
196
+ ")"
197
+ ] }),
198
+ /* @__PURE__ */ jsxs("button", { onClick: () => setShowClosed(true), style: { ...S.tab, ...showClosed ? S.tabActive : {} }, children: [
199
+ t("chat.tabs.closed"),
200
+ " (",
201
+ sessions.closed.length,
202
+ ")"
203
+ ] })
204
+ ] }),
205
+ /* @__PURE__ */ jsx("div", { children: loading ? /* @__PURE__ */ jsx("div", { style: { padding: 20, textAlign: "center", color: "#94a3b8" }, children: t("common.loading") }) : displayedSessions.length === 0 ? /* @__PURE__ */ jsx("div", { style: { padding: 20, textAlign: "center", color: "#94a3b8" }, children: showClosed ? t("chat.noSessionClosed") : t("chat.noSessionActive") }) : displayedSessions.map((s2) => /* @__PURE__ */ jsxs("button", { onClick: () => setSelectedSession(s2.session), style: { ...S.sessionItem, ...selectedSession === s2.session ? S.sessionActive : {} }, children: [
206
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "space-between" }, children: [
207
+ /* @__PURE__ */ jsx("span", { style: { fontWeight: 600 }, children: getClientName(s2.client) }),
208
+ s2.unreadCount > 0 && /* @__PURE__ */ jsx("span", { style: { padding: "1px 6px", borderRadius: 10, background: "#dc2626", color: "#fff", fontSize: 10, fontWeight: 700 }, children: s2.unreadCount })
209
+ ] }),
210
+ /* @__PURE__ */ jsx("div", { style: { fontSize: 12, color: "var(--theme-elevation-500)", marginTop: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, children: s2.lastMessage }),
211
+ /* @__PURE__ */ jsxs("div", { style: { fontSize: 11, color: "var(--theme-elevation-400)", marginTop: 2 }, children: [
212
+ new Date(s2.lastMessageAt).toLocaleString("fr-FR", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" }),
213
+ " -- ",
214
+ s2.messageCount,
215
+ " ",
216
+ t("chat.msg")
217
+ ] })
218
+ ] }, s2.session)) })
219
+ ] }),
220
+ /* @__PURE__ */ jsx("div", { style: S.chatPanel, children: !selectedSession ? /* @__PURE__ */ jsx("div", { style: { flex: 1, display: "flex", alignItems: "center", justifyContent: "center", color: "#94a3b8", fontSize: 14 }, children: t("chat.selectSession") }) : /* @__PURE__ */ jsxs(Fragment, { children: [
221
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center", padding: "8px 14px", borderBottom: "1px solid var(--theme-elevation-200)" }, children: [
222
+ /* @__PURE__ */ jsx("span", { style: { fontFamily: "monospace", fontSize: 12, color: "var(--theme-elevation-500)" }, children: selectedSession }),
223
+ /* @__PURE__ */ jsx("button", { onClick: closeSession, style: { padding: "4px 12px", borderRadius: 6, border: "1px solid #dc2626", background: "none", color: "#dc2626", fontSize: 12, cursor: "pointer" }, children: t("chat.closeChat") })
224
+ ] }),
225
+ /* @__PURE__ */ jsxs("div", { style: S.messagesArea, children: [
226
+ messages.map((msg) => /* @__PURE__ */ jsx("div", { style: { display: "flex", flexDirection: msg.senderType === "agent" ? "row-reverse" : "row", padding: "2px 14px" }, children: msg.senderType === "system" ? /* @__PURE__ */ jsx("div", { style: S.bubbleSystem, children: msg.message }) : /* @__PURE__ */ jsxs("div", { style: { ...S.bubble, ...msg.senderType === "agent" ? S.bubbleAgent : S.bubbleClient }, children: [
227
+ /* @__PURE__ */ jsx("div", { style: { fontSize: 11, fontWeight: 600, marginBottom: 2 }, children: msg.senderType === "agent" ? t("chat.you") : t("chat.clientLabel") }),
228
+ /* @__PURE__ */ jsx("div", { children: msg.message }),
229
+ /* @__PURE__ */ jsx("div", { style: { fontSize: 10, color: msg.senderType === "agent" ? "#1e40af" : "var(--theme-elevation-400)", marginTop: 2 }, children: new Date(msg.createdAt).toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit" }) })
230
+ ] }) }, msg.id)),
231
+ /* @__PURE__ */ jsx("div", { ref: messagesEndRef })
232
+ ] }),
233
+ /* @__PURE__ */ jsxs("form", { onSubmit: sendMessage, style: S.composer, children: [
234
+ cannedResponses.length > 0 && /* @__PURE__ */ jsxs("select", { onChange: (e) => {
235
+ const cr = cannedResponses.find((c) => String(c.id) === e.target.value);
236
+ if (cr) setInput(cr.body);
237
+ e.target.value = "";
238
+ }, style: { padding: "4px 8px", borderRadius: 6, border: "1px solid var(--theme-elevation-200)", fontSize: 11, marginBottom: 6, color: "var(--theme-text)", background: "var(--theme-elevation-0)" }, children: [
239
+ /* @__PURE__ */ jsx("option", { value: "", children: t("chat.quickReply") }),
240
+ cannedResponses.map((cr) => /* @__PURE__ */ jsx("option", { value: String(cr.id), children: cr.title }, cr.id))
241
+ ] }),
242
+ /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: 8 }, children: [
243
+ /* @__PURE__ */ jsx("input", { type: "text", value: input, onChange: (e) => setInput(e.target.value), placeholder: t("chat.inputPlaceholder"), maxLength: 2e3, style: S.composerInput, autoFocus: true }),
244
+ /* @__PURE__ */ jsx("button", { type: "submit", disabled: !input.trim() || sending, style: S.sendBtn, children: t("chat.sendButton") })
245
+ ] })
246
+ ] })
247
+ ] }) })
248
+ ] })
249
+ ] });
250
+ };
251
+
252
+ export { ChatViewClient };
@@ -0,0 +1,29 @@
1
+ import { jsx } from 'react/jsx-runtime';
2
+ import { DefaultTemplate } from '@payloadcms/next/templates';
3
+ import { redirect } from 'next/navigation';
4
+ import { AdminErrorBoundary } from '../shared/ErrorBoundary';
5
+ import { ChatViewClient } from './client';
6
+
7
+ const ChatView = ({ initPageResult }) => {
8
+ const { req, visibleEntities } = initPageResult;
9
+ if (!req.user) {
10
+ redirect("/admin/login");
11
+ }
12
+ return /* @__PURE__ */ jsx(
13
+ DefaultTemplate,
14
+ {
15
+ i18n: req.i18n,
16
+ locale: initPageResult.locale,
17
+ params: {},
18
+ payload: req.payload,
19
+ permissions: initPageResult.permissions,
20
+ searchParams: {},
21
+ user: req.user,
22
+ visibleEntities,
23
+ children: /* @__PURE__ */ jsx(AdminErrorBoundary, { viewName: "ChatView", children: /* @__PURE__ */ jsx(ChatViewClient, {}) })
24
+ }
25
+ );
26
+ };
27
+ var ChatView_default = ChatView;
28
+
29
+ export { ChatView, ChatView_default as default };