@escalated-dev/escalated 0.7.1 → 0.9.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 (117) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +380 -357
  3. package/package.json +85 -81
  4. package/src/components/ActiveChatsPanel.vue +246 -246
  5. package/src/components/AdminDashboard.stories.js +1423 -1423
  6. package/src/components/AttachmentList.vue +65 -65
  7. package/src/components/ChatActionBar.vue +226 -226
  8. package/src/components/ChatBubble.vue +162 -162
  9. package/src/components/ChatComposer.vue +308 -308
  10. package/src/components/ChatQueue.vue +222 -222
  11. package/src/components/ChatThread.vue +197 -197
  12. package/src/components/CustomTicketActions.stories.js +71 -0
  13. package/src/components/CustomTicketActions.vue +101 -0
  14. package/src/components/EscalatedLayout.vue +619 -598
  15. package/src/components/FollowButton.vue +20 -1
  16. package/src/components/MentionDropdown.vue +154 -154
  17. package/src/components/MetricComparison.vue +89 -89
  18. package/src/components/PercentileChart.vue +67 -67
  19. package/src/components/PeriodSelector.vue +98 -98
  20. package/src/components/PresenceIndicator.vue +228 -213
  21. package/src/components/ReplyComposer.vue +336 -336
  22. package/src/components/ReplyThread.vue +153 -153
  23. package/src/components/ReportChart.vue +395 -395
  24. package/src/components/ReportExportButton.vue +108 -108
  25. package/src/components/SaveViewDialog.vue +172 -172
  26. package/src/components/SavedViewSidebar.vue +208 -208
  27. package/src/components/SkillTagManager.vue +29 -22
  28. package/src/components/SnoozeButton.vue +247 -247
  29. package/src/components/TicketFilters.vue +270 -270
  30. package/src/components/TicketList.vue +655 -655
  31. package/src/components/TicketSidebar.vue +4 -0
  32. package/src/components/TicketSplitDialog.vue +98 -98
  33. package/src/components/TicketSubjects.stories.js +63 -0
  34. package/src/components/TicketSubjects.vue +107 -0
  35. package/src/components/TwoFactorSetup.vue +1 -37
  36. package/src/components/VariableTokenInput.vue +111 -111
  37. package/src/components/WorkflowActionConfig.vue +287 -287
  38. package/src/components/WorkflowActionList.vue +350 -350
  39. package/src/components/WorkflowConditionBuilder.vue +265 -265
  40. package/src/components/WorkflowTriggerSelector.vue +125 -125
  41. package/src/components/admin/newsletters/AnalyticsTiles.stories.js +14 -0
  42. package/src/components/admin/newsletters/AnalyticsTiles.vue +55 -0
  43. package/src/components/admin/newsletters/DeliveriesTable.stories.js +28 -0
  44. package/src/components/admin/newsletters/DeliveriesTable.vue +104 -0
  45. package/src/components/admin/newsletters/DynamicFilterBuilder.stories.js +11 -0
  46. package/src/components/admin/newsletters/DynamicFilterBuilder.vue +53 -0
  47. package/src/components/admin/newsletters/ListMemberTable.stories.js +12 -0
  48. package/src/components/admin/newsletters/ListMemberTable.vue +53 -0
  49. package/src/components/admin/newsletters/MarkdownEditor.stories.js +6 -0
  50. package/src/components/admin/newsletters/MarkdownEditor.vue +53 -0
  51. package/src/components/admin/newsletters/MergeFieldDropdown.stories.js +6 -0
  52. package/src/components/admin/newsletters/MergeFieldDropdown.vue +84 -0
  53. package/src/components/admin/newsletters/PreviewIframe.stories.js +7 -0
  54. package/src/components/admin/newsletters/PreviewIframe.vue +40 -0
  55. package/src/components/admin/newsletters/SummaryTiles.stories.js +8 -0
  56. package/src/components/admin/newsletters/SummaryTiles.vue +63 -0
  57. package/src/composables/useChat.js +187 -187
  58. package/src/composables/useI18n.js +30 -8
  59. package/src/composables/useMentions.js +134 -134
  60. package/src/composables/usePermissions.js +31 -0
  61. package/src/composables/useRealtime.js +182 -182
  62. package/src/index.js +85 -84
  63. package/src/locales/README.md +13 -0
  64. package/src/locales/ar.json +727 -727
  65. package/src/locales/de.json +690 -690
  66. package/src/locales/en.json +889 -729
  67. package/src/locales/es.json +691 -691
  68. package/src/locales/fr.json +691 -691
  69. package/src/locales/index.js +16 -16
  70. package/src/locales/it.json +727 -727
  71. package/src/locales/ja.json +727 -727
  72. package/src/locales/ko.json +727 -727
  73. package/src/locales/nl.json +727 -727
  74. package/src/locales/pl.json +727 -727
  75. package/src/locales/pt-BR.json +727 -727
  76. package/src/locales/ru.json +727 -727
  77. package/src/locales/tr.json +727 -727
  78. package/src/locales/zh-CN.json +727 -727
  79. package/src/pages/Admin/Newsletters/Compose.vue +192 -0
  80. package/src/pages/Admin/Newsletters/Edit.vue +24 -0
  81. package/src/pages/Admin/Newsletters/Index.vue +141 -0
  82. package/src/pages/Admin/Newsletters/Lists/Create.vue +64 -0
  83. package/src/pages/Admin/Newsletters/Lists/Index.vue +59 -0
  84. package/src/pages/Admin/Newsletters/Lists/Show.vue +53 -0
  85. package/src/pages/Admin/Newsletters/Settings.vue +85 -0
  86. package/src/pages/Admin/Newsletters/Show.vue +140 -0
  87. package/src/pages/Admin/Newsletters/Templates/Create.vue +11 -0
  88. package/src/pages/Admin/Newsletters/Templates/Index.vue +54 -0
  89. package/src/pages/Admin/Newsletters/Templates/Show.vue +65 -0
  90. package/src/pages/Admin/Newsletters/usePreview.js +44 -0
  91. package/src/pages/Admin/Reports/AgentDetail.vue +132 -132
  92. package/src/pages/Admin/Reports/AgentRanking.vue +246 -246
  93. package/src/pages/Admin/Reports/Cohorts.vue +180 -180
  94. package/src/pages/Admin/Reports/Comparison.vue +141 -141
  95. package/src/pages/Admin/Reports/Dashboard.vue +226 -226
  96. package/src/pages/Admin/Reports/ResolutionTimes.vue +164 -164
  97. package/src/pages/Admin/Reports/ResponseTimes.vue +164 -164
  98. package/src/pages/Admin/Reports/SlaTrends.vue +183 -183
  99. package/src/pages/Admin/Settings/SsoSettings.vue +157 -4
  100. package/src/pages/Admin/Settings/TwoFactor.vue +32 -6
  101. package/src/pages/Admin/Settings.vue +1008 -1008
  102. package/src/pages/Admin/Skills/Form.vue +164 -4
  103. package/src/pages/Admin/Skills/Index.vue +14 -3
  104. package/src/pages/Admin/Tickets/Index.vue +126 -126
  105. package/src/pages/Admin/Tickets/Show.vue +254 -249
  106. package/src/pages/Admin/Users/Index.vue +145 -0
  107. package/src/pages/Admin/Workflows/Builder.vue +207 -207
  108. package/src/pages/Admin/Workflows/Index.vue +235 -235
  109. package/src/pages/Admin/Workflows/Logs.vue +286 -286
  110. package/src/pages/Agent/TicketIndex.vue +112 -112
  111. package/src/pages/Agent/TicketShow.vue +547 -494
  112. package/src/pages/Customer/Index.vue +26 -1
  113. package/src/pages/Customer/KnowledgeBase/Article.vue +129 -129
  114. package/src/plugin.js +175 -175
  115. package/src/utils/mentionHighlight.js +24 -24
  116. package/src/widget/EscalatedWidget.vue +804 -804
  117. package/src/widget/index.js +254 -254
@@ -1,134 +1,134 @@
1
- import { ref, onUnmounted } from 'vue';
2
-
3
- /**
4
- * Composable that detects `@` typed in a text input/textarea,
5
- * fetches agent suggestions from the API (debounced), and provides
6
- * an insert function to replace the mention token.
7
- *
8
- * @param {Object} options
9
- * @param {string} [options.searchEndpoint] - API endpoint for agent search (default: route-based)
10
- * @param {number} [options.debounce=250] - Debounce delay in ms
11
- * @returns {Object}
12
- */
13
- export function useMentions(options = {}) {
14
- const { debounce = 250 } = options;
15
-
16
- const suggestions = ref([]);
17
- const isActive = ref(false);
18
- const query = ref('');
19
- const mentionStart = ref(null); // cursor position where `@` was typed
20
- const loading = ref(false);
21
-
22
- let timer = null;
23
-
24
- function clearTimer() {
25
- if (timer !== null) {
26
- window.clearTimeout(timer);
27
- timer = null;
28
- }
29
- }
30
-
31
- /**
32
- * Call this on every input/keyup event with the textarea element
33
- * and the current text value.
34
- */
35
- function onTextChange(textareaEl, text) {
36
- if (!textareaEl) return;
37
-
38
- const cursorPos = textareaEl.selectionStart;
39
- const textBeforeCursor = text.slice(0, cursorPos);
40
-
41
- // Find the last `@` that starts a mention (preceded by whitespace or start of string)
42
- const mentionMatch = textBeforeCursor.match(/(?:^|[\s(])@([a-zA-Z0-9_ ]*)$/);
43
-
44
- if (mentionMatch) {
45
- const searchQuery = mentionMatch[1];
46
- // The @ is at cursorPos minus the matched group minus 1 for the @
47
- mentionStart.value = cursorPos - searchQuery.length - 1;
48
- query.value = searchQuery;
49
- isActive.value = true;
50
- debouncedFetch(searchQuery);
51
- } else {
52
- close();
53
- }
54
- }
55
-
56
- function debouncedFetch(searchQuery) {
57
- clearTimer();
58
-
59
- if (searchQuery.length < 1) {
60
- fetchSuggestions('');
61
- return;
62
- }
63
-
64
- timer = window.setTimeout(() => {
65
- fetchSuggestions(searchQuery);
66
- }, debounce);
67
- }
68
-
69
- async function fetchSuggestions(searchQuery) {
70
- loading.value = true;
71
- try {
72
- const endpoint = options.searchEndpoint || '/support/admin/agents/search';
73
- const url = `${endpoint}?q=${encodeURIComponent(searchQuery)}`;
74
- const response = await fetch(url, {
75
- headers: {
76
- Accept: 'application/json',
77
- 'X-Requested-With': 'XMLHttpRequest',
78
- 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '',
79
- },
80
- });
81
- if (response.ok) {
82
- suggestions.value = await response.json();
83
- } else {
84
- suggestions.value = [];
85
- }
86
- } catch {
87
- suggestions.value = [];
88
- } finally {
89
- loading.value = false;
90
- }
91
- }
92
-
93
- /**
94
- * Insert the selected agent mention into the text.
95
- * Returns the new text value with the mention inserted.
96
- *
97
- * @param {string} currentText - Current textarea value
98
- * @param {Object} agent - Agent object with `name` property
99
- * @returns {string} Updated text
100
- */
101
- function insertMention(currentText, agent) {
102
- if (mentionStart.value === null) return currentText;
103
-
104
- const before = currentText.slice(0, mentionStart.value);
105
- const cursorPos = mentionStart.value + 1 + query.value.length;
106
- const after = currentText.slice(cursorPos);
107
-
108
- const mentionText = `@{${agent.name}} `;
109
- const newText = before + mentionText + after;
110
-
111
- close();
112
- return newText;
113
- }
114
-
115
- function close() {
116
- isActive.value = false;
117
- suggestions.value = [];
118
- query.value = '';
119
- mentionStart.value = null;
120
- clearTimer();
121
- }
122
-
123
- onUnmounted(clearTimer);
124
-
125
- return {
126
- suggestions,
127
- isActive,
128
- query,
129
- loading,
130
- onTextChange,
131
- insertMention,
132
- close,
133
- };
134
- }
1
+ import { ref, onUnmounted } from 'vue';
2
+
3
+ /**
4
+ * Composable that detects `@` typed in a text input/textarea,
5
+ * fetches agent suggestions from the API (debounced), and provides
6
+ * an insert function to replace the mention token.
7
+ *
8
+ * @param {Object} options
9
+ * @param {string} [options.searchEndpoint] - API endpoint for agent search (default: route-based)
10
+ * @param {number} [options.debounce=250] - Debounce delay in ms
11
+ * @returns {Object}
12
+ */
13
+ export function useMentions(options = {}) {
14
+ const { debounce = 250 } = options;
15
+
16
+ const suggestions = ref([]);
17
+ const isActive = ref(false);
18
+ const query = ref('');
19
+ const mentionStart = ref(null); // cursor position where `@` was typed
20
+ const loading = ref(false);
21
+
22
+ let timer = null;
23
+
24
+ function clearTimer() {
25
+ if (timer !== null) {
26
+ window.clearTimeout(timer);
27
+ timer = null;
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Call this on every input/keyup event with the textarea element
33
+ * and the current text value.
34
+ */
35
+ function onTextChange(textareaEl, text) {
36
+ if (!textareaEl) return;
37
+
38
+ const cursorPos = textareaEl.selectionStart;
39
+ const textBeforeCursor = text.slice(0, cursorPos);
40
+
41
+ // Find the last `@` that starts a mention (preceded by whitespace or start of string)
42
+ const mentionMatch = textBeforeCursor.match(/(?:^|[\s(])@([a-zA-Z0-9_ ]*)$/);
43
+
44
+ if (mentionMatch) {
45
+ const searchQuery = mentionMatch[1];
46
+ // The @ is at cursorPos minus the matched group minus 1 for the @
47
+ mentionStart.value = cursorPos - searchQuery.length - 1;
48
+ query.value = searchQuery;
49
+ isActive.value = true;
50
+ debouncedFetch(searchQuery);
51
+ } else {
52
+ close();
53
+ }
54
+ }
55
+
56
+ function debouncedFetch(searchQuery) {
57
+ clearTimer();
58
+
59
+ if (searchQuery.length < 1) {
60
+ fetchSuggestions('');
61
+ return;
62
+ }
63
+
64
+ timer = window.setTimeout(() => {
65
+ fetchSuggestions(searchQuery);
66
+ }, debounce);
67
+ }
68
+
69
+ async function fetchSuggestions(searchQuery) {
70
+ loading.value = true;
71
+ try {
72
+ const endpoint = options.searchEndpoint || '/support/admin/agents/search';
73
+ const url = `${endpoint}?q=${encodeURIComponent(searchQuery)}`;
74
+ const response = await fetch(url, {
75
+ headers: {
76
+ Accept: 'application/json',
77
+ 'X-Requested-With': 'XMLHttpRequest',
78
+ 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '',
79
+ },
80
+ });
81
+ if (response.ok) {
82
+ suggestions.value = await response.json();
83
+ } else {
84
+ suggestions.value = [];
85
+ }
86
+ } catch {
87
+ suggestions.value = [];
88
+ } finally {
89
+ loading.value = false;
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Insert the selected agent mention into the text.
95
+ * Returns the new text value with the mention inserted.
96
+ *
97
+ * @param {string} currentText - Current textarea value
98
+ * @param {Object} agent - Agent object with `name` property
99
+ * @returns {string} Updated text
100
+ */
101
+ function insertMention(currentText, agent) {
102
+ if (mentionStart.value === null) return currentText;
103
+
104
+ const before = currentText.slice(0, mentionStart.value);
105
+ const cursorPos = mentionStart.value + 1 + query.value.length;
106
+ const after = currentText.slice(cursorPos);
107
+
108
+ const mentionText = `@{${agent.name}} `;
109
+ const newText = before + mentionText + after;
110
+
111
+ close();
112
+ return newText;
113
+ }
114
+
115
+ function close() {
116
+ isActive.value = false;
117
+ suggestions.value = [];
118
+ query.value = '';
119
+ mentionStart.value = null;
120
+ clearTimer();
121
+ }
122
+
123
+ onUnmounted(clearTimer);
124
+
125
+ return {
126
+ suggestions,
127
+ isActive,
128
+ query,
129
+ loading,
130
+ onTextChange,
131
+ insertMention,
132
+ close,
133
+ };
134
+ }
@@ -0,0 +1,31 @@
1
+ import { computed } from 'vue';
2
+ import { usePage } from '@inertiajs/vue3';
3
+
4
+ /**
5
+ * Read the current user's permission slugs from Inertia shared props.
6
+ * Canonical source: `page.props.escalated.permissions` (string[]).
7
+ */
8
+ export function usePermissions() {
9
+ const page = usePage();
10
+
11
+ const permissions = computed(() => {
12
+ const raw = page.props.escalated?.permissions;
13
+ if (raw === undefined || raw === null) {
14
+ return null;
15
+ }
16
+ return Array.isArray(raw) ? raw : [];
17
+ });
18
+
19
+ function hasPermission(slug) {
20
+ const perms = permissions.value;
21
+ if (perms === null) {
22
+ return page.props.escalated?.is_admin === true;
23
+ }
24
+ if (perms.includes('*')) {
25
+ return true;
26
+ }
27
+ return perms.includes(slug);
28
+ }
29
+
30
+ return { permissions, hasPermission };
31
+ }
@@ -1,182 +1,182 @@
1
- import { ref, onUnmounted, readonly } from 'vue';
2
-
3
- /**
4
- * Composable for real-time WebSocket event listening via Laravel Echo.
5
- *
6
- * If `window.Echo` is available (provided by the host app), this composable
7
- * subscribes to private channels and listens for broadcast events. When Echo
8
- * is not present, it silently falls back - the caller can check `echoAvailable`
9
- * and implement polling as needed.
10
- *
11
- * Usage:
12
- * const { echoAvailable, subscribeToTicket, subscribeToTickets, subscribeToAgent } = useRealtime();
13
- *
14
- * All subscriptions are automatically cleaned up on component unmount.
15
- */
16
- export function useRealtime() {
17
- const echoAvailable = ref(typeof window !== 'undefined' && !!window.Echo);
18
- const subscriptions = [];
19
-
20
- /**
21
- * Subscribe to a private channel and listen for an event.
22
- * Returns an unsubscribe function.
23
- */
24
- function listen(channelName, eventName, callback) {
25
- if (!echoAvailable.value) return () => {};
26
-
27
- const channel = window.Echo.private(channelName);
28
- channel.listen(eventName, callback);
29
-
30
- const unsub = () => {
31
- channel.stopListening(eventName, callback);
32
- window.Echo.leave(channelName);
33
- };
34
- subscriptions.push(unsub);
35
- return unsub;
36
- }
37
-
38
- /**
39
- * Subscribe to a specific ticket's channel for real-time updates.
40
- *
41
- * @param {number|string} ticketId - The ticket ID
42
- * @param {Object} handlers - Event handler callbacks
43
- * @param {Function} [handlers.onReplyCreated] - Called when a new reply is added
44
- * @param {Function} [handlers.onTicketUpdated] - Called when ticket fields are updated
45
- * @param {Function} [handlers.onStatusChanged] - Called when ticket status changes
46
- * @param {Function} [handlers.onTicketAssigned] - Called when ticket is assigned
47
- * @param {Function} [handlers.onTicketEscalated] - Called when ticket is escalated
48
- * @returns {Function} Unsubscribe function
49
- */
50
- function subscribeToTicket(ticketId, handlers = {}) {
51
- if (!echoAvailable.value) return () => {};
52
-
53
- const channelName = `escalated.tickets.${ticketId}`;
54
- const channel = window.Echo.private(channelName);
55
- const listeners = [];
56
-
57
- if (handlers.onReplyCreated) {
58
- channel.listen('.reply.created', handlers.onReplyCreated);
59
- listeners.push(['.reply.created', handlers.onReplyCreated]);
60
- }
61
- if (handlers.onTicketUpdated) {
62
- channel.listen('.ticket.updated', handlers.onTicketUpdated);
63
- listeners.push(['.ticket.updated', handlers.onTicketUpdated]);
64
- }
65
- if (handlers.onStatusChanged) {
66
- channel.listen('.ticket.status_changed', handlers.onStatusChanged);
67
- listeners.push(['.ticket.status_changed', handlers.onStatusChanged]);
68
- }
69
- if (handlers.onTicketAssigned) {
70
- channel.listen('.ticket.assigned', handlers.onTicketAssigned);
71
- listeners.push(['.ticket.assigned', handlers.onTicketAssigned]);
72
- }
73
- if (handlers.onTicketEscalated) {
74
- channel.listen('.ticket.escalated', handlers.onTicketEscalated);
75
- listeners.push(['.ticket.escalated', handlers.onTicketEscalated]);
76
- }
77
-
78
- const unsub = () => {
79
- listeners.forEach(([event, cb]) => channel.stopListening(event, cb));
80
- window.Echo.leave(channelName);
81
- };
82
- subscriptions.push(unsub);
83
- return unsub;
84
- }
85
-
86
- /**
87
- * Subscribe to the global tickets channel for new ticket notifications.
88
- *
89
- * @param {Object} handlers - Event handler callbacks
90
- * @param {Function} [handlers.onTicketCreated] - Called when a new ticket is created
91
- * @returns {Function} Unsubscribe function
92
- */
93
- function subscribeToTickets(handlers = {}) {
94
- if (!echoAvailable.value) return () => {};
95
-
96
- const channelName = 'escalated.tickets';
97
- const channel = window.Echo.private(channelName);
98
- const listeners = [];
99
-
100
- if (handlers.onTicketCreated) {
101
- channel.listen('.ticket.created', handlers.onTicketCreated);
102
- listeners.push(['.ticket.created', handlers.onTicketCreated]);
103
- }
104
-
105
- const unsub = () => {
106
- listeners.forEach(([event, cb]) => channel.stopListening(event, cb));
107
- window.Echo.leave(channelName);
108
- };
109
- subscriptions.push(unsub);
110
- return unsub;
111
- }
112
-
113
- /**
114
- * Subscribe to an agent's personal channel for assignment notifications.
115
- *
116
- * @param {number|string} agentId - The agent's user ID
117
- * @param {Object} handlers - Event handler callbacks
118
- * @param {Function} [handlers.onTicketAssigned] - Called when a ticket is assigned to this agent
119
- * @returns {Function} Unsubscribe function
120
- */
121
- function subscribeToAgent(agentId, handlers = {}) {
122
- if (!echoAvailable.value) return () => {};
123
-
124
- const channelName = `escalated.agents.${agentId}`;
125
- const channel = window.Echo.private(channelName);
126
- const listeners = [];
127
-
128
- if (handlers.onTicketAssigned) {
129
- channel.listen('.ticket.assigned', handlers.onTicketAssigned);
130
- listeners.push(['.ticket.assigned', handlers.onTicketAssigned]);
131
- }
132
-
133
- const unsub = () => {
134
- listeners.forEach(([event, cb]) => channel.stopListening(event, cb));
135
- window.Echo.leave(channelName);
136
- };
137
- subscriptions.push(unsub);
138
- return unsub;
139
- }
140
-
141
- /**
142
- * Get a presence channel for a ticket (if Echo supports it).
143
- * Returns the channel instance or null.
144
- */
145
- function joinTicketPresence(ticketId, callbacks = {}) {
146
- if (!echoAvailable.value) return null;
147
-
148
- const channelName = `escalated.tickets.${ticketId}`;
149
- const channel = window.Echo.join(channelName);
150
-
151
- if (callbacks.here) channel.here(callbacks.here);
152
- if (callbacks.joining) channel.joining(callbacks.joining);
153
- if (callbacks.leaving) channel.leaving(callbacks.leaving);
154
-
155
- const unsub = () => {
156
- window.Echo.leave(`presence-${channelName}`);
157
- };
158
- subscriptions.push(unsub);
159
- return { channel, unsubscribe: unsub };
160
- }
161
-
162
- // Cleanup all subscriptions on component unmount
163
- onUnmounted(() => {
164
- subscriptions.forEach((unsub) => {
165
- try {
166
- unsub();
167
- } catch {
168
- /* ignore */
169
- }
170
- });
171
- subscriptions.length = 0;
172
- });
173
-
174
- return {
175
- echoAvailable: readonly(echoAvailable),
176
- listen,
177
- subscribeToTicket,
178
- subscribeToTickets,
179
- subscribeToAgent,
180
- joinTicketPresence,
181
- };
182
- }
1
+ import { ref, onUnmounted, readonly } from 'vue';
2
+
3
+ /**
4
+ * Composable for real-time WebSocket event listening via Laravel Echo.
5
+ *
6
+ * If `window.Echo` is available (provided by the host app), this composable
7
+ * subscribes to private channels and listens for broadcast events. When Echo
8
+ * is not present, it silently falls back - the caller can check `echoAvailable`
9
+ * and implement polling as needed.
10
+ *
11
+ * Usage:
12
+ * const { echoAvailable, subscribeToTicket, subscribeToTickets, subscribeToAgent } = useRealtime();
13
+ *
14
+ * All subscriptions are automatically cleaned up on component unmount.
15
+ */
16
+ export function useRealtime() {
17
+ const echoAvailable = ref(typeof window !== 'undefined' && !!window.Echo);
18
+ const subscriptions = [];
19
+
20
+ /**
21
+ * Subscribe to a private channel and listen for an event.
22
+ * Returns an unsubscribe function.
23
+ */
24
+ function listen(channelName, eventName, callback) {
25
+ if (!echoAvailable.value) return () => {};
26
+
27
+ const channel = window.Echo.private(channelName);
28
+ channel.listen(eventName, callback);
29
+
30
+ const unsub = () => {
31
+ channel.stopListening(eventName, callback);
32
+ window.Echo.leave(channelName);
33
+ };
34
+ subscriptions.push(unsub);
35
+ return unsub;
36
+ }
37
+
38
+ /**
39
+ * Subscribe to a specific ticket's channel for real-time updates.
40
+ *
41
+ * @param {number|string} ticketId - The ticket ID
42
+ * @param {Object} handlers - Event handler callbacks
43
+ * @param {Function} [handlers.onReplyCreated] - Called when a new reply is added
44
+ * @param {Function} [handlers.onTicketUpdated] - Called when ticket fields are updated
45
+ * @param {Function} [handlers.onStatusChanged] - Called when ticket status changes
46
+ * @param {Function} [handlers.onTicketAssigned] - Called when ticket is assigned
47
+ * @param {Function} [handlers.onTicketEscalated] - Called when ticket is escalated
48
+ * @returns {Function} Unsubscribe function
49
+ */
50
+ function subscribeToTicket(ticketId, handlers = {}) {
51
+ if (!echoAvailable.value) return () => {};
52
+
53
+ const channelName = `escalated.tickets.${ticketId}`;
54
+ const channel = window.Echo.private(channelName);
55
+ const listeners = [];
56
+
57
+ if (handlers.onReplyCreated) {
58
+ channel.listen('.reply.created', handlers.onReplyCreated);
59
+ listeners.push(['.reply.created', handlers.onReplyCreated]);
60
+ }
61
+ if (handlers.onTicketUpdated) {
62
+ channel.listen('.ticket.updated', handlers.onTicketUpdated);
63
+ listeners.push(['.ticket.updated', handlers.onTicketUpdated]);
64
+ }
65
+ if (handlers.onStatusChanged) {
66
+ channel.listen('.ticket.status_changed', handlers.onStatusChanged);
67
+ listeners.push(['.ticket.status_changed', handlers.onStatusChanged]);
68
+ }
69
+ if (handlers.onTicketAssigned) {
70
+ channel.listen('.ticket.assigned', handlers.onTicketAssigned);
71
+ listeners.push(['.ticket.assigned', handlers.onTicketAssigned]);
72
+ }
73
+ if (handlers.onTicketEscalated) {
74
+ channel.listen('.ticket.escalated', handlers.onTicketEscalated);
75
+ listeners.push(['.ticket.escalated', handlers.onTicketEscalated]);
76
+ }
77
+
78
+ const unsub = () => {
79
+ listeners.forEach(([event, cb]) => channel.stopListening(event, cb));
80
+ window.Echo.leave(channelName);
81
+ };
82
+ subscriptions.push(unsub);
83
+ return unsub;
84
+ }
85
+
86
+ /**
87
+ * Subscribe to the global tickets channel for new ticket notifications.
88
+ *
89
+ * @param {Object} handlers - Event handler callbacks
90
+ * @param {Function} [handlers.onTicketCreated] - Called when a new ticket is created
91
+ * @returns {Function} Unsubscribe function
92
+ */
93
+ function subscribeToTickets(handlers = {}) {
94
+ if (!echoAvailable.value) return () => {};
95
+
96
+ const channelName = 'escalated.tickets';
97
+ const channel = window.Echo.private(channelName);
98
+ const listeners = [];
99
+
100
+ if (handlers.onTicketCreated) {
101
+ channel.listen('.ticket.created', handlers.onTicketCreated);
102
+ listeners.push(['.ticket.created', handlers.onTicketCreated]);
103
+ }
104
+
105
+ const unsub = () => {
106
+ listeners.forEach(([event, cb]) => channel.stopListening(event, cb));
107
+ window.Echo.leave(channelName);
108
+ };
109
+ subscriptions.push(unsub);
110
+ return unsub;
111
+ }
112
+
113
+ /**
114
+ * Subscribe to an agent's personal channel for assignment notifications.
115
+ *
116
+ * @param {number|string} agentId - The agent's user ID
117
+ * @param {Object} handlers - Event handler callbacks
118
+ * @param {Function} [handlers.onTicketAssigned] - Called when a ticket is assigned to this agent
119
+ * @returns {Function} Unsubscribe function
120
+ */
121
+ function subscribeToAgent(agentId, handlers = {}) {
122
+ if (!echoAvailable.value) return () => {};
123
+
124
+ const channelName = `escalated.agents.${agentId}`;
125
+ const channel = window.Echo.private(channelName);
126
+ const listeners = [];
127
+
128
+ if (handlers.onTicketAssigned) {
129
+ channel.listen('.ticket.assigned', handlers.onTicketAssigned);
130
+ listeners.push(['.ticket.assigned', handlers.onTicketAssigned]);
131
+ }
132
+
133
+ const unsub = () => {
134
+ listeners.forEach(([event, cb]) => channel.stopListening(event, cb));
135
+ window.Echo.leave(channelName);
136
+ };
137
+ subscriptions.push(unsub);
138
+ return unsub;
139
+ }
140
+
141
+ /**
142
+ * Get a presence channel for a ticket (if Echo supports it).
143
+ * Returns the channel instance or null.
144
+ */
145
+ function joinTicketPresence(ticketId, callbacks = {}) {
146
+ if (!echoAvailable.value) return null;
147
+
148
+ const channelName = `escalated.tickets.${ticketId}`;
149
+ const channel = window.Echo.join(channelName);
150
+
151
+ if (callbacks.here) channel.here(callbacks.here);
152
+ if (callbacks.joining) channel.joining(callbacks.joining);
153
+ if (callbacks.leaving) channel.leaving(callbacks.leaving);
154
+
155
+ const unsub = () => {
156
+ window.Echo.leave(`presence-${channelName}`);
157
+ };
158
+ subscriptions.push(unsub);
159
+ return { channel, unsubscribe: unsub };
160
+ }
161
+
162
+ // Cleanup all subscriptions on component unmount
163
+ onUnmounted(() => {
164
+ subscriptions.forEach((unsub) => {
165
+ try {
166
+ unsub();
167
+ } catch {
168
+ /* ignore */
169
+ }
170
+ });
171
+ subscriptions.length = 0;
172
+ });
173
+
174
+ return {
175
+ echoAvailable: readonly(echoAvailable),
176
+ listen,
177
+ subscribeToTicket,
178
+ subscribeToTickets,
179
+ subscribeToAgent,
180
+ joinTicketPresence,
181
+ };
182
+ }