@in.pulse-crm/sdk 2.10.0 → 2.10.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.
package/.prettierrc CHANGED
@@ -1,4 +1,4 @@
1
- {
2
- "tabWidth": 4,
3
- "useTabs": true
4
- }
1
+ {
2
+ "tabWidth": 4,
3
+ "useTabs": true
4
+ }
@@ -1,5 +1,3 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
1
  import ApiClient from "./api-client";
4
2
  import { File, UploadFileOptions } from "./types/files.types";
5
3
  declare class FilesClient extends ApiClient {
@@ -1,5 +1,3 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
1
  export interface UploadFileOptions {
4
2
  /**
5
3
  * Nome da instância onde o arquivo está armazenado.
@@ -4,20 +4,24 @@ export interface WppContact {
4
4
  name: string;
5
5
  phone: string;
6
6
  customerId?: number;
7
+ avatarUrl?: string;
7
8
  instance: string;
8
9
  isBlocked: boolean;
9
10
  isOnlyAdmin: boolean;
11
+ lastOutOfHoursReplySentAt?: Date | null;
10
12
  }
11
13
  export interface WppContactWithCustomer {
12
14
  id: number;
13
15
  name: string;
14
16
  phone: string;
15
17
  customerId?: number;
18
+ avatarUrl?: string;
16
19
  instance: string;
17
20
  isBlocked: boolean;
18
21
  isOnlyAdmin: boolean;
19
22
  customer: Customer | null;
20
23
  chatingWith: string | null;
24
+ lastOutOfHoursReplySentAt?: Date | null;
21
25
  }
22
26
  export interface WppMessage {
23
27
  id: number;
@@ -29,6 +33,7 @@ export interface WppMessage {
29
33
  type: string;
30
34
  quotedId?: number | null;
31
35
  chatId?: number | null;
36
+ userName?: string;
32
37
  contactId?: number | null;
33
38
  body: string;
34
39
  timestamp: string;
@@ -55,6 +60,7 @@ export interface WppChat {
55
60
  instance: string;
56
61
  contactId?: number;
57
62
  userId?: number;
63
+ userName?: string;
58
64
  walletId?: number;
59
65
  botId?: number;
60
66
  resultId?: number;
@@ -148,3 +154,48 @@ export interface WppSchedule {
148
154
  chatId: number | null;
149
155
  contact: WppContact;
150
156
  }
157
+ export type NotificationType = "CHAT_AUTO_FINISHED" | "CHAT_TRANSFERRED" | "CHAT_REASSIGNED" | "ALERT" | "INFO" | "WARNING" | "ERROR";
158
+ export interface AppNotification {
159
+ id: number;
160
+ title: string;
161
+ description: string;
162
+ read: boolean;
163
+ instance: string;
164
+ userId: number | null;
165
+ chatId: number | null;
166
+ type: NotificationType;
167
+ createdAt: string;
168
+ }
169
+ export interface PaginatedNotificationsResponse {
170
+ notifications: AppNotification[];
171
+ totalCount: number;
172
+ }
173
+ export interface AutomaticResponseSchedule {
174
+ id?: number;
175
+ dayOfWeek: number;
176
+ startTime: string;
177
+ endTime: string;
178
+ }
179
+ export interface AutomaticResponseRule {
180
+ id: number;
181
+ name: string;
182
+ message: string;
183
+ isEnabled: boolean;
184
+ isGlobal: boolean;
185
+ cooldownSeconds: number;
186
+ fileId: number | null;
187
+ schedules: AutomaticResponseSchedule[];
188
+ userAssignments: {
189
+ userId: number;
190
+ }[];
191
+ }
192
+ export interface AutomaticResponseRuleDTO {
193
+ name: string;
194
+ message: string;
195
+ isEnabled: boolean;
196
+ isGlobal: boolean;
197
+ cooldownSeconds: number;
198
+ fileId?: number | null;
199
+ userIds: number[];
200
+ schedules: Omit<AutomaticResponseSchedule, 'id'>[];
201
+ }
@@ -1,6 +1,7 @@
1
1
  import ApiClient from "./api-client";
2
2
  import { RequestFilters } from "./types";
3
- import { CreateScheduleDTO, ForwardMessagesData, SendMessageData, WppChatsAndMessages, WppChatWithDetailsAndMessages, WppContact, WppContactWithCustomer, WppMessage, WppSchedule, WppWallet } from "./types/whatsapp.types";
3
+ import { DataResponse, MessageResponse } from "./types/response.types";
4
+ import { AppNotification, AutomaticResponseRule, AutomaticResponseRuleDTO, CreateScheduleDTO, ForwardMessagesData, PaginatedNotificationsResponse, SendMessageData, WppChatsAndMessages, WppChatWithDetailsAndMessages, WppContact, WppContactWithCustomer, WppMessage, WppSchedule, WppWallet } from "./types/whatsapp.types";
4
5
  interface FetchMessagesFilters {
5
6
  minDate: string;
6
7
  maxDate: string;
@@ -33,8 +34,22 @@ export default class WhatsappClient extends ApiClient {
33
34
  setAuth(token: string): void;
34
35
  getChatsMonitor(): Promise<WppChatsAndMessages>;
35
36
  transferAttendance(id: number, userId: number): Promise<void>;
36
- getNotifications(): Promise<any>;
37
- markAllAsReadNotification(): Promise<any>;
37
+ /**
38
+ * Busca as notificações do usuário de forma paginada.
39
+ */
40
+ getNotifications(params: {
41
+ page: number;
42
+ pageSize: number;
43
+ }): Promise<DataResponse<PaginatedNotificationsResponse>>;
44
+ /**
45
+ * Marca todas as notificações do usuário como lidas.
46
+ */
47
+ markAllAsReadNotification(): Promise<MessageResponse>;
48
+ /**
49
+ * Marca uma notificação específica como lida.
50
+ * @param notificationId - O ID (numérico) da notificação a ser marcada.
51
+ */
52
+ markOneAsReadNotification(notificationId: number): Promise<DataResponse<AppNotification>>;
38
53
  /**
39
54
  * Obtém os detalhes de um agendamento.
40
55
  * @param filters - keys de WppSchedule.
@@ -64,5 +79,9 @@ export default class WhatsappClient extends ApiClient {
64
79
  getMessages(token: string, filters: FetchMessagesFilters): Promise<(WppMessage & {
65
80
  WppContact: WppContact | null;
66
81
  })[]>;
82
+ getAutoResponseRules(): Promise<AutomaticResponseRule[]>;
83
+ createAutoResponseRule(ruleData: AutomaticResponseRuleDTO): Promise<AutomaticResponseRule>;
84
+ updateAutoResponseRule(id: number, ruleData: Omit<AutomaticResponseRuleDTO, 'instance'>): Promise<AutomaticResponseRule>;
85
+ deleteAutoResponseRule(id: number): Promise<void>;
67
86
  }
68
87
  export {};
@@ -128,15 +128,34 @@ class WhatsappClient extends api_client_1.default {
128
128
  const body = { userId };
129
129
  await this.ax.post(url, body);
130
130
  }
131
- async getNotifications() {
132
- const url = `/api/whatsapp/notifications`;
131
+ /**
132
+ * Busca as notificações do usuário de forma paginada.
133
+ */
134
+ async getNotifications(params) {
135
+ const searchParams = new URLSearchParams({
136
+ page: String(params.page),
137
+ pageSize: String(params.pageSize),
138
+ });
139
+ const url = `/api/whatsapp/notifications?${searchParams.toString()}`;
133
140
  const { data: res } = await this.ax.get(url);
134
- return res.data;
141
+ return res;
135
142
  }
143
+ /**
144
+ * Marca todas as notificações do usuário como lidas.
145
+ */
136
146
  async markAllAsReadNotification() {
137
147
  const url = `/api/whatsapp/notifications/mark-all-read`;
138
148
  const { data: res } = await this.ax.patch(url);
139
- return res.data;
149
+ return res;
150
+ }
151
+ /**
152
+ * Marca uma notificação específica como lida.
153
+ * @param notificationId - O ID (numérico) da notificação a ser marcada.
154
+ */
155
+ async markOneAsReadNotification(notificationId) {
156
+ const url = `/api/whatsapp/notifications/${notificationId}/read`;
157
+ const { data: res } = await this.ax.patch(url);
158
+ return res;
140
159
  }
141
160
  /**
142
161
  * Obtém os detalhes de um agendamento.
@@ -218,5 +237,24 @@ class WhatsappClient extends api_client_1.default {
218
237
  });
219
238
  return res.data;
220
239
  }
240
+ async getAutoResponseRules() {
241
+ const url = `/api/auto-response-rules`;
242
+ const { data: res } = await this.ax.get(url);
243
+ return res.data;
244
+ }
245
+ async createAutoResponseRule(ruleData) {
246
+ const url = `/api/auto-response-rules`;
247
+ const { data: res } = await this.ax.post(url, ruleData);
248
+ return res.data;
249
+ }
250
+ async updateAutoResponseRule(id, ruleData) {
251
+ const url = `/api/auto-response-rules/${id}`;
252
+ const { data: res } = await this.ax.put(url, ruleData);
253
+ return res.data;
254
+ }
255
+ async deleteAutoResponseRule(id) {
256
+ const url = `/api/auto-response-rules/${id}`;
257
+ await this.ax.delete(url);
258
+ }
221
259
  }
222
260
  exports.default = WhatsappClient;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@in.pulse-crm/sdk",
3
- "version": "2.10.0",
3
+ "version": "2.10.2",
4
4
  "description": "SDKs for abstraction of api consumption of in.pulse-crm application",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -5,9 +5,11 @@ export interface WppContact {
5
5
  name: string;
6
6
  phone: string;
7
7
  customerId?: number;
8
+ avatarUrl?: string;
8
9
  instance: string;
9
10
  isBlocked: boolean;
10
11
  isOnlyAdmin: boolean;
12
+ lastOutOfHoursReplySentAt?: Date | null;
11
13
  }
12
14
 
13
15
  export interface WppContactWithCustomer {
@@ -15,11 +17,13 @@ export interface WppContactWithCustomer {
15
17
  name: string;
16
18
  phone: string;
17
19
  customerId?: number;
20
+ avatarUrl?: string;
18
21
  instance: string;
19
22
  isBlocked: boolean;
20
23
  isOnlyAdmin: boolean;
21
24
  customer: Customer | null;
22
25
  chatingWith: string | null;
26
+ lastOutOfHoursReplySentAt?: Date | null;
23
27
  }
24
28
 
25
29
  export interface WppMessage {
@@ -32,6 +36,7 @@ export interface WppMessage {
32
36
  type: string;
33
37
  quotedId?: number | null;
34
38
  chatId?: number | null;
39
+ userName?: string;
35
40
  contactId?: number | null;
36
41
  body: string;
37
42
  timestamp: string;
@@ -54,6 +59,7 @@ export interface WppChat {
54
59
  instance: string;
55
60
  contactId?: number;
56
61
  userId?: number;
62
+ userName?: string;
57
63
  walletId?: number;
58
64
  botId?: number;
59
65
  resultId?: number;
@@ -164,3 +170,59 @@ export interface WppSchedule {
164
170
  chatId: number | null;
165
171
  contact: WppContact;
166
172
  }
173
+ export type NotificationType =
174
+ | "CHAT_AUTO_FINISHED"
175
+ | "CHAT_TRANSFERRED"
176
+ | "CHAT_REASSIGNED"
177
+ | "ALERT"
178
+ | "INFO"
179
+ | "WARNING"
180
+ | "ERROR";
181
+
182
+
183
+ export interface AppNotification {
184
+ id: number;
185
+ title: string;
186
+ description: string;
187
+ read: boolean;
188
+ instance: string;
189
+ userId: number | null;
190
+ chatId: number | null;
191
+ type: NotificationType;
192
+ createdAt: string;
193
+ }
194
+
195
+ export interface PaginatedNotificationsResponse {
196
+ notifications: AppNotification[];
197
+ totalCount: number;
198
+ }
199
+ export interface AutomaticResponseSchedule {
200
+ id?: number;
201
+ dayOfWeek: number;
202
+ startTime: string;
203
+ endTime: string;
204
+ }
205
+
206
+ export interface AutomaticResponseRule {
207
+ id: number;
208
+ name: string;
209
+ message: string;
210
+ isEnabled: boolean;
211
+ isGlobal: boolean;
212
+ cooldownSeconds: number;
213
+ fileId: number | null;
214
+ schedules: AutomaticResponseSchedule[];
215
+ userAssignments: { userId: number }[];
216
+ }
217
+
218
+ export interface AutomaticResponseRuleDTO {
219
+ name: string;
220
+ message: string;
221
+ isEnabled: boolean;
222
+ isGlobal: boolean;
223
+ cooldownSeconds: number;
224
+ fileId?: number | null;
225
+ userIds: number[];
226
+ schedules: Omit<AutomaticResponseSchedule, 'id'>[];
227
+ }
228
+
@@ -2,347 +2,365 @@ import ApiClient from "./api-client";
2
2
  import { RequestFilters } from "./types";
3
3
  import { DataResponse, MessageResponse } from "./types/response.types";
4
4
  import {
5
- CreateScheduleDTO,
6
- ForwardMessagesData,
7
- SendMessageData,
8
- WppChatsAndMessages,
9
- WppChatWithDetailsAndMessages,
10
- WppContact,
11
- WppContactWithCustomer,
12
- WppMessage,
13
- WppSchedule,
14
- WppWallet,
5
+ AppNotification,
6
+ AutomaticResponseRule,
7
+ AutomaticResponseRuleDTO,
8
+ CreateScheduleDTO,
9
+ ForwardMessagesData,
10
+ PaginatedNotificationsResponse,
11
+ SendMessageData,
12
+ WppChatsAndMessages,
13
+ WppChatWithDetailsAndMessages,
14
+ WppContact,
15
+ WppContactWithCustomer,
16
+ WppMessage,
17
+ WppSchedule,
18
+ WppWallet,
15
19
  } from "./types/whatsapp.types";
16
20
  import FormData from "form-data";
17
21
 
22
+
18
23
  type GetChatsResponse = DataResponse<WppChatsAndMessages>;
19
24
  type GetChatResponse = DataResponse<WppChatWithDetailsAndMessages>;
20
25
  type GetMessageResponse = DataResponse<WppMessage>;
21
26
  type MarkChatAsReadResponse = DataResponse<WppMessage[]>;
22
27
 
23
28
  interface FetchMessagesFilters {
24
- minDate: string;
25
- maxDate: string;
26
- userId?: number | null;
29
+ minDate: string;
30
+ maxDate: string;
31
+ userId?: number | null;
27
32
  }
28
33
 
29
34
  export default class WhatsappClient extends ApiClient {
30
- public async getChatsBySession(
31
- messages = false,
32
- contact = false,
33
- token: string | null = null,
34
- ) {
35
- const headers = token
36
- ? { Authorization: `Bearer ${token}` }
37
- : undefined;
38
- const url = `/api/whatsapp/session/chats?messages=${messages}&contact=${contact}`;
39
-
40
- const { data: res } = await this.ax.get<GetChatsResponse>(url, {
41
- headers,
42
- });
43
-
44
- return res.data;
45
- }
46
-
47
- public async getChatById(id: number) {
48
- const { data: res } = await this.ax.get<GetChatResponse>(
49
- `/api/whatsapp/chats/${id}`,
50
- );
51
-
52
- return res.data;
53
- }
54
-
55
- public async getMessageById(id: string) {
56
- const { data: res } = await this.ax.get<GetMessageResponse>(
57
- `/api/whatsapp/messages/${id}`,
58
- );
59
-
60
- return res.data;
61
- }
62
-
63
- public async getUserWallets(instance: string, userId: number) {
64
- const { data: res } = await this.ax.get<DataResponse<WppWallet[]>>(
65
- `/api/wallets?instance=${instance}&userId=${userId}`,
66
- );
67
-
68
- return res.data;
69
- }
70
-
71
- public async markContactMessagesAsRead(contactId: number) {
72
- const url = "/api/whatsapp/messages/mark-as-read";
73
- const body = { contactId };
74
- const { data: res } = await this.ax.patch<MarkChatAsReadResponse>(
75
- url,
76
- body,
77
- );
78
-
79
- return res.data;
80
- }
81
-
82
- public async sendMessage(to: string, data: SendMessageData) {
83
- const url = "/api/whatsapp/messages";
84
- const formData = new FormData();
85
-
86
- formData.append("to", to);
87
- data.text && formData.append("text", data.text);
88
- data.file && formData.append("file", data.file);
89
- data.quotedId && formData.append("quotedId", String(data.quotedId));
90
- data.chatId && formData.append("chatId", String(data.chatId));
91
- data.contactId && formData.append("contactId", String(data.contactId));
92
- data.sendAsAudio && formData.append("sendAsAudio", "true");
93
- data.sendAsDocument && formData.append("sendAsDocument", "true");
94
- data.sendAsChatOwner &&
95
- formData.append("sendAsChatOwner", String(data.sendAsChatOwner));
96
-
97
- const { data: res } = await this.ax.post<DataResponse<WppMessage>>(
98
- url,
99
- formData,
100
- {
101
- headers: {
102
- "Content-Type": "multipart/form-data",
103
- },
104
- },
105
- );
106
-
107
- return res.data;
108
- }
109
-
110
- public async finishChatById(id: number, resultId: number) {
111
- const url = `/api/whatsapp/chats/${id}/finish`;
112
- const body = { resultId };
113
-
114
- await this.ax.post<MessageResponse>(url, body);
115
- }
116
-
117
- public async startChatByContactId(contactId: number, template?: any) {
118
- const url = `/api/whatsapp/chats`;
119
- const body = { contactId, template };
120
-
121
- const { data: res } = await this.ax.post<
122
- DataResponse<WppChatWithDetailsAndMessages>
123
- >(url, body);
124
-
125
- return res.data;
126
- }
127
-
128
- public async getResults() {
129
- const url = `/api/whatsapp/results`;
130
- const { data: res } =
131
- await this.ax.get<DataResponse<{ id: number; name: string }[]>>(
132
- url,
133
- );
134
-
135
- return res.data;
136
- }
137
-
138
- public async getCustomerContacts(customerId: number) {
139
- const url = `/api/whatsapp/customer/${customerId}/contacts`;
140
- const { data: res } =
141
- await this.ax.get<DataResponse<WppContact[]>>(url);
142
-
143
- return res.data;
144
- }
145
-
146
- public async getContactsWithCustomer() {
147
- const url = `/api/whatsapp/contacts/customer`;
148
- const { data: res } =
149
- await this.ax.get<DataResponse<WppContactWithCustomer[]>>(url);
150
-
151
- return res.data;
152
- }
153
- public async getContacts() {
154
- const url = `/api/whatsapp/contacts`;
155
- const { data: res } =
156
- await this.ax.get<DataResponse<WppContact[]>>(url);
157
-
158
- return res.data;
159
- }
160
- public async createContact(
161
- name: string,
162
- phone: string,
163
- customerId?: number,
164
- ) {
165
- const baseUrl = `/api/whatsapp`;
166
- const url = customerId
167
- ? `${baseUrl}/customers/${customerId}/contacts`
168
- : `${baseUrl}/contacts`;
169
-
170
- const body = { name, phone };
171
-
172
- const { data: res } = await this.ax.post<DataResponse<WppContact>>(
173
- url,
174
- body,
175
- );
176
-
177
- return res.data;
178
- }
179
- public async forwardMessages(data: ForwardMessagesData) {
180
- const url = "/api/whatsapp/messages/forward";
181
-
182
- const body = data;
183
-
184
- await this.ax.post<MessageResponse>(url, body);
185
- }
186
- public async updateContact(
187
- contactId: number,
188
- name: string,
189
- customerId?: number | null,
190
- ) {
191
- const url = `/api/whatsapp/contacts/${contactId}`;
192
- const body: Record<string, any> = { name };
193
-
194
- customerId !== undefined && (body["customerId"] = customerId);
195
-
196
- const { data: res } = await this.ax.put<DataResponse<WppContact>>(
197
- url,
198
- body,
199
- );
200
-
201
- return res.data;
202
- }
203
-
204
- public async deleteContact(contactId: number) {
205
- const url = `/api/whatsapp/contacts/${contactId}`;
206
-
207
- await this.ax.delete<MessageResponse>(url);
208
- }
209
-
210
- public async getSectors() {
211
- const url = `/api/whatsapp/sectors`;
212
- const { data: res } =
213
- await this.ax.get<DataResponse<{ id: number; name: string }[]>>(
214
- url,
215
- );
216
-
217
- return res.data;
218
- }
219
-
220
- public setAuth(token: string) {
221
- this.ax.defaults.headers.common["Authorization"] = `Bearer ${token}`;
222
- }
223
- public async getChatsMonitor() {
224
- const url = `/api/whatsapp/session/monitor`;
225
-
226
- const { data: res } = await this.ax.get<GetChatsResponse>(url);
227
-
228
- return res.data;
229
- }
230
- public async transferAttendance(id: number, userId: number) {
231
- const url = `/api/whatsapp/chats/${id}/transfer`;
232
- const body = { userId };
233
-
234
- await this.ax.post<MessageResponse>(url, body);
235
- }
236
- public async getNotifications() {
237
- const url = `/api/whatsapp/notifications`;
238
- const { data: res } = await this.ax.get<DataResponse<any>>(url);
239
-
240
- return res.data;
241
- }
242
-
243
- public async markAllAsReadNotification() {
244
- const url = `/api/whatsapp/notifications/mark-all-read`;
245
- const { data: res } = await this.ax.patch<DataResponse<any>>(url);
246
-
247
- return res.data;
248
- }
249
-
250
- /**
251
- * Obtém os detalhes de um agendamento.
252
- * @param filters - keys de WppSchedule.
253
- * @param userId/sectorId filtrar por usúario/setor
254
- * @returns Uma Promise que resolve para um array de objetos wppSchedule.
255
- */
256
- public async getSchedules(
257
- userId?: string,
258
- sectorId?: string,
259
- filters?: RequestFilters<WppSchedule>,
260
- ) {
261
- let baseUrl = `/api/whatsapp/schedules`;
262
- const params = new URLSearchParams(filters);
263
-
264
- if (params.toString()) {
265
- if (userId && sectorId) {
266
- baseUrl += `?userId=${userId}&sectorId=${sectorId}&${params.toString()}`;
267
- } else if (userId) {
268
- baseUrl += `?userId=${userId}&${params.toString()}`;
269
- } else if (sectorId) {
270
- baseUrl += `?sectorId=${sectorId}&${params.toString()}`;
271
- } else {
272
- baseUrl += `?${params.toString()}`;
273
- }
274
- } else if (userId || sectorId) {
275
- if (userId && sectorId) {
276
- baseUrl += `?userId=${userId}&sectorId=${sectorId}`;
277
- } else if (userId) {
278
- baseUrl += `?userId=${userId}`;
279
- } else if (sectorId) {
280
- baseUrl += `?sectorId=${sectorId}`;
281
- }
282
- }
283
-
284
- const response = await this.ax.get(baseUrl);
285
- return response.data;
286
- }
287
-
288
- /**
289
- * Cria um novo agendamento.
290
- * @param scheduleData - Os dados do agendamento, keys de wppSchedule.
291
- * @returns Uma Promise que resolve para um objeto wppSchedule.
292
- */
293
- public async createSchedule(data: CreateScheduleDTO) {
294
- const response = await this.ax.post(`/api/whatsapp/schedules`, data);
295
- return response.data;
296
- }
297
-
298
- /**
299
- * Edita um agendamento existente.
300
- * @param scheduleId - O ID do agendamento a ser editado.
301
- * @param updatedData - Os dados atualizados do agendamento.
302
- * @returns Uma Promise que resolve para um objeto wppSchedule.
303
- */
304
- public async updateSchedule(
305
- scheduleId: number,
306
- updatedData: Record<string, WppSchedule>,
307
- ) {
308
- const response = await this.ax.patch(
309
- `/api/whatsapp/schedules/${scheduleId}`,
310
- updatedData,
311
- );
312
- return response.data;
313
- }
314
-
315
- /**
316
- * Exclui um agendamento.
317
- * @param scheduleId - O ID do agendamento a ser excluído.
318
- * @returns Uma Promise que resolve para um objeto wppSchedule.
319
- */
320
- public async deleteSchedule(scheduleId: number) {
321
- const response = await this.ax.delete(
322
- `/api/whatsapp/schedules/${scheduleId}`,
323
- );
324
- return response.data;
325
- }
326
-
327
- public async getMessages(token: string, filters: FetchMessagesFilters) {
328
- const params = new URLSearchParams(
329
- Object.entries(filters)
330
- .filter(([_, v]) => v !== undefined && v !== null)
331
- .reduce<Record<string, string>>((acc, [k, v]) => {
332
- acc[k] = String(v);
333
- return acc;
334
- }, {}),
335
- );
336
- const url = `/api/whatsapp/messages?${params.toString()}`;
337
-
338
- const { data: res } = await this.ax.get<
339
- DataResponse<(WppMessage & { WppContact: WppContact | null })[]>
340
- >(url, {
341
- headers: {
342
- Authorization: `Bearer ${token}`,
343
- },
344
- });
345
-
346
- return res.data;
347
- }
348
- }
35
+ public async getChatsBySession(
36
+ messages = false,
37
+ contact = false,
38
+ token: string | null = null,
39
+ ) {
40
+ const headers = token
41
+ ? { Authorization: `Bearer ${token}` }
42
+ : undefined;
43
+ const url = `/api/whatsapp/session/chats?messages=${messages}&contact=${contact}`;
44
+ const { data: res } = await this.ax.get<GetChatsResponse>(url, {
45
+ headers,
46
+ });
47
+ return res.data;
48
+ }
49
+
50
+ public async getChatById(id: number) {
51
+ const { data: res } = await this.ax.get<GetChatResponse>(
52
+ `/api/whatsapp/chats/${id}`,
53
+ );
54
+ return res.data;
55
+ }
56
+
57
+ public async getMessageById(id: string) {
58
+ const { data: res } = await this.ax.get<GetMessageResponse>(
59
+ `/api/whatsapp/messages/${id}`,
60
+ );
61
+ return res.data;
62
+ }
63
+
64
+ public async getUserWallets(instance: string, userId: number) {
65
+ const { data: res } = await this.ax.get<DataResponse<WppWallet[]>>(
66
+ `/api/wallets?instance=${instance}&userId=${userId}`,
67
+ );
68
+ return res.data;
69
+ }
70
+
71
+ public async markContactMessagesAsRead(contactId: number) {
72
+ const url = "/api/whatsapp/messages/mark-as-read";
73
+ const body = { contactId };
74
+ const { data: res } = await this.ax.patch<MarkChatAsReadResponse>(
75
+ url,
76
+ body,
77
+ );
78
+ return res.data;
79
+ }
80
+
81
+ public async sendMessage(to: string, data: SendMessageData) {
82
+ const url = "/api/whatsapp/messages";
83
+ const formData = new FormData();
84
+ formData.append("to", to);
85
+ data.text && formData.append("text", data.text);
86
+ data.file && formData.append("file", data.file);
87
+ data.quotedId && formData.append("quotedId", String(data.quotedId));
88
+ data.chatId && formData.append("chatId", String(data.chatId));
89
+ data.contactId && formData.append("contactId", String(data.contactId));
90
+ data.sendAsAudio && formData.append("sendAsAudio", "true");
91
+ data.sendAsDocument && formData.append("sendAsDocument", "true");
92
+ data.sendAsChatOwner &&
93
+ formData.append("sendAsChatOwner", String(data.sendAsChatOwner));
94
+ const { data: res } = await this.ax.post<DataResponse<WppMessage>>(
95
+ url,
96
+ formData,
97
+ {
98
+ headers: {
99
+ "Content-Type": "multipart/form-data",
100
+ },
101
+ },
102
+ );
103
+ return res.data;
104
+ }
105
+
106
+ public async finishChatById(id: number, resultId: number) {
107
+ const url = `/api/whatsapp/chats/${id}/finish`;
108
+ const body = { resultId };
109
+ await this.ax.post<MessageResponse>(url, body);
110
+ }
111
+
112
+ public async startChatByContactId(contactId: number, template?: any) {
113
+ const url = `/api/whatsapp/chats`;
114
+ const body = { contactId, template };
115
+ const { data: res } = await this.ax.post<
116
+ DataResponse<WppChatWithDetailsAndMessages>
117
+ >(url, body);
118
+ return res.data;
119
+ }
120
+
121
+ public async getResults() {
122
+ const url = `/api/whatsapp/results`;
123
+ const { data: res } =
124
+ await this.ax.get<DataResponse<{ id: number; name: string }[]>>(
125
+ url,
126
+ );
127
+ return res.data;
128
+ }
129
+
130
+ public async getCustomerContacts(customerId: number) {
131
+ const url = `/api/whatsapp/customer/${customerId}/contacts`;
132
+ const { data: res } =
133
+ await this.ax.get<DataResponse<WppContact[]>>(url);
134
+ return res.data;
135
+ }
136
+
137
+ public async getContactsWithCustomer() {
138
+ const url = `/api/whatsapp/contacts/customer`;
139
+ const { data: res } =
140
+ await this.ax.get<DataResponse<WppContactWithCustomer[]>>(url);
141
+ return res.data;
142
+ }
143
+
144
+ public async getContacts() {
145
+ const url = `/api/whatsapp/contacts`;
146
+ const { data: res } =
147
+ await this.ax.get<DataResponse<WppContact[]>>(url);
148
+ return res.data;
149
+ }
150
+
151
+ public async createContact(
152
+ name: string,
153
+ phone: string,
154
+ customerId?: number,
155
+ ) {
156
+ const baseUrl = `/api/whatsapp`;
157
+ const url = customerId
158
+ ? `${baseUrl}/customers/${customerId}/contacts`
159
+ : `${baseUrl}/contacts`;
160
+ const body = { name, phone };
161
+ const { data: res } = await this.ax.post<DataResponse<WppContact>>(
162
+ url,
163
+ body,
164
+ );
165
+ return res.data;
166
+ }
167
+
168
+ public async forwardMessages(data: ForwardMessagesData) {
169
+ const url = "/api/whatsapp/messages/forward";
170
+ const body = data;
171
+ await this.ax.post<MessageResponse>(url, body);
172
+ }
173
+
174
+ public async updateContact(
175
+ contactId: number,
176
+ name: string,
177
+ customerId?: number | null,
178
+ ) {
179
+ const url = `/api/whatsapp/contacts/${contactId}`;
180
+ const body: Record<string, any> = { name };
181
+ customerId !== undefined && (body["customerId"] = customerId);
182
+ const { data: res } = await this.ax.put<DataResponse<WppContact>>(
183
+ url,
184
+ body,
185
+ );
186
+ return res.data;
187
+ }
188
+
189
+ public async deleteContact(contactId: number) {
190
+ const url = `/api/whatsapp/contacts/${contactId}`;
191
+ await this.ax.delete<MessageResponse>(url);
192
+ }
193
+
194
+ public async getSectors() {
195
+ const url = `/api/whatsapp/sectors`;
196
+ const { data: res } =
197
+ await this.ax.get<DataResponse<{ id: number; name: string }[]>>(
198
+ url,
199
+ );
200
+ return res.data;
201
+ }
202
+
203
+ public setAuth(token: string) {
204
+ this.ax.defaults.headers.common["Authorization"] = `Bearer ${token}`;
205
+ }
206
+
207
+ public async getChatsMonitor() {
208
+ const url = `/api/whatsapp/session/monitor`;
209
+ const { data: res } = await this.ax.get<GetChatsResponse>(url);
210
+ return res.data;
211
+ }
212
+
213
+ public async transferAttendance(id: number, userId: number) {
214
+ const url = `/api/whatsapp/chats/${id}/transfer`;
215
+ const body = { userId };
216
+ await this.ax.post<MessageResponse>(url, body);
217
+ }
218
+ /**
219
+ * Busca as notificações do usuário de forma paginada.
220
+ */
221
+ public async getNotifications(params: { page: number; pageSize: number }) {
222
+ const searchParams = new URLSearchParams({
223
+ page: String(params.page),
224
+ pageSize: String(params.pageSize),
225
+ });
226
+ const url = `/api/whatsapp/notifications?${searchParams.toString()}`;
227
+ const { data: res } = await this.ax.get<DataResponse<PaginatedNotificationsResponse>>(url);
228
+ return res;
229
+ }
230
+
231
+ /**
232
+ * Marca todas as notificações do usuário como lidas.
233
+ */
234
+ public async markAllAsReadNotification() {
235
+ const url = `/api/whatsapp/notifications/mark-all-read`;
236
+ const { data: res } = await this.ax.patch<MessageResponse>(url);
237
+ return res;
238
+ }
239
+
240
+ /**
241
+ * Marca uma notificação específica como lida.
242
+ * @param notificationId - O ID (numérico) da notificação a ser marcada.
243
+ */
244
+ public async markOneAsReadNotification(notificationId: number) {
245
+ const url = `/api/whatsapp/notifications/${notificationId}/read`;
246
+ const { data: res } = await this.ax.patch<DataResponse<AppNotification>>(url);
247
+ return res;
248
+ }
249
+
250
+ /**
251
+ * Obtém os detalhes de um agendamento.
252
+ * @param filters - keys de WppSchedule.
253
+ * @param userId/sectorId filtrar por usúario/setor
254
+ * @returns Uma Promise que resolve para um array de objetos wppSchedule.
255
+ */
256
+ public async getSchedules(
257
+ userId?: string,
258
+ sectorId?: string,
259
+ filters?: RequestFilters<WppSchedule>,
260
+ ) {
261
+ let baseUrl = `/api/whatsapp/schedules`;
262
+ const params = new URLSearchParams(filters);
263
+ if (params.toString()) {
264
+ if (userId && sectorId) {
265
+ baseUrl += `?userId=${userId}&sectorId=${sectorId}&${params.toString()}`;
266
+ } else if (userId) {
267
+ baseUrl += `?userId=${userId}&${params.toString()}`;
268
+ } else if (sectorId) {
269
+ baseUrl += `?sectorId=${sectorId}&${params.toString()}`;
270
+ } else {
271
+ baseUrl += `?${params.toString()}`;
272
+ }
273
+ } else if (userId || sectorId) {
274
+ if (userId && sectorId) {
275
+ baseUrl += `?userId=${userId}&sectorId=${sectorId}`;
276
+ } else if (userId) {
277
+ baseUrl += `?userId=${userId}`;
278
+ } else if (sectorId) {
279
+ baseUrl += `?sectorId=${sectorId}`;
280
+ }
281
+ }
282
+ const response = await this.ax.get(baseUrl);
283
+ return response.data;
284
+ }
285
+
286
+ /**
287
+ * Cria um novo agendamento.
288
+ * @param scheduleData - Os dados do agendamento, keys de wppSchedule.
289
+ * @returns Uma Promise que resolve para um objeto wppSchedule.
290
+ */
291
+ public async createSchedule(data: CreateScheduleDTO) {
292
+ const response = await this.ax.post(`/api/whatsapp/schedules`, data);
293
+ return response.data;
294
+ }
295
+
296
+ /**
297
+ * Edita um agendamento existente.
298
+ * @param scheduleId - O ID do agendamento a ser editado.
299
+ * @param updatedData - Os dados atualizados do agendamento.
300
+ * @returns Uma Promise que resolve para um objeto wppSchedule.
301
+ */
302
+ public async updateSchedule(
303
+ scheduleId: number,
304
+ updatedData: Record<string, WppSchedule>,
305
+ ) {
306
+ const response = await this.ax.patch(
307
+ `/api/whatsapp/schedules/${scheduleId}`,
308
+ updatedData,
309
+ );
310
+ return response.data;
311
+ }
312
+
313
+ /**
314
+ * Exclui um agendamento.
315
+ * @param scheduleId - O ID do agendamento a ser excluído.
316
+ * @returns Uma Promise que resolve para um objeto wppSchedule.
317
+ */
318
+ public async deleteSchedule(scheduleId: number) {
319
+ const response = await this.ax.delete(
320
+ `/api/whatsapp/schedules/${scheduleId}`,
321
+ );
322
+ return response.data;
323
+ }
324
+
325
+ public async getMessages(token: string, filters: FetchMessagesFilters) {
326
+ const params = new URLSearchParams(
327
+ Object.entries(filters)
328
+ .filter(([_, v]) => v !== undefined && v !== null)
329
+ .reduce<Record<string, string>>((acc, [k, v]) => {
330
+ acc[k] = String(v);
331
+ return acc;
332
+ }, {}),
333
+ );
334
+ const url = `/api/whatsapp/messages?${params.toString()}`;
335
+ const { data: res } = await this.ax.get<
336
+ DataResponse<(WppMessage & { WppContact: WppContact | null })[]>
337
+ >(url, {
338
+ headers: {
339
+ Authorization: `Bearer ${token}`,
340
+ },
341
+ });
342
+ return res.data;
343
+ }
344
+ public async getAutoResponseRules() {
345
+ const url = `/api/auto-response-rules`;
346
+ const { data: res } = await this.ax.get<DataResponse<AutomaticResponseRule[]>>(url);
347
+ return res.data;
348
+ }
349
+
350
+ public async createAutoResponseRule(ruleData: AutomaticResponseRuleDTO) {
351
+ const url = `/api/auto-response-rules`;
352
+ const { data: res } = await this.ax.post<DataResponse<AutomaticResponseRule>>(url, ruleData);
353
+ return res.data;
354
+ }
355
+
356
+ public async updateAutoResponseRule(id: number, ruleData: Omit<AutomaticResponseRuleDTO, 'instance'>) {
357
+ const url = `/api/auto-response-rules/${id}`;
358
+ const { data: res } = await this.ax.put<DataResponse<AutomaticResponseRule>>(url, ruleData);
359
+ return res.data;
360
+ }
361
+
362
+ public async deleteAutoResponseRule(id: number) {
363
+ const url = `/api/auto-response-rules/${id}`;
364
+ await this.ax.delete<MessageResponse>(url);
365
+ }
366
+ }
package/tsconfig.json CHANGED
@@ -1,17 +1,17 @@
1
- {
2
- "compilerOptions": {
3
- "target": "es2022" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
4
- "module": "commonjs" /* Specify what module code is generated. */,
5
- "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
6
- "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
7
- "strict": true /* Enable all strict type-checking options. */,
8
- "skipLibCheck": true /* Skip type checking all .d.ts files. */,
9
- "noUnusedLocals": false,
10
- "outDir": "./dist", /* Redirect output structure to the directory. */
11
- "declaration": true
12
- },
13
- "include": [
14
- "src/index.ts",
15
- "src/**/*.{ts}"
16
- ]
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2022" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
4
+ "module": "commonjs" /* Specify what module code is generated. */,
5
+ "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
6
+ "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
7
+ "strict": true /* Enable all strict type-checking options. */,
8
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */,
9
+ "noUnusedLocals": false,
10
+ "outDir": "./dist", /* Redirect output structure to the directory. */
11
+ "declaration": true
12
+ },
13
+ "include": [
14
+ "src/index.ts",
15
+ "src/**/*.{ts}"
16
+ ]
17
17
  }