@ikatec/digisac-api-sdk 4.5.1 → 4.7.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 (129) hide show
  1. package/README.md +16 -11
  2. package/dist/apis/answers/AnswersApi.cjs +38 -0
  3. package/dist/apis/answers/AnswersApi.cjs.map +1 -1
  4. package/dist/apis/answers/AnswersApi.d.ts +33 -2
  5. package/dist/apis/answers/AnswersApi.d.ts.map +1 -1
  6. package/dist/apis/answers/AnswersApi.mjs +38 -0
  7. package/dist/apis/answers/AnswersApi.mjs.map +1 -1
  8. package/dist/apis/answers/types.d.ts +64 -1
  9. package/dist/apis/answers/types.d.ts.map +1 -1
  10. package/dist/apis/botSimulators/BotSimulatorsApi.cjs +42 -0
  11. package/dist/apis/botSimulators/BotSimulatorsApi.cjs.map +1 -0
  12. package/dist/apis/botSimulators/BotSimulatorsApi.d.ts +31 -0
  13. package/dist/apis/botSimulators/BotSimulatorsApi.d.ts.map +1 -0
  14. package/dist/apis/botSimulators/BotSimulatorsApi.mjs +41 -0
  15. package/dist/apis/botSimulators/BotSimulatorsApi.mjs.map +1 -0
  16. package/dist/apis/botSimulators/index.cjs +4 -0
  17. package/dist/apis/botSimulators/index.d.ts +3 -0
  18. package/dist/apis/botSimulators/index.d.ts.map +1 -0
  19. package/dist/apis/botSimulators/index.mjs +3 -0
  20. package/dist/apis/botSimulators/types.cjs +0 -0
  21. package/dist/apis/botSimulators/types.d.ts +73 -0
  22. package/dist/apis/botSimulators/types.d.ts.map +1 -0
  23. package/dist/apis/botSimulators/types.mjs +0 -0
  24. package/dist/apis/botVersions/BotVersionsApi.cjs +25 -0
  25. package/dist/apis/botVersions/BotVersionsApi.cjs.map +1 -1
  26. package/dist/apis/botVersions/BotVersionsApi.d.ts +18 -0
  27. package/dist/apis/botVersions/BotVersionsApi.d.ts.map +1 -1
  28. package/dist/apis/botVersions/BotVersionsApi.mjs +25 -0
  29. package/dist/apis/botVersions/BotVersionsApi.mjs.map +1 -1
  30. package/dist/apis/botVersions/types.d.ts +4 -0
  31. package/dist/apis/botVersions/types.d.ts.map +1 -1
  32. package/dist/apis/bots/BotsApi.cjs +99 -4
  33. package/dist/apis/bots/BotsApi.cjs.map +1 -1
  34. package/dist/apis/bots/BotsApi.d.ts +78 -5
  35. package/dist/apis/bots/BotsApi.d.ts.map +1 -1
  36. package/dist/apis/bots/BotsApi.mjs +99 -4
  37. package/dist/apis/bots/BotsApi.mjs.map +1 -1
  38. package/dist/apis/bots/types.d.ts +266 -16
  39. package/dist/apis/bots/types.d.ts.map +1 -1
  40. package/dist/apis/index.cjs +3 -0
  41. package/dist/apis/index.d.ts +1 -0
  42. package/dist/apis/index.d.ts.map +1 -1
  43. package/dist/apis/index.mjs +3 -1
  44. package/dist/apis/questions/QuestionsApi.cjs +15 -0
  45. package/dist/apis/questions/QuestionsApi.cjs.map +1 -1
  46. package/dist/apis/questions/QuestionsApi.d.ts +15 -1
  47. package/dist/apis/questions/QuestionsApi.d.ts.map +1 -1
  48. package/dist/apis/questions/QuestionsApi.mjs +15 -0
  49. package/dist/apis/questions/QuestionsApi.mjs.map +1 -1
  50. package/dist/apis/questions/types.d.ts +25 -5
  51. package/dist/apis/questions/types.d.ts.map +1 -1
  52. package/dist/apis/quickReplies/QuickRepliesApi.cjs +16 -0
  53. package/dist/apis/quickReplies/QuickRepliesApi.cjs.map +1 -1
  54. package/dist/apis/quickReplies/QuickRepliesApi.d.ts +15 -2
  55. package/dist/apis/quickReplies/QuickRepliesApi.d.ts.map +1 -1
  56. package/dist/apis/quickReplies/QuickRepliesApi.mjs +16 -0
  57. package/dist/apis/quickReplies/QuickRepliesApi.mjs.map +1 -1
  58. package/dist/apis/quickReplies/types.d.ts +30 -2
  59. package/dist/apis/quickReplies/types.d.ts.map +1 -1
  60. package/dist/apis/schedule/ScheduleApi.cjs +37 -2
  61. package/dist/apis/schedule/ScheduleApi.cjs.map +1 -1
  62. package/dist/apis/schedule/ScheduleApi.d.ts +30 -3
  63. package/dist/apis/schedule/ScheduleApi.d.ts.map +1 -1
  64. package/dist/apis/schedule/ScheduleApi.mjs +37 -2
  65. package/dist/apis/schedule/ScheduleApi.mjs.map +1 -1
  66. package/dist/apis/schedule/types.d.ts +58 -11
  67. package/dist/apis/schedule/types.d.ts.map +1 -1
  68. package/dist/apis/ticketTopics/TicketTopicsApi.cjs +25 -2
  69. package/dist/apis/ticketTopics/TicketTopicsApi.cjs.map +1 -1
  70. package/dist/apis/ticketTopics/TicketTopicsApi.d.ts +18 -4
  71. package/dist/apis/ticketTopics/TicketTopicsApi.d.ts.map +1 -1
  72. package/dist/apis/ticketTopics/TicketTopicsApi.mjs +25 -2
  73. package/dist/apis/ticketTopics/TicketTopicsApi.mjs.map +1 -1
  74. package/dist/apis/ticketTopics/types.d.ts +22 -1
  75. package/dist/apis/ticketTopics/types.d.ts.map +1 -1
  76. package/dist/apis/tickets/TicketsApi.cjs +74 -1
  77. package/dist/apis/tickets/TicketsApi.cjs.map +1 -1
  78. package/dist/apis/tickets/TicketsApi.d.ts +68 -3
  79. package/dist/apis/tickets/TicketsApi.d.ts.map +1 -1
  80. package/dist/apis/tickets/TicketsApi.mjs +74 -1
  81. package/dist/apis/tickets/TicketsApi.mjs.map +1 -1
  82. package/dist/apis/tickets/types.d.ts +69 -8
  83. package/dist/apis/tickets/types.d.ts.map +1 -1
  84. package/dist/core/BaseCrudApi.cjs +5 -2
  85. package/dist/core/BaseCrudApi.cjs.map +1 -1
  86. package/dist/core/BaseCrudApi.d.ts +7 -4
  87. package/dist/core/BaseCrudApi.d.ts.map +1 -1
  88. package/dist/core/BaseCrudApi.mjs +5 -2
  89. package/dist/core/BaseCrudApi.mjs.map +1 -1
  90. package/dist/core/types.d.ts +1 -1
  91. package/dist/core/types.d.ts.map +1 -1
  92. package/dist/incommingWebhooks/index.d.ts +17 -9
  93. package/dist/incommingWebhooks/index.d.ts.map +1 -1
  94. package/package.json +1 -1
  95. package/src/apis/answers/AnswersApi.test.ts +67 -0
  96. package/src/apis/answers/AnswersApi.ts +66 -2
  97. package/src/apis/answers/types.ts +64 -2
  98. package/src/apis/botSimulators/BotSimulatorsApi.test.ts +58 -0
  99. package/src/apis/botSimulators/BotSimulatorsApi.ts +57 -0
  100. package/src/apis/botSimulators/index.ts +2 -0
  101. package/src/apis/botSimulators/types.ts +72 -0
  102. package/src/apis/botVersions/BotVersionsApi.test.ts +51 -0
  103. package/src/apis/botVersions/BotVersionsApi.ts +41 -0
  104. package/src/apis/botVersions/types.ts +4 -0
  105. package/src/apis/bots/BotsApi.test.ts +177 -0
  106. package/src/apis/bots/BotsApi.ts +162 -6
  107. package/src/apis/bots/types.ts +267 -15
  108. package/src/apis/index.ts +1 -0
  109. package/src/apis/payloads.test-d.ts +178 -1
  110. package/src/apis/queryFormat.test.ts +23 -0
  111. package/src/apis/questions/QuestionsApi.test.ts +49 -0
  112. package/src/apis/questions/QuestionsApi.ts +20 -1
  113. package/src/apis/questions/types.ts +25 -6
  114. package/src/apis/quickReplies/QuickRepliesApi.test.ts +69 -0
  115. package/src/apis/quickReplies/QuickRepliesApi.ts +35 -2
  116. package/src/apis/quickReplies/types.ts +34 -2
  117. package/src/apis/schedule/ScheduleApi.test.ts +80 -0
  118. package/src/apis/schedule/ScheduleApi.ts +59 -6
  119. package/src/apis/schedule/types.ts +66 -11
  120. package/src/apis/ticketTopics/TicketTopicsApi.test.ts +40 -0
  121. package/src/apis/ticketTopics/TicketTopicsApi.ts +35 -4
  122. package/src/apis/ticketTopics/types.ts +26 -1
  123. package/src/apis/tickets/TicketsApi.test.ts +142 -5
  124. package/src/apis/tickets/TicketsApi.ts +135 -3
  125. package/src/apis/tickets/types.ts +76 -6
  126. package/src/core/BaseCrudApi.ts +9 -5
  127. package/src/core/types.ts +2 -1
  128. package/src/incommingWebhooks/index.test-d.ts +23 -1
  129. package/src/incommingWebhooks/index.ts +18 -9
@@ -0,0 +1,177 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest'
2
+ import type { ApiClient } from '../../core/ApiClient'
3
+ import { BotsApi } from './BotsApi'
4
+ import type { BotContextInput } from './types'
5
+
6
+ // ── Mock client factory ──────────────────────────────────────────────
7
+
8
+ function createMockClient(): ApiClient {
9
+ return {
10
+ setAccessToken: vi.fn().mockReturnThis(),
11
+ request: vi.fn(),
12
+ get: vi.fn(),
13
+ post: vi.fn(),
14
+ put: vi.fn(),
15
+ patch: vi.fn(),
16
+ delete: vi.fn(),
17
+ }
18
+ }
19
+
20
+ const headers = { 'X-Custom': 'value' }
21
+
22
+ const contexts: BotContextInput[] = [
23
+ {
24
+ id: '@INIT',
25
+ name: 'Contexto inicial',
26
+ triggers: [
27
+ {
28
+ trigger: { type: 'TICKET_OPENED' },
29
+ rules: [
30
+ {
31
+ title: 'abertura',
32
+ conditions: [],
33
+ actions: [{ type: { value: 'SEND_MESSAGE' }, data: { text: 'Olá' } }],
34
+ },
35
+ ],
36
+ },
37
+ ],
38
+ },
39
+ ]
40
+
41
+ // ── Tests ────────────────────────────────────────────────────────────
42
+
43
+ describe('BotsApi', () => {
44
+ let client: ReturnType<typeof createMockClient>
45
+ let api: BotsApi
46
+
47
+ beforeEach(() => {
48
+ client = createMockClient()
49
+ api = new BotsApi(client)
50
+ })
51
+
52
+ describe('getMany', () => {
53
+ it('calls client.get with /bots and the query', async () => {
54
+ await api.getMany({ where: { name: 'x' } }, headers)
55
+ expect(client.get).toHaveBeenCalledWith(
56
+ `/bots?query=${encodeURIComponent(JSON.stringify({ where: { name: 'x' } }))}`,
57
+ headers,
58
+ )
59
+ })
60
+ })
61
+
62
+ describe('getOne', () => {
63
+ it('reads the first item of a one-item page', async () => {
64
+ vi.mocked(client.get).mockResolvedValue({ data: [{ id: 'b1' }], total: 1 })
65
+ const result = await api.getOne({ where: { name: 'x' } })
66
+ expect(client.get).toHaveBeenCalledWith(
67
+ `/bots?query=${encodeURIComponent(
68
+ JSON.stringify({ where: { name: 'x' }, perPage: 1, page: 1 }),
69
+ )}`,
70
+ undefined,
71
+ )
72
+ expect(result).toEqual({ id: 'b1' })
73
+ })
74
+
75
+ it('resolves null on an empty page', async () => {
76
+ vi.mocked(client.get).mockResolvedValue({ data: [], total: 0 })
77
+ expect(await api.getOne()).toBeNull()
78
+ })
79
+ })
80
+
81
+ describe('CRUD', () => {
82
+ it('getById calls client.get with /bots/:id', async () => {
83
+ await api.getById('b1', { include: ['currentBotVersion'] }, headers)
84
+ expect(client.get).toHaveBeenCalledWith(
85
+ `/bots/b1?query=${encodeURIComponent(JSON.stringify({ include: ['currentBotVersion'] }))}`,
86
+ headers,
87
+ )
88
+ })
89
+
90
+ it('create calls client.post with /bots and the contexts list', async () => {
91
+ const body = { name: 'Robô', contexts, isDraft: true }
92
+ await api.create(body, headers)
93
+ expect(client.post).toHaveBeenCalledWith('/bots', body, headers)
94
+ })
95
+
96
+ it('updateById saves the flow or only renames', async () => {
97
+ await api.updateById('b1', { name: 'Robô', contexts })
98
+ expect(client.put).toHaveBeenCalledWith('/bots/b1', { name: 'Robô', contexts }, undefined)
99
+ await api.updateById('b1', { name: 'Novo', onlyUpdateBotName: true })
100
+ expect(client.put).toHaveBeenCalledWith(
101
+ '/bots/b1',
102
+ { name: 'Novo', onlyUpdateBotName: true },
103
+ undefined,
104
+ )
105
+ })
106
+
107
+ it('deleteById calls client.delete with /bots/:id', async () => {
108
+ vi.mocked(client.delete).mockResolvedValue(false)
109
+ expect(await api.deleteById('b1', headers)).toBe(false)
110
+ expect(client.delete).toHaveBeenCalledWith('/bots/b1', headers)
111
+ })
112
+
113
+ it("deleteById passes the 'OK' of a fixed backend through", async () => {
114
+ vi.mocked(client.delete).mockResolvedValue('OK')
115
+ expect(await api.deleteById('b1')).toBe('OK')
116
+ })
117
+ })
118
+
119
+ describe('getErrors', () => {
120
+ it('calls client.get with /bots/:id/errors and the filters', async () => {
121
+ const query = { page: 2, perPage: 10, errorCode: 'TIMEOUT', sort: 'serviceName' }
122
+ await api.getErrors('b1', query, headers)
123
+ expect(client.get).toHaveBeenCalledWith(
124
+ `/bots/b1/errors?query=${encodeURIComponent(JSON.stringify(query))}`,
125
+ headers,
126
+ )
127
+ })
128
+
129
+ it('sends no query string without filters', async () => {
130
+ await api.getErrors('b1')
131
+ expect(client.get).toHaveBeenCalledWith('/bots/b1/errors', undefined)
132
+ })
133
+ })
134
+
135
+ describe('triggerSignal', () => {
136
+ it('sends the flag in the body', async () => {
137
+ await api.triggerSignal('b1', 'c1', 'vip', headers)
138
+ expect(client.post).toHaveBeenCalledWith(
139
+ '/bots/b1/trigger-signal/c1',
140
+ { flag: 'vip' },
141
+ headers,
142
+ )
143
+ })
144
+
145
+ it('sends no body without a flag', async () => {
146
+ await api.triggerSignal('b1', 'c1')
147
+ expect(client.post).toHaveBeenCalledWith('/bots/b1/trigger-signal/c1', undefined, undefined)
148
+ })
149
+ })
150
+
151
+ describe('requestCallback', () => {
152
+ it('posts the response data to /bots/:id/request-callback/:pendingRequestId', async () => {
153
+ await api.requestCallback('b1', 'h1', { status: 'paid' }, headers)
154
+ expect(client.post).toHaveBeenCalledWith(
155
+ '/bots/b1/request-callback/h1',
156
+ { status: 'paid' },
157
+ headers,
158
+ )
159
+ })
160
+ })
161
+
162
+ describe('suggestAgentPrompt', () => {
163
+ it('posts the agent config to /bots/suggest-agent-prompt', async () => {
164
+ vi.mocked(client.post).mockResolvedValue('Você é um agente...')
165
+ const body = {
166
+ voiceTone: 'formal',
167
+ languageType: 'simple',
168
+ function: 'support',
169
+ companySegment: 'Varejo',
170
+ companySubject: 'Loja',
171
+ companyServices: 'Vendas',
172
+ } as const
173
+ expect(await api.suggestAgentPrompt(body)).toBe('Você é um agente...')
174
+ expect(client.post).toHaveBeenCalledWith('/bots/suggest-agent-prompt', body, undefined)
175
+ })
176
+ })
177
+ })
@@ -1,9 +1,165 @@
1
- import type { ApiClient } from '../../core/ApiClient'
2
- import { BaseCrudApi } from '../../core/BaseCrudApi'
3
- import type { Bot, CreateBotPayload, UpdateBotPayload } from './types'
1
+ import { BaseApi } from '../../core/BaseApi'
2
+ import type {
3
+ GetByIdQuery,
4
+ HasCreate,
5
+ HasDeleteById,
6
+ HasGetById,
7
+ HasUpdateById,
8
+ ListQuery,
9
+ Paginated,
10
+ } from '../../core/types'
11
+ import type {
12
+ Bot,
13
+ BotErrorsQuery,
14
+ BotHistory,
15
+ CreateBotPayload,
16
+ SuggestAgentPromptPayload,
17
+ UpdateBotPayload,
18
+ } from './types'
4
19
 
5
- export class BotsApi extends BaseCrudApi<Bot, CreateBotPayload, UpdateBotPayload> {
6
- constructor(client: ApiClient) {
7
- super(client, '/bots')
20
+ /**
21
+ * Bots. The list route always paginates (`paginate: false` is ignored), so this class does not
22
+ * extend `BaseCrudApi`. The contexts travel as a list (`BotContextInput` / `BotParsedContext`),
23
+ * not as the stored map that `BotVersionsApi` serves.
24
+ *
25
+ * `GET /bots/:id/errors/export` is not exposed: it answers a binary xlsx, and `ApiClient` only
26
+ * handles JSON/text bodies.
27
+ */
28
+ export class BotsApi
29
+ extends BaseApi
30
+ implements
31
+ HasGetById<Bot>,
32
+ HasCreate<Bot, CreateBotPayload>,
33
+ HasUpdateById<Bot, UpdateBotPayload>,
34
+ HasDeleteById<'OK' | false>
35
+ {
36
+ public readonly basePath = '/bots'
37
+
38
+ /**
39
+ * Lists the bots of the account. Always paginated, even with `paginate: false`.
40
+ * @permissions bots.view
41
+ */
42
+ getMany(query?: ListQuery<Bot>, headers?: Record<string, string>): Promise<Paginated<Bot>> {
43
+ return this.client.get<Paginated<Bot>>(`${this.basePath}${this.toQueryString(query)}`, headers)
44
+ }
45
+
46
+ /**
47
+ * Returns the first bot matching the query, or `null` when none match.
48
+ * @permissions bots.view
49
+ */
50
+ async getOne(query?: ListQuery<Bot>, headers?: Record<string, string>): Promise<Bot | null> {
51
+ const page = await this.getMany({ ...query, perPage: 1, page: 1 }, headers)
52
+ return page?.data?.[0] ?? null
53
+ }
54
+
55
+ /**
56
+ * Returns a bot by ID, with `defaultContexts` (the stored map, as a JSON string). An unknown id
57
+ * answers 500, not an empty body.
58
+ * @permissions bots.view
59
+ */
60
+ getById(id: string, query?: GetByIdQuery<Bot>, headers?: Record<string, string>): Promise<Bot> {
61
+ return this.client.get<Bot>(`${this.basePath}/${id}${this.toQueryString(query)}`, headers)
62
+ }
63
+
64
+ /**
65
+ * Creates a bot and its first version (published, or a draft with `isDraft`). A duplicate name
66
+ * answers 409, unless the account allows duplicate names. Send `flowJson` with `edges`, or the
67
+ * bot never sends a message (SD-2323).
68
+ * @permissions bots.create
69
+ */
70
+ create(body: CreateBotPayload, headers?: Record<string, string>): Promise<Bot> {
71
+ return this.client.post<Bot, CreateBotPayload>(this.basePath, body, headers)
72
+ }
73
+
74
+ /**
75
+ * Saves the flow (publishing a version, or into the draft with `isDraft`), or only renames the
76
+ * bot with `onlyUpdateBotName`. Resolves to the bot with `defaultContexts` as an object.
77
+ * @permissions bots.view OR bots.update
78
+ */
79
+ updateById(id: string, body: UpdateBotPayload, headers?: Record<string, string>): Promise<Bot> {
80
+ return this.client.put<Bot, UpdateBotPayload>(`${this.basePath}/${id}`, body, headers)
81
+ }
82
+
83
+ /**
84
+ * Deletes a bot and its versions (hard delete). Today resolves to `false` even when the bot was
85
+ * deleted (the backend destroy returns nothing); it becomes `'OK'` once the destroy returns the
86
+ * bot, as in the other routes. Do not read the result as success or failure. An unknown id
87
+ * answers 500.
88
+ * @permissions bots.view OR bots.destroy
89
+ */
90
+ deleteById(id: string, headers?: Record<string, string>): Promise<'OK' | false> {
91
+ return this.client.delete<'OK' | false>(`${this.basePath}/${id}`, headers)
92
+ }
93
+
94
+ /**
95
+ * Lists the failed steps of the bot runs, newest first by default. An unknown bot answers an
96
+ * empty page.
97
+ * @permissions bots.view
98
+ */
99
+ getErrors(
100
+ id: string,
101
+ query?: BotErrorsQuery,
102
+ headers?: Record<string, string>,
103
+ ): Promise<Paginated<BotHistory>> {
104
+ return this.client.get<Paginated<BotHistory>>(
105
+ `${this.basePath}/${id}/errors${this.toQueryString(query)}`,
106
+ headers,
107
+ )
108
+ }
109
+
110
+ /**
111
+ * Fires the `API_SIGNAL` trigger of the bot for the contact, with an optional `flag` (read by
112
+ * the `api_signal_flag` condition). Asynchronous: always resolves with no content, and the
113
+ * worker only runs it when the contact has an open ticket.
114
+ * @permissions bots.view
115
+ */
116
+ triggerSignal(
117
+ botId: string,
118
+ contactId: string,
119
+ flag?: string,
120
+ headers?: Record<string, string>,
121
+ ): Promise<void> {
122
+ return this.client.post<void, { flag: string } | undefined>(
123
+ `${this.basePath}/${botId}/trigger-signal/${contactId}`,
124
+ flag === undefined ? undefined : { flag },
125
+ headers,
126
+ )
127
+ }
128
+
129
+ /**
130
+ * Answers a pending asynchronous `HTTP_REQUEST` action: `body` becomes the response the bot
131
+ * reads. Resolves with no content. An unknown history answers 404; a history that is not
132
+ * `PENDING`, or of another bot, answers 400. JSON bodies only (the route also takes text, XML
133
+ * and CSV), up to 250 KB.
134
+ * @permissions bots.view
135
+ */
136
+ requestCallback(
137
+ id: string,
138
+ pendingRequestId: string,
139
+ body: unknown,
140
+ headers?: Record<string, string>,
141
+ ): Promise<void> {
142
+ return this.client.post<void, unknown>(
143
+ `${this.basePath}/${id}/request-callback/${pendingRequestId}`,
144
+ body,
145
+ headers,
146
+ )
147
+ }
148
+
149
+ /**
150
+ * Generates a prompt for an AI agent of the bot. COSTS one AI agent credit of the account and
151
+ * calls OpenAI. No permission check: any authenticated user. A missing field answers 400; an
152
+ * option outside the lists, or the AI agent limit of the account reached
153
+ * (`Agent limit reached`), answers 500.
154
+ */
155
+ suggestAgentPrompt(
156
+ body: SuggestAgentPromptPayload,
157
+ headers?: Record<string, string>,
158
+ ): Promise<string> {
159
+ return this.client.post<string, SuggestAgentPromptPayload>(
160
+ `${this.basePath}/suggest-agent-prompt`,
161
+ body,
162
+ headers,
163
+ )
8
164
  }
9
165
  }
@@ -1,4 +1,5 @@
1
1
  import type { BotVersion } from '../botVersions/types'
2
+ import type { Contact } from '../contacts/types'
2
3
  import type { Service } from '../services/types'
3
4
 
4
5
  // ─── Settings ─────────────────────────────────────────────────────────────────
@@ -35,6 +36,10 @@ export type BotEvent =
35
36
  | 'CONTACT_RECONNECTED'
36
37
  | 'API_SIGNAL'
37
38
  | 'ANONYMOUS_USER_CREATED_WEBCHAT'
39
+ /** Fired by the worker in `@EVERY` when the contact stops answering the bot. */
40
+ | 'BOT_INACTIVE'
41
+ /** Fired by the worker when an asynchronous `HTTP_REQUEST` action gets its callback. */
42
+ | 'HTTP_REQUEST_CALLBACK'
38
43
 
39
44
  export type BotFlowTriggerNode = {
40
45
  id: string
@@ -69,8 +74,19 @@ export type BotFlowEdge = {
69
74
  sourceHandle: string
70
75
  }
71
76
 
72
- /** Visual flow graph used by the flow builder UI. Gets compiled into `contexts` on save. */
77
+ /** Visual flow graph used by the flow builder UI, as the API answers it. */
73
78
  export type BotFlowJson = {
79
+ nodes: BotFlowNode[]
80
+ /** Absent in a bot saved without a flow (`{ nodes: [] }`). */
81
+ edges?: BotFlowEdge[]
82
+ }
83
+
84
+ /**
85
+ * The flow graph to save. `edges` is required: a bot saved without it (or without `flowJson`)
86
+ * never sends a message — the worker fails reading `flowJson.edges` (SD-2323). Send at least
87
+ * `{ nodes: [], edges: [] }`.
88
+ */
89
+ export type BotFlowJsonInput = {
74
90
  nodes: BotFlowNode[]
75
91
  edges: BotFlowEdge[]
76
92
  }
@@ -108,7 +124,7 @@ export type BotActionDataMap = {
108
124
  actions?: { title: string; value: string }[]
109
125
  }
110
126
  SEND_TERM: {
111
- /** Acceptance term UUID. */
127
+ /** Acceptance term UUID (as stored); see `BotActionInput` for how to send it. */
112
128
  acceptanceTerms?: string
113
129
  }
114
130
  CONFIRM_TERM: {
@@ -170,14 +186,21 @@ export type BotActionDataMap = {
170
186
  maxAttempts?: number
171
187
  /** Actions to take based on AI agent outcomes. */
172
188
  actions?: { context?: string; action: { id: string; type: string } }[]
189
+ /** Knowledge base subject UUIDs the agent answers from. */
190
+ knowledgeBase?: string[]
191
+ /** Waits `waitSeconds` to group the contact's messages before answering. */
192
+ messageGrouping?: { enabled?: boolean; waitSeconds?: number }
173
193
  }
174
194
  HTTP_REQUEST: {
175
195
  requestName?: string
176
196
  endpointUrl?: string
177
197
  httpMethod?: 'get' | 'post' | 'put' | 'patch' | 'delete'
178
198
  isAsyncRequest?: boolean
199
+ /** Sends the Digisac payload (contact, ticket, message) along with the request. */
200
+ sendDigisacPayload?: boolean
179
201
  bodyType?: 'json' | 'xml' | 'formData' | 'empty'
180
- headers?: { key: string; value: string }[]
202
+ /** A `secret` header comes back from the API with `value: null`. */
203
+ headers?: { key: string; value: string | null; secret?: boolean }[]
181
204
  requestBodyFormData?: { key: string; value: string }[]
182
205
  requestBodyJson?: string
183
206
  requestBodyXml?: string
@@ -248,40 +271,269 @@ export type BotContexts = {
248
271
  [contextId: string]: BotContext
249
272
  }
250
273
 
274
+ // ─── Contexts as the /bots routes take and return them ───────────────────────
275
+ //
276
+ // `BotContexts` above is the stored form (a map by context id), served as is by `/bot-versions`
277
+ // and `currentBotVersion`. The `/bots` routes take the contexts as a LIST instead and answer the
278
+ // list again, with each trigger, variable, operator and action described by its option object.
279
+
280
+ /** A variable, operator or action option as the bot builder describes it. */
281
+ export type BotOption<TValue extends string = string> = { value: TValue; name?: string }
282
+
283
+ export type BotConditionTarget =
284
+ | string
285
+ | number
286
+ | string[]
287
+ | { id: string }
288
+ | { id: string }[]
289
+ | { value: string }
290
+ | { value: string }[]
291
+ | { variableName: string; variableValue: string }
292
+
293
+ /** A condition is dropped in silence when `variable`, `operator` or a truthy `target` is missing. */
294
+ export type BotConditionInput = {
295
+ variable: BotOption
296
+ operator: BotOption
297
+ target: BotConditionTarget
298
+ }
299
+
300
+ export type BotConditionGroupInput = {
301
+ conditionType: 'and' | 'or'
302
+ conditions: BotConditionInput[]
303
+ }
304
+
305
+ /** Actions the API saves. `SET_VAR` runs in the worker, but saving it answers 500. */
306
+ export type BotSavableActionType = Exclude<BotActionType, 'SET_VAR'>
307
+
308
+ export type BotActionInput = {
309
+ [K in BotSavableActionType]: {
310
+ type: BotOption<K>
311
+ /** Related records go as their id, except the ones below. */
312
+ data: K extends 'SEND_MESSAGE'
313
+ ? Omit<BotActionDataMap['SEND_MESSAGE'], 'file'> & {
314
+ /**
315
+ * The file goes as an object: a bare id is dropped. `{ fileName, mimetype, base64Url }`
316
+ * uploads a new one.
317
+ */
318
+ file?: { id: string } | { fileName: string; mimetype: string; base64Url: string }
319
+ }
320
+ : K extends 'SEND_TERM'
321
+ ? {
322
+ /**
323
+ * Send the term as `{ id }`: the bot keeps it as `data.currentDefaultTerm`, and both
324
+ * the "term in use" check of `DELETE /acceptance-terms/:id` and the reset of the
325
+ * contacts' acceptance read its `id`. A bare id is saved, but those checks miss it.
326
+ */
327
+ acceptanceTerms?: { id: string } | string
328
+ }
329
+ : BotActionDataMap[K]
330
+ }
331
+ }[BotSavableActionType]
332
+
333
+ /**
334
+ * A `SEND_MESSAGE` without text, interactive or file is dropped, and so is a rule left with no
335
+ * action (except a `BOT_INACTIVE` rule with `data`).
336
+ */
337
+ export type BotRuleInput = {
338
+ title?: string
339
+ actions: BotActionInput[]
340
+ fallbackActions?: BotActionInput[]
341
+ /** Required: a missing `conditions` answers 500. */
342
+ conditions: BotConditionInput[] | BotConditionGroupInput
343
+ data?: Record<string, unknown>
344
+ }
345
+
346
+ export type BotTriggerInput = {
347
+ trigger: { type: BotEvent }
348
+ rules: BotRuleInput[]
349
+ }
350
+
351
+ /** `@INIT`, `@EVERY` and `@FALLBACK` are the built-in contexts; other ids are user-defined. */
352
+ export type BotContextInput = {
353
+ id: string
354
+ name?: string
355
+ triggers: BotTriggerInput[]
356
+ }
357
+
358
+ export type BotParsedCondition =
359
+ | {
360
+ /** `undefined` for a variable the builder does not list. */
361
+ variable?: BotOption & { type?: string; subType?: string }
362
+ operator?: BotOption
363
+ /** Departments and tags come back as their records. */
364
+ target: unknown
365
+ }
366
+ | { $and: BotParsedCondition[] }
367
+ | { $or: BotParsedCondition[] }
368
+
369
+ export type BotParsedAction = {
370
+ type: { value: BotSavableActionType; name: string }
371
+ /** The ids of questions, terms, tags, departments, users etc. come back as their records. */
372
+ data: Record<string, unknown>
373
+ }
374
+
375
+ export type BotParsedRule = {
376
+ title: string
377
+ actions: BotParsedAction[]
378
+ fallbackActions: BotParsedAction[]
379
+ conditions: BotParsedCondition[]
380
+ }
381
+
382
+ export type BotParsedTrigger = {
383
+ /** `undefined` for the worker events the builder does not list (`LEAVE_CONTEXT`, `BOT_INACTIVE`, `HTTP_REQUEST_CALLBACK`). */
384
+ trigger?: { type: BotEvent; name: string }
385
+ rules: BotParsedRule[]
386
+ }
387
+
388
+ export type BotParsedContext = {
389
+ id: string
390
+ name: string
391
+ triggers: BotParsedTrigger[]
392
+ }
393
+
251
394
  // ─── Bot ──────────────────────────────────────────────────────────────────────
252
395
 
396
+ /** Bots are hard-deleted (no `deletedAt`). */
253
397
  export type Bot = {
254
398
  id: string
255
399
  name: string
256
- data: Record<string, unknown>
257
- contexts: BotContexts
400
+ /** Rewritten on every save: the `SEND_TERM` acceptance term of the contexts, as it was sent. */
401
+ data: { currentDefaultTerm?: { id: string } | string | null } & Record<string, unknown>
402
+ /**
403
+ * The list form (see `BotParsedContext`), not the stored map. Saving it back as is loses the
404
+ * `data` of the rules and the `{{@variable}}` conditions (the list does not carry them).
405
+ */
406
+ contexts: BotParsedContext[]
258
407
  flowJson: BotFlowJson | null
259
408
  settings: BotSettings
260
409
  currentBotVersionId: string | null
261
410
  accountId: string
262
411
  createdAt: string
263
412
  updatedAt: string
264
- deletedAt: string | null
413
+ /**
414
+ * The stored map of `contexts`: a JSON string in `getById`, an object in `updateById`; absent
415
+ * in `getMany` and `create`.
416
+ */
417
+ defaultContexts?: string | BotContexts
265
418
  // relationships
266
419
  currentBotVersion?: BotVersion | null
267
420
  services?: Service[]
421
+ /** In `getById`, the first version comes with its contexts in the list form. */
422
+ botVersions?: BotVersion[]
268
423
  }
269
424
 
425
+ export type BotRelationships = 'currentBotVersion' | 'services' | 'botVersions'
426
+
427
+ /** The bot as stored (contexts in the map form), as the `bot.*` webhooks deliver it. */
428
+ export type BotRecord = Omit<
429
+ Bot,
430
+ 'contexts' | 'defaultContexts' | 'flowJson' | BotRelationships
431
+ > & {
432
+ contexts: BotContexts
433
+ /**
434
+ * Raw, unlike the API answers: `{}` for a bot saved without a flow, and the bare list of nodes
435
+ * for a bot created with `isDraft`.
436
+ */
437
+ flowJson: Partial<BotFlowJson> | BotFlowNode[] | null
438
+ }
439
+
440
+ /** What the `bot.api-signal` webhook delivers (the `triggerSignal` call), not the bot. */
441
+ export type BotApiSignalData = {
442
+ botId: string
443
+ contactId: string
444
+ flag?: string
445
+ }
446
+
447
+ /** A duplicate name answers 409, unless the account allows duplicate names. */
270
448
  export type CreateBotPayload = {
271
449
  name: string
272
- data?: Record<string, unknown>
273
- contexts?: BotContexts
274
- flowJson?: BotFlowJson
450
+ /** Required: a missing `contexts` answers 500. */
451
+ contexts: BotContextInput[]
452
+ /** Omitted, the bot never sends a message (SD-2323): send at least `{ nodes: [], edges: [] }`. */
453
+ flowJson?: BotFlowJsonInput
275
454
  settings?: BotSettings
455
+ /**
456
+ * Saves the version as a draft instead of publishing it. The bot itself still takes the draft
457
+ * contexts on create, and its `flowJson` is saved as the bare list of nodes.
458
+ */
459
+ isDraft?: boolean
460
+ /** The id of a bot of the account to duplicate: its secret HTTP headers are kept. */
461
+ id?: string
462
+ /** @deprecated Ignored: the backend rewrites `data` on every save. */
463
+ data?: Record<string, unknown>
276
464
  }
277
465
 
278
- export type BotRelationships = 'currentBotVersion' | 'services'
466
+ /** Renames the bot without touching its contexts or versions. */
467
+ export type RenameBotPayload = {
468
+ name: string
469
+ onlyUpdateBotName: true
470
+ }
279
471
 
280
- export type UpdateBotPayload = {
281
- name?: string
282
- data?: Record<string, unknown>
283
- contexts?: BotContexts
284
- flowJson?: BotFlowJson
472
+ export type SaveBotPayload = {
473
+ /** Required on update too. */
474
+ name: string
475
+ /**
476
+ * The whole flow: it replaces the published one (or the draft, with `isDraft`). An empty list
477
+ * publishes a bot with no contexts.
478
+ */
479
+ contexts: BotContextInput[]
480
+ /** Omitted or without `edges`, the bot never sends a message (SD-2323). */
481
+ flowJson?: BotFlowJsonInput
285
482
  settings?: BotSettings
483
+ /** Saves into the latest draft (or a new one) instead of publishing. */
484
+ isDraft?: boolean
485
+ /** @deprecated Ignored: the backend rewrites `data` on every save. */
486
+ data?: Record<string, unknown>
487
+ /** @deprecated Ignored: every publish points the bot to the version it saves. */
286
488
  currentBotVersionId?: string | null
287
489
  }
490
+
491
+ export type UpdateBotPayload = RenameBotPayload | SaveBotPayload
492
+
493
+ // ─── Bot errors and extra routes ─────────────────────────────────────────────
494
+
495
+ export type BotHistoryStatus = 'PENDING' | 'SUCCESS' | 'FAILED'
496
+
497
+ /** A step of a bot run, as `getErrors` lists it (always `status: 'FAILED'`). */
498
+ export type BotHistory = {
499
+ id: string
500
+ action: string
501
+ context: string
502
+ payload: Record<string, unknown>
503
+ status: BotHistoryStatus
504
+ errorCode: string | null
505
+ errorMessage: string | null
506
+ createdAt: string
507
+ updatedAt: string
508
+ botId: string
509
+ botSessionId: string
510
+ accountId: string
511
+ contactId: string
512
+ contact?: Contact & { service?: Service }
513
+ }
514
+
515
+ export type BotErrorsQuery = {
516
+ page?: number
517
+ /** Defaults to 15, with no upper limit. */
518
+ perPage?: number
519
+ /** A column of the history, or `serviceName` for the connection of the contact. Defaults to `createdAt`. */
520
+ sort?: string
521
+ order?: 'ASC' | 'DESC'
522
+ errorCode?: string
523
+ serviceId?: string
524
+ /** Matches part of the action name. */
525
+ search?: string
526
+ /** ISO date. */
527
+ startDate?: string
528
+ /** ISO date. */
529
+ endDate?: string
530
+ }
531
+
532
+ export type SuggestAgentPromptPayload = {
533
+ voiceTone: 'formal' | 'neutral' | 'informal'
534
+ languageType: 'simple' | 'neutral' | 'technical'
535
+ function: 'triage' | 'sales' | 'answer-questions' | 'support'
536
+ companySegment: string
537
+ companySubject: string
538
+ companyServices: string
539
+ }