@greatapps/greatchat-ui 0.1.1 → 0.1.2

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.
@@ -0,0 +1,163 @@
1
+ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
2
+ import type { Channel, WhatsappStatus } from "../types";
3
+ import {
4
+ type GchatHookConfig,
5
+ DEFAULT_CHANNEL_STATUS_POLLING,
6
+ DEFAULT_QR_POLLING,
7
+ useGchatClient,
8
+ } from "./types";
9
+
10
+ // ---------------------------------------------------------------------------
11
+ // Queries
12
+ // ---------------------------------------------------------------------------
13
+
14
+ export function useChannels(config: GchatHookConfig) {
15
+ const client = useGchatClient(config);
16
+
17
+ return useQuery({
18
+ queryKey: ["greatchat", "channels", config.accountId],
19
+ queryFn: () => client.listChannels(config.accountId),
20
+ enabled: !!config.accountId && !!config.token,
21
+ select: (res) => res.data || [],
22
+ });
23
+ }
24
+
25
+ export function useChannelWhatsappStatus(
26
+ config: GchatHookConfig,
27
+ channelId: number | null,
28
+ enabled = true,
29
+ pollingInterval?: number,
30
+ ) {
31
+ const client = useGchatClient(config);
32
+
33
+ return useQuery({
34
+ queryKey: ["greatchat", "channel-status", config.accountId, channelId],
35
+ queryFn: () =>
36
+ client.getChannelWhatsappStatus(config.accountId, channelId!),
37
+ enabled: !!config.accountId && !!config.token && !!channelId && enabled,
38
+ refetchInterval: pollingInterval ?? DEFAULT_CHANNEL_STATUS_POLLING,
39
+ select: (res) => {
40
+ const d = res.data;
41
+ return (Array.isArray(d) ? d[0] : d) as WhatsappStatus;
42
+ },
43
+ });
44
+ }
45
+
46
+ export function useChannelQR(
47
+ config: GchatHookConfig,
48
+ channelId: number | null,
49
+ enabled = false,
50
+ pollingInterval?: number,
51
+ ) {
52
+ const client = useGchatClient(config);
53
+
54
+ return useQuery({
55
+ queryKey: ["greatchat", "channel-qr", config.accountId, channelId],
56
+ queryFn: () => client.getChannelQR(config.accountId, channelId!),
57
+ enabled: !!config.accountId && !!config.token && !!channelId && enabled,
58
+ refetchInterval: pollingInterval ?? DEFAULT_QR_POLLING,
59
+ });
60
+ }
61
+
62
+ // ---------------------------------------------------------------------------
63
+ // Mutations
64
+ // ---------------------------------------------------------------------------
65
+
66
+ export function useCreateChannel(config: GchatHookConfig) {
67
+ const client = useGchatClient(config);
68
+ const queryClient = useQueryClient();
69
+
70
+ return useMutation({
71
+ mutationFn: (
72
+ body: Pick<Channel, "name" | "type" | "provider"> &
73
+ Partial<Pick<Channel, "identifier" | "id_agent">>,
74
+ ) => client.createChannel(config.accountId, body),
75
+ onSuccess: () => {
76
+ queryClient.invalidateQueries({
77
+ queryKey: ["greatchat", "channels"],
78
+ });
79
+ },
80
+ });
81
+ }
82
+
83
+ export function useUpdateChannel(config: GchatHookConfig) {
84
+ const client = useGchatClient(config);
85
+ const queryClient = useQueryClient();
86
+
87
+ return useMutation({
88
+ mutationFn: ({
89
+ id,
90
+ body,
91
+ }: {
92
+ id: number;
93
+ body: Partial<
94
+ Pick<Channel, "name" | "identifier" | "status" | "id_agent">
95
+ >;
96
+ }) => client.updateChannel(config.accountId, id, body),
97
+ onSuccess: () => {
98
+ queryClient.invalidateQueries({
99
+ queryKey: ["greatchat", "channels"],
100
+ });
101
+ },
102
+ });
103
+ }
104
+
105
+ export function useDeleteChannel(config: GchatHookConfig) {
106
+ const client = useGchatClient(config);
107
+ const queryClient = useQueryClient();
108
+
109
+ return useMutation({
110
+ mutationFn: (channelId: number) =>
111
+ client.deleteChannel(config.accountId, channelId),
112
+ onSuccess: () => {
113
+ queryClient.invalidateQueries({
114
+ queryKey: ["greatchat", "channels"],
115
+ });
116
+ },
117
+ });
118
+ }
119
+
120
+ export function useConnectChannel(config: GchatHookConfig) {
121
+ const client = useGchatClient(config);
122
+
123
+ return useMutation({
124
+ mutationFn: (channelId: number) =>
125
+ client.connectChannel(config.accountId, channelId),
126
+ });
127
+ }
128
+
129
+ export function useDisconnectChannel(config: GchatHookConfig) {
130
+ const client = useGchatClient(config);
131
+ const queryClient = useQueryClient();
132
+
133
+ return useMutation({
134
+ mutationFn: (channelId: number) =>
135
+ client.disconnectChannel(config.accountId, channelId),
136
+ onSuccess: () => {
137
+ queryClient.invalidateQueries({
138
+ queryKey: ["greatchat", "channel-status"],
139
+ });
140
+ queryClient.invalidateQueries({
141
+ queryKey: ["greatchat", "channels"],
142
+ });
143
+ },
144
+ });
145
+ }
146
+
147
+ export function useLogoutChannel(config: GchatHookConfig) {
148
+ const client = useGchatClient(config);
149
+ const queryClient = useQueryClient();
150
+
151
+ return useMutation({
152
+ mutationFn: (channelId: number) =>
153
+ client.logoutChannel(config.accountId, channelId),
154
+ onSuccess: () => {
155
+ queryClient.invalidateQueries({
156
+ queryKey: ["greatchat", "channel-status"],
157
+ });
158
+ queryClient.invalidateQueries({
159
+ queryKey: ["greatchat", "channels"],
160
+ });
161
+ },
162
+ });
163
+ }
@@ -0,0 +1,94 @@
1
+ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
2
+ import type { Contact } from "../types";
3
+ import { type GchatHookConfig, useGchatClient } from "./types";
4
+
5
+ // ---------------------------------------------------------------------------
6
+ // Queries
7
+ // ---------------------------------------------------------------------------
8
+
9
+ export function useContacts(
10
+ config: GchatHookConfig,
11
+ params?: Record<string, string>,
12
+ ) {
13
+ const client = useGchatClient(config);
14
+
15
+ return useQuery({
16
+ queryKey: ["greatchat", "contacts", config.accountId, params],
17
+ queryFn: () => client.listContacts(config.accountId, params),
18
+ enabled: !!config.accountId && !!config.token,
19
+ select: (res) => ({ data: res.data || [], total: res.total || 0 }),
20
+ });
21
+ }
22
+
23
+ export function useGetContact(
24
+ config: GchatHookConfig,
25
+ contactId: number | null,
26
+ ) {
27
+ const client = useGchatClient(config);
28
+
29
+ return useQuery({
30
+ queryKey: ["greatchat", "contact", config.accountId, contactId],
31
+ queryFn: () => client.getContact(config.accountId, contactId!),
32
+ enabled: !!config.accountId && !!config.token && !!contactId,
33
+ select: (res) => {
34
+ const d = res.data;
35
+ return (Array.isArray(d) ? d[0] : d) as Contact;
36
+ },
37
+ });
38
+ }
39
+
40
+ // ---------------------------------------------------------------------------
41
+ // Mutations
42
+ // ---------------------------------------------------------------------------
43
+
44
+ export function useCreateContact(config: GchatHookConfig) {
45
+ const client = useGchatClient(config);
46
+ const queryClient = useQueryClient();
47
+
48
+ return useMutation({
49
+ mutationFn: (body: {
50
+ name: string;
51
+ phone_number?: string;
52
+ identifier?: string;
53
+ }) => client.createContact(config.accountId, body),
54
+ onSuccess: () => {
55
+ queryClient.invalidateQueries({
56
+ queryKey: ["greatchat", "contacts"],
57
+ });
58
+ },
59
+ });
60
+ }
61
+
62
+ export function useUpdateContact(config: GchatHookConfig) {
63
+ const client = useGchatClient(config);
64
+ const queryClient = useQueryClient();
65
+
66
+ return useMutation({
67
+ mutationFn: ({
68
+ id,
69
+ body,
70
+ }: {
71
+ id: number;
72
+ body: { name?: string; phone_number?: string; identifier?: string };
73
+ }) => client.updateContact(config.accountId, id, body),
74
+ onSuccess: () => {
75
+ queryClient.invalidateQueries({
76
+ queryKey: ["greatchat", "contacts"],
77
+ });
78
+ },
79
+ });
80
+ }
81
+
82
+ export function useDeleteContact(config: GchatHookConfig) {
83
+ const client = useGchatClient(config);
84
+ const queryClient = useQueryClient();
85
+
86
+ return useMutation({
87
+ mutationFn: (id: number) => client.deleteContact(config.accountId, id),
88
+ onSuccess: () => {
89
+ queryClient.invalidateQueries({
90
+ queryKey: ["greatchat", "contacts"],
91
+ });
92
+ },
93
+ });
94
+ }
@@ -0,0 +1,405 @@
1
+ import { useMemo, useSyncExternalStore } from "react";
2
+ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
3
+ import type { InboxMessage } from "../types";
4
+ import {
5
+ type GchatHookConfig,
6
+ DEFAULT_MESSAGES_POLLING,
7
+ useGchatClient,
8
+ } from "./types";
9
+
10
+ // ---------------------------------------------------------------------------
11
+ // Optimistic message store (module-level — survives server refetches)
12
+ // ---------------------------------------------------------------------------
13
+
14
+ const optimisticStore = new Map<string, InboxMessage[]>();
15
+ let nextOptimisticId = -1;
16
+
17
+ // useSyncExternalStore subscription — guarantees synchronous re-renders
18
+ let storeVersion = 0;
19
+ const listeners = new Set<() => void>();
20
+
21
+ function subscribeStore(listener: () => void) {
22
+ listeners.add(listener);
23
+ return () => {
24
+ listeners.delete(listener);
25
+ };
26
+ }
27
+
28
+ function getStoreVersion() {
29
+ return storeVersion;
30
+ }
31
+
32
+ function storeKey(accountId: number, idInbox: number) {
33
+ return `${accountId}:${idInbox}`;
34
+ }
35
+
36
+ function getOptimistic(accountId: number, idInbox: number): InboxMessage[] {
37
+ return optimisticStore.get(storeKey(accountId, idInbox)) || [];
38
+ }
39
+
40
+ function setOptimistic(
41
+ accountId: number,
42
+ idInbox: number,
43
+ msgs: InboxMessage[],
44
+ ) {
45
+ const key = storeKey(accountId, idInbox);
46
+ if (msgs.length === 0) {
47
+ optimisticStore.delete(key);
48
+ } else {
49
+ optimisticStore.set(key, msgs);
50
+ }
51
+ storeVersion++;
52
+ listeners.forEach((fn) => fn());
53
+ }
54
+
55
+ /**
56
+ * Silently clean up the store without notifying listeners (avoids render loops).
57
+ * Used inside useMemo to remove optimistic messages confirmed by the server.
58
+ */
59
+ function cleanupOptimistic(
60
+ accountId: number,
61
+ idInbox: number,
62
+ msgs: InboxMessage[],
63
+ ) {
64
+ const key = storeKey(accountId, idInbox);
65
+ if (msgs.length === 0) {
66
+ optimisticStore.delete(key);
67
+ } else {
68
+ optimisticStore.set(key, msgs);
69
+ }
70
+ }
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // Query
74
+ // ---------------------------------------------------------------------------
75
+
76
+ export function useInboxMessages(
77
+ config: GchatHookConfig,
78
+ idInbox: number | null,
79
+ pollingInterval?: number,
80
+ ) {
81
+ const client = useGchatClient(config);
82
+
83
+ // Subscribe to optimistic store — re-renders when store changes
84
+ const optimisticVersion = useSyncExternalStore(
85
+ subscribeStore,
86
+ getStoreVersion,
87
+ getStoreVersion,
88
+ );
89
+
90
+ const query = useQuery({
91
+ queryKey: ["greatchat", "inbox-messages", config.accountId, idInbox],
92
+ queryFn: () =>
93
+ client.listInboxMessages(config.accountId, {
94
+ id_inbox: String(idInbox!),
95
+ sort: "datetime_add:asc",
96
+ limit: "100",
97
+ }),
98
+ enabled: !!config.accountId && !!config.token && !!idInbox,
99
+ refetchInterval: pollingInterval ?? DEFAULT_MESSAGES_POLLING,
100
+ select: (res) => res.data || [],
101
+ });
102
+
103
+ // Merge server data with optimistic messages
104
+ const messages = useMemo(() => {
105
+ const serverMessages = query.data || [];
106
+ if (!config.accountId || !idInbox) return serverMessages;
107
+
108
+ const optimistic = getOptimistic(config.accountId, idInbox);
109
+ if (!optimistic.length) return serverMessages;
110
+
111
+ // Separate overrides (positive ID = retry) from new messages (negative ID = send)
112
+ const overrides = new Map<number, InboxMessage>();
113
+ const newOptimistic: InboxMessage[] = [];
114
+ for (const om of optimistic) {
115
+ if (om.id > 0) {
116
+ overrides.set(om.id, om);
117
+ } else {
118
+ newOptimistic.push(om);
119
+ }
120
+ }
121
+
122
+ // Apply overrides to server messages (replace in-place)
123
+ const merged =
124
+ overrides.size > 0
125
+ ? serverMessages.map((sm) => overrides.get(sm.id) ?? sm)
126
+ : serverMessages;
127
+
128
+ // Auto-cleanup: remove overrides when server no longer shows "failed"
129
+ if (overrides.size > 0) {
130
+ for (const [id] of overrides) {
131
+ const sm = serverMessages.find((s) => s.id === id);
132
+ if (sm && sm.status !== "failed") {
133
+ overrides.delete(id);
134
+ }
135
+ }
136
+ }
137
+
138
+ // One-to-one matching for new optimistic messages (negative IDs)
139
+ const stillNeeded: InboxMessage[] = [];
140
+ const claimed = new Set<number>();
141
+
142
+ for (const om of newOptimistic) {
143
+ // Always keep failed messages (until user retries or dismisses)
144
+ if (om.status === "failed") {
145
+ stillNeeded.push(om);
146
+ continue;
147
+ }
148
+
149
+ // Find a matching server message that hasn't been claimed yet
150
+ const matchIdx = merged.findIndex(
151
+ (sm, i) =>
152
+ !claimed.has(i) &&
153
+ sm.direction === "outbound" &&
154
+ sm.content === om.content &&
155
+ sm.content_type === om.content_type &&
156
+ sm.source === om.source,
157
+ );
158
+
159
+ if (matchIdx >= 0) {
160
+ claimed.add(matchIdx); // server confirmed this one
161
+ } else {
162
+ stillNeeded.push(om); // keep showing optimistic
163
+ }
164
+ }
165
+
166
+ // Silently clean up confirmed messages (no re-notification)
167
+ const allKept = [...Array.from(overrides.values()), ...stillNeeded];
168
+ if (allKept.length !== optimistic.length) {
169
+ cleanupOptimistic(config.accountId, idInbox, allKept);
170
+ }
171
+
172
+ // Sort by datetime to keep chronological order
173
+ const result = [...merged, ...stillNeeded];
174
+ result.sort(
175
+ (a, b) =>
176
+ new Date(a.datetime_add).getTime() -
177
+ new Date(b.datetime_add).getTime(),
178
+ );
179
+ return result;
180
+ // eslint-disable-next-line react-hooks/exhaustive-deps
181
+ }, [query.data, config.accountId, idInbox, optimisticVersion]);
182
+
183
+ return { ...query, data: messages };
184
+ }
185
+
186
+ // ---------------------------------------------------------------------------
187
+ // Send mutation
188
+ // ---------------------------------------------------------------------------
189
+
190
+ export function useSendMessage(config: GchatHookConfig) {
191
+ const client = useGchatClient(config);
192
+ const queryClient = useQueryClient();
193
+
194
+ return useMutation({
195
+ mutationFn: async ({
196
+ idInbox,
197
+ content,
198
+ }: {
199
+ idInbox: number;
200
+ content: string;
201
+ }) => {
202
+ const result = await client.sendMessage(config.accountId, {
203
+ id_inbox: idInbox,
204
+ content,
205
+ content_type: "text",
206
+ source: "agent",
207
+ direction: "outbound",
208
+ });
209
+
210
+ if (result.status === 0) {
211
+ throw new Error(result.message || "Erro desconhecido ao enviar");
212
+ }
213
+
214
+ return result;
215
+ },
216
+
217
+ onMutate: (variables) => {
218
+ const msg: InboxMessage = {
219
+ id: nextOptimisticId--,
220
+ id_account: config.accountId,
221
+ id_inbox: variables.idInbox,
222
+ id_contact: null,
223
+ direction: "outbound",
224
+ content: variables.content,
225
+ content_type: "text",
226
+ content_url: null,
227
+ metadata: null,
228
+ external_id: null,
229
+ status: "pending",
230
+ source: "agent",
231
+ is_private: false,
232
+ datetime_add: new Date().toISOString(),
233
+ datetime_alt: null,
234
+ };
235
+
236
+ const current = getOptimistic(config.accountId, variables.idInbox);
237
+ setOptimistic(config.accountId, variables.idInbox, [...current, msg]);
238
+
239
+ return { optimisticMsg: msg };
240
+ },
241
+
242
+ onError: (error, variables, context) => {
243
+ if (!context) return;
244
+ const { optimisticMsg } = context;
245
+
246
+ const current = getOptimistic(config.accountId, variables.idInbox);
247
+ setOptimistic(
248
+ config.accountId,
249
+ variables.idInbox,
250
+ current.map((m) =>
251
+ m.id === optimisticMsg.id
252
+ ? { ...m, status: "failed" as const, _error: error.message }
253
+ : m,
254
+ ),
255
+ );
256
+ },
257
+
258
+ onSuccess: (_result, variables, context) => {
259
+ if (!context) return;
260
+ const { optimisticMsg } = context;
261
+
262
+ const current = getOptimistic(config.accountId, variables.idInbox);
263
+ setOptimistic(
264
+ config.accountId,
265
+ variables.idInbox,
266
+ current.filter((m) => m.id !== optimisticMsg.id),
267
+ );
268
+ queryClient.invalidateQueries({
269
+ queryKey: [
270
+ "greatchat",
271
+ "inbox-messages",
272
+ config.accountId,
273
+ variables.idInbox,
274
+ ],
275
+ });
276
+ queryClient.invalidateQueries({
277
+ queryKey: ["greatchat", "inboxes"],
278
+ });
279
+ },
280
+ });
281
+ }
282
+
283
+ // ---------------------------------------------------------------------------
284
+ // Retry failed message (updates in-place, same bubble transitions states)
285
+ // ---------------------------------------------------------------------------
286
+
287
+ export function useRetryMessage(config: GchatHookConfig) {
288
+ const client = useGchatClient(config);
289
+ const queryClient = useQueryClient();
290
+
291
+ return async (message: InboxMessage) => {
292
+ if (!config.accountId || !config.token || !message.content) return;
293
+
294
+ // Add as override with status "pending"
295
+ const current = getOptimistic(config.accountId, message.id_inbox);
296
+ setOptimistic(config.accountId, message.id_inbox, [
297
+ ...current.filter((m) => m.id !== message.id),
298
+ {
299
+ ...message,
300
+ status: "pending" as const,
301
+ _error: undefined,
302
+ datetime_add: new Date().toISOString(),
303
+ },
304
+ ]);
305
+
306
+ try {
307
+ const result = await client.sendMessage(config.accountId, {
308
+ id_inbox: message.id_inbox,
309
+ content: message.content,
310
+ content_type: message.content_type,
311
+ source: "agent",
312
+ direction: "outbound",
313
+ });
314
+
315
+ if (result.status === 0) {
316
+ throw new Error(result.message || "Erro desconhecido ao enviar");
317
+ }
318
+
319
+ const after = getOptimistic(config.accountId, message.id_inbox);
320
+ setOptimistic(
321
+ config.accountId,
322
+ message.id_inbox,
323
+ after.filter((m) => m.id !== message.id),
324
+ );
325
+ queryClient.invalidateQueries({
326
+ queryKey: [
327
+ "greatchat",
328
+ "inbox-messages",
329
+ config.accountId,
330
+ message.id_inbox,
331
+ ],
332
+ });
333
+ queryClient.invalidateQueries({
334
+ queryKey: ["greatchat", "inboxes"],
335
+ });
336
+ } catch (err) {
337
+ const errorMessage =
338
+ err instanceof Error ? err.message : "Erro ao enviar mensagem";
339
+ const after = getOptimistic(config.accountId, message.id_inbox);
340
+ setOptimistic(
341
+ config.accountId,
342
+ message.id_inbox,
343
+ after.map((m) =>
344
+ m.id === message.id
345
+ ? { ...m, status: "failed" as const, _error: errorMessage }
346
+ : m,
347
+ ),
348
+ );
349
+ }
350
+ };
351
+ }
352
+
353
+ // ---------------------------------------------------------------------------
354
+ // Revoke message
355
+ // ---------------------------------------------------------------------------
356
+
357
+ export function useRevokeMessage(config: GchatHookConfig) {
358
+ const client = useGchatClient(config);
359
+ const queryClient = useQueryClient();
360
+
361
+ return useMutation({
362
+ mutationFn: async ({ id }: { id: number; idInbox: number }) =>
363
+ client.revokeMessage(config.accountId, id),
364
+ onSuccess: (_data, variables) => {
365
+ queryClient.invalidateQueries({
366
+ queryKey: [
367
+ "greatchat",
368
+ "inbox-messages",
369
+ config.accountId,
370
+ variables.idInbox,
371
+ ],
372
+ });
373
+ },
374
+ });
375
+ }
376
+
377
+ // ---------------------------------------------------------------------------
378
+ // Edit message
379
+ // ---------------------------------------------------------------------------
380
+
381
+ export function useEditMessage(config: GchatHookConfig) {
382
+ const client = useGchatClient(config);
383
+ const queryClient = useQueryClient();
384
+
385
+ return useMutation({
386
+ mutationFn: async ({
387
+ id,
388
+ content,
389
+ }: {
390
+ id: number;
391
+ idInbox: number;
392
+ content: string;
393
+ }) => client.editMessage(config.accountId, id, { content }),
394
+ onSuccess: (_data, variables) => {
395
+ queryClient.invalidateQueries({
396
+ queryKey: [
397
+ "greatchat",
398
+ "inbox-messages",
399
+ config.accountId,
400
+ variables.idInbox,
401
+ ],
402
+ });
403
+ },
404
+ });
405
+ }