@channelhub/widget 0.1.11 → 0.1.13

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/src/api.ts CHANGED
@@ -1,4 +1,39 @@
1
- import type { ChannelHubAgent, Connection, Conversation, Message, MessageAttachment, Page } from './types.js';
1
+ import type { CannedResponse, ChannelHubAgent, ChannelHubTenantSettings, Connection, Conversation, Message, MessageAttachment, Page } from './types.js';
2
+
3
+ export const DEFAULT_TENANT_SETTINGS: ChannelHubTenantSettings = {
4
+ ai: {
5
+ mode: 'off',
6
+ tone: 'friendly',
7
+ debounceSeconds: 5,
8
+ autoPauseOnAgentAssign: true,
9
+ autoPauseOnAgentReply: true,
10
+ handoffOnPhone: true,
11
+ handoffOnComplaint: true,
12
+ schedule: 'always',
13
+ businessHours: { start: '08:00', end: '18:00' },
14
+ provider: 'openai',
15
+ webhookUrl: '',
16
+ webhookSecret: '',
17
+ apiKey: '',
18
+ model: 'gpt-4o-mini',
19
+ systemPrompt: '',
20
+ parameters: {},
21
+ },
22
+ inbox: {
23
+ autoAssignOnFirstReply: true,
24
+ soundNotification: true,
25
+ quickReplies: [
26
+ 'Cảm ơn bạn đã liên hệ 🙏',
27
+ 'Mình sẽ kiểm tra ngay',
28
+ 'Vui lòng chờ 1-2 phút',
29
+ ],
30
+ welcomeMessageEnabled: false,
31
+ welcomeMessageText: 'Xin chào! Cảm ơn bạn đã nhắn tin cho cửa hàng. Nhân viên sẽ phản hồi ngay trong ít phút.',
32
+ awayMessageEnabled: false,
33
+ awayMessageText: 'Hiện cửa hàng đang ngoài giờ làm việc. Bạn vui lòng để lại Số điện thoại và yêu cầu, chúng mình sẽ liên hệ lại sớm nhất nhé!',
34
+ },
35
+ isPlatformManaged: false,
36
+ };
2
37
 
3
38
  export class ChannelHubClient {
4
39
  constructor(private readonly apiUrl: string, private readonly token: string) {}
@@ -59,11 +94,137 @@ export class ChannelHubClient {
59
94
  if (!response.ok && response.status !== 204) throw new Error(`markRead failed (${response.status})`);
60
95
  }
61
96
 
62
- listCannedResponses(search?: string): Promise<{ id: string; title: string; content: string; shortcut: string | null }[]> {
97
+ listCannedResponses(search?: string): Promise<CannedResponse[]> {
63
98
  const q = search?.trim() ? `?search=${encodeURIComponent(search)}` : '';
64
99
  return this.request(`/v1/canned-responses${q}`);
65
100
  }
66
101
 
102
+ createCannedResponse(data: { title: string; content: string; shortcut?: string }): Promise<CannedResponse> {
103
+ return this.request('/v1/canned-responses', {
104
+ method: 'POST',
105
+ body: JSON.stringify(data),
106
+ });
107
+ }
108
+
109
+ updateCannedResponse(id: string, data: { title?: string; content?: string; shortcut?: string | null }): Promise<CannedResponse> {
110
+ return this.request(`/v1/canned-responses/${encodeURIComponent(id)}`, {
111
+ method: 'PATCH',
112
+ body: JSON.stringify(data),
113
+ });
114
+ }
115
+
116
+ async deleteCannedResponse(id: string): Promise<void> {
117
+ const response = await fetch(`${this.apiUrl}/v1/canned-responses/${encodeURIComponent(id)}`, {
118
+ method: 'DELETE',
119
+ headers: { authorization: `Bearer ${this.token}` },
120
+ });
121
+ if (!response.ok && response.status !== 204) {
122
+ throw new Error(`deleteCannedResponse failed (${response.status})`);
123
+ }
124
+ }
125
+
126
+ private settingsStorageKey(): string {
127
+ return `channelhub_settings_${this.token.slice(0, 12)}`;
128
+ }
129
+
130
+ private mergeWithDefaultSettings(partial?: Partial<ChannelHubTenantSettings> | null): ChannelHubTenantSettings {
131
+ return {
132
+ ai: {
133
+ ...DEFAULT_TENANT_SETTINGS.ai,
134
+ ...(partial?.ai ?? {}),
135
+ businessHours: {
136
+ ...DEFAULT_TENANT_SETTINGS.ai.businessHours,
137
+ ...(partial?.ai?.businessHours ?? {}),
138
+ },
139
+ parameters: {
140
+ ...DEFAULT_TENANT_SETTINGS.ai.parameters,
141
+ ...(partial?.ai?.parameters ?? {}),
142
+ },
143
+ },
144
+ inbox: {
145
+ ...DEFAULT_TENANT_SETTINGS.inbox,
146
+ ...(partial?.inbox ?? {}),
147
+ quickReplies: Array.isArray(partial?.inbox?.quickReplies)
148
+ ? partial!.inbox!.quickReplies
149
+ : DEFAULT_TENANT_SETTINGS.inbox.quickReplies,
150
+ },
151
+ isPlatformManaged: Boolean(partial?.isPlatformManaged ?? DEFAULT_TENANT_SETTINGS.isPlatformManaged),
152
+ };
153
+ }
154
+
155
+ async getSettings(): Promise<ChannelHubTenantSettings> {
156
+ try {
157
+ const remote = await this.request<ChannelHubTenantSettings>('/v1/settings');
158
+ const merged = this.mergeWithDefaultSettings(remote);
159
+ try {
160
+ if (typeof localStorage !== 'undefined') {
161
+ localStorage.setItem(this.settingsStorageKey(), JSON.stringify(merged));
162
+ }
163
+ } catch {
164
+ // Ignore localStorage quota/disabled errors
165
+ }
166
+ return merged;
167
+ } catch {
168
+ try {
169
+ if (typeof localStorage !== 'undefined') {
170
+ const cached = localStorage.getItem(this.settingsStorageKey());
171
+ if (cached) return this.mergeWithDefaultSettings(JSON.parse(cached));
172
+ }
173
+ } catch {
174
+ // Ignore parse errors
175
+ }
176
+ return this.mergeWithDefaultSettings(null);
177
+ }
178
+ }
179
+
180
+ async updateSettings(patch: Partial<ChannelHubTenantSettings>): Promise<ChannelHubTenantSettings> {
181
+ try {
182
+ const updated = await this.request<ChannelHubTenantSettings>('/v1/settings', {
183
+ method: 'PUT',
184
+ body: JSON.stringify(patch),
185
+ });
186
+ const merged = this.mergeWithDefaultSettings(updated);
187
+ try {
188
+ if (typeof localStorage !== 'undefined') {
189
+ localStorage.setItem(this.settingsStorageKey(), JSON.stringify(merged));
190
+ }
191
+ } catch {
192
+ // Ignore
193
+ }
194
+ return merged;
195
+ } catch {
196
+ const current = await this.getSettings();
197
+ const merged = this.mergeWithDefaultSettings({
198
+ ...current,
199
+ ...patch,
200
+ ai: {
201
+ ...current.ai,
202
+ ...(patch.ai ?? {}),
203
+ businessHours: {
204
+ ...current.ai.businessHours,
205
+ ...(patch.ai?.businessHours ?? {}),
206
+ },
207
+ parameters: {
208
+ ...current.ai.parameters,
209
+ ...(patch.ai?.parameters ?? {}),
210
+ },
211
+ },
212
+ inbox: {
213
+ ...current.inbox,
214
+ ...(patch.inbox ?? {}),
215
+ },
216
+ });
217
+ try {
218
+ if (typeof localStorage !== 'undefined') {
219
+ localStorage.setItem(this.settingsStorageKey(), JSON.stringify(merged));
220
+ }
221
+ } catch {
222
+ // Ignore
223
+ }
224
+ return merged;
225
+ }
226
+ }
227
+
67
228
  getNote(conversationId: string): Promise<{ id: string; content: string; updatedAt: string } | null> {
68
229
  return this.request(`/v1/conversations/${encodeURIComponent(conversationId)}/note`);
69
230
  }
package/src/index.ts CHANGED
@@ -4,7 +4,23 @@ console.log(`[ChannelHub] widget v${__WIDGET_VERSION__} loaded`);
4
4
  export { ChannelHubInbox } from './ChannelHubInbox.js';
5
5
  export { ChannelHubChannels } from './ChannelHubChannels.js';
6
6
  export { ChannelHubNotificationBell } from './ChannelHubNotificationBell.js';
7
- export { ChannelHubClient } from './api.js';
8
- export type { WidgetProps, WidgetTheme, Conversation, Message, ChannelHubInboxHandle, ChannelHubAgent } from './types.js';
7
+ export { ChannelHubSettings } from './ChannelHubSettings.js';
8
+ export { ChannelHubClient, DEFAULT_TENANT_SETTINGS } from './api.js';
9
+ export type {
10
+ WidgetProps,
11
+ WidgetTheme,
12
+ Conversation,
13
+ Message,
14
+ ChannelHubInboxHandle,
15
+ ChannelHubAgent,
16
+ CannedResponse,
17
+ ChannelHubAiMode,
18
+ ChannelHubAiTone,
19
+ ChannelHubAiProvider,
20
+ ChannelHubCustomParameter,
21
+ ChannelHubTenantSettings,
22
+ ChannelHubSettingsTab,
23
+ ChannelHubSettingsProps,
24
+ } from './types.js';
9
25
  export type { ChannelHubChannelsProps, ChannelConnection } from './ChannelHubChannels.js';
10
26
  export type { ChannelHubNotificationBellProps } from './ChannelHubNotificationBell.js';
package/src/types.ts CHANGED
@@ -1,14 +1,34 @@
1
1
  import type React from 'react';
2
2
 
3
- export type Provider = 'facebook' | 'instagram' | 'telegram' | 'zalo' | string;
3
+ /**
4
+ * Supported messaging channel providers in ChannelHub.
5
+ */
6
+ export type Provider = 'facebook' | 'instagram' | 'telegram' | 'zalo' | 'livechat' | 'whatsapp' | string;
4
7
 
5
8
  export type Connection = { id: string; provider: Provider; type?: string; metadata?: Record<string, unknown> };
6
9
 
10
+ /**
11
+ * Represents a staff member / support agent in the host application (CRM / POS / ERP).
12
+ * Used for conversation assignment (`assignedAgent`) and message attribution (`senderAgent`).
13
+ *
14
+ * @example
15
+ * const currentAgent: ChannelHubAgent = {
16
+ * id: 'emp_101',
17
+ * name: 'Nguyễn Văn A',
18
+ * title: 'Tư vấn viên',
19
+ * avatarUrl: 'https://example.com/avatar.png',
20
+ * };
21
+ */
7
22
  export interface ChannelHubAgent {
23
+ /** Unique staff ID from the host platform/CRM */
8
24
  id: string;
25
+ /** Display name shown on conversation badges and message bubbles */
9
26
  name: string;
27
+ /** Optional avatar URL */
10
28
  avatarUrl?: string;
29
+ /** Optional role/title (e.g., "Sale", "CSKH", "Lễ tân") */
11
30
  title?: string;
31
+ /** Optional custom metadata from host platform */
12
32
  metadata?: Record<string, unknown>;
13
33
  }
14
34
 
@@ -65,13 +85,14 @@ export type ChannelHubInboxHandle = {
65
85
  refresh: () => void;
66
86
  };
67
87
 
68
- // ─── Extension System ────────────────────────────────────────────────────────
88
+ // ─── Extension System (CRM / ERP / Host App Integration) ─────────────────────
69
89
 
70
90
  export interface ExtensionContact {
71
91
  id: string;
72
92
  name?: string;
73
93
  pictureUrl?: string;
74
94
  providerUserId: string;
95
+ /** External CRM customer ID linked via `ctx.linkContact(externalId)` */
75
96
  externalId?: string;
76
97
  }
77
98
 
@@ -80,8 +101,11 @@ export interface ExtensionContext {
80
101
  contact: ExtensionContact;
81
102
  provider?: Provider;
82
103
  recentMessages?: Message[];
104
+ /** Link or unlink this chat contact with an external CRM customer ID */
83
105
  linkContact: (externalId: string | null) => Promise<void>;
106
+ /** Trigger re-fetching of `contactInfoRows` across all registered extensions */
84
107
  refreshContactInfo: () => void;
108
+ /** Programmatically send a message into the active conversation */
85
109
  sendMessage: (text?: string, attachments?: MessageAttachment[]) => Promise<void>;
86
110
  }
87
111
 
@@ -116,6 +140,11 @@ export interface MessageEnrichment {
116
140
  render: (match: RegExpMatchArray, ctx: ExtensionContext, message: Message) => React.ReactNode;
117
141
  }
118
142
 
143
+ /**
144
+ * Extension hook interface allowing host platforms (CRM, POS, Clinic, E-commerce)
145
+ * to inject custom customer data rows, sidebar CTA buttons, composer toolbar actions,
146
+ * and inline message regex enrichments into `<ChannelHubInbox />`.
147
+ */
119
148
  export interface Extension {
120
149
  contactInfoRows?: (ctx: ExtensionContext) => Promise<ContactInfoRow[]>;
121
150
  sidebarActions?: SidebarAction[];
@@ -123,8 +152,191 @@ export interface Extension {
123
152
  messageEnrichments?: MessageEnrichment[];
124
153
  }
125
154
 
155
+ // ─── Settings, AI & Canned Responses ─────────────────────────────────────────
156
+
157
+ export interface CannedResponse {
158
+ id: string;
159
+ title: string;
160
+ content: string;
161
+ shortcut: string | null;
162
+ }
163
+
164
+ /**
165
+ * - `'off'`: AI is disabled.
166
+ * - `'copilot'`: AI suggests replies/drafts to human agents; does not auto-send.
167
+ * - `'autopilot'`: AI automatically replies when conversation is unassigned (`assignedAgent === null`).
168
+ */
169
+ export type ChannelHubAiMode = 'off' | 'copilot' | 'autopilot';
170
+ export type ChannelHubAiTone = 'friendly' | 'professional' | 'concise';
171
+ export type ChannelHubAiProvider = 'webhook' | 'openai' | 'gemini' | 'anthropic';
172
+
173
+ /**
174
+ * Schema definition for a platform-specific business parameter rendered inside `<ChannelHubSettings />`.
175
+ *
176
+ * When a SaaS Platform embeds ChannelHub for its end-merchants (tenants), the Platform can define
177
+ * domain-specific fields (e.g. `allowStockCheck`, `bookingLink`, `shippingPolicy`).
178
+ * User inputs are persisted in `settings.ai.parameters[key]` via `PUT /v1/settings` and can be
179
+ * retrieved by the Platform's AI backend via `GET /v1/settings` or `onSettingsChange`.
180
+ *
181
+ * @example
182
+ * const customParameters: ChannelHubCustomParameter[] = [
183
+ * {
184
+ * key: 'allowStockCheck',
185
+ * type: 'toggle',
186
+ * label: 'Cho phép AI tự tra cứu & báo tồn kho',
187
+ * description: 'AI tự động kiểm tra tồn kho thực tế từ POS trước khi trả lời khách',
188
+ * defaultValue: true,
189
+ * },
190
+ * {
191
+ * key: 'shippingPolicy',
192
+ * type: 'textarea',
193
+ * label: 'Chính sách giao hàng & đổi trả của shop',
194
+ * placeholder: 'VD: Freeship đơn từ 300k, đổi trả trong 7 ngày...',
195
+ * },
196
+ * ];
197
+ */
198
+ export interface ChannelHubCustomParameter {
199
+ /** Unique parameter key saved under `settings.ai.parameters[key]` */
200
+ key: string;
201
+ /** UI control type rendered in `<ChannelHubSettings />` */
202
+ type: 'toggle' | 'text' | 'textarea' | 'select';
203
+ /** Human-readable label shown to the shop owner / admin */
204
+ label: string;
205
+ /** Optional helper text explaining what this parameter controls */
206
+ description?: string;
207
+ /** Placeholder text for `'text'` and `'textarea'` inputs */
208
+ placeholder?: string;
209
+ /** Default value applied if the tenant has not configured this parameter yet */
210
+ defaultValue?: string | boolean;
211
+ /** Dropdown options when `type === 'select'` */
212
+ options?: { label: string; value: string }[];
213
+ }
214
+
215
+ /**
216
+ * Tenant-level configuration stored in `tenants.settings` (JSONB) and returned by `GET /v1/settings`.
217
+ */
218
+ export interface ChannelHubTenantSettings {
219
+ ai: {
220
+ mode: ChannelHubAiMode;
221
+ tone: ChannelHubAiTone;
222
+ /** Seconds to wait and batch consecutive customer messages before triggering AI (default: 5) */
223
+ debounceSeconds: number;
224
+ /** Automatically stop AI autopilot when a staff member claims/is assigned to the conversation */
225
+ autoPauseOnAgentAssign: boolean;
226
+ /** Automatically stop AI autopilot when a staff member manually sends a message */
227
+ autoPauseOnAgentReply: boolean;
228
+ /** Hand off to human staff when customer leaves a phone number */
229
+ handoffOnPhone: boolean;
230
+ /** Hand off to human staff when customer complains or asks for a human */
231
+ handoffOnComplaint: boolean;
232
+ schedule: 'always' | 'outside_hours';
233
+ businessHours: { start: string; end: string };
234
+ provider: ChannelHubAiProvider;
235
+ webhookUrl?: string;
236
+ webhookSecret?: string;
237
+ apiKey?: string;
238
+ model?: string;
239
+ systemPrompt?: string;
240
+ /**
241
+ * Key-value map of custom business parameters defined by `customParameters`
242
+ * (e.g. `{ allowStockCheck: true, shippingPolicy: "Freeship > 300k" }`).
243
+ */
244
+ parameters: Record<string, string | boolean>;
245
+ };
246
+ inbox: {
247
+ /** Automatically assign an unassigned conversation to the first agent who replies */
248
+ autoAssignOnFirstReply: boolean;
249
+ /** Play notification sound on new inbound messages */
250
+ soundNotification: boolean;
251
+ /** Quick reply chips shown above the message composer */
252
+ quickReplies: string[];
253
+ welcomeMessageEnabled: boolean;
254
+ welcomeMessageText: string;
255
+ awayMessageEnabled: boolean;
256
+ awayMessageText: string;
257
+ };
258
+ /**
259
+ * `true` when the tenant belongs to a parent SaaS Platform (`tenants.platform_id != null`).
260
+ * When `true` (or when `hideTechnicalAiConfig` is passed), technical AI connection settings
261
+ * (API Keys, Model names, Webhook URLs) are hidden from end-user merchants.
262
+ */
263
+ isPlatformManaged?: boolean;
264
+ }
265
+
266
+ export type ChannelHubSettingsTab = 'ai' | 'templates' | 'inbox' | 'channels';
267
+
268
+ /**
269
+ * Props for `<ChannelHubSettings />`.
270
+ *
271
+ * Supports two integration modes:
272
+ * 1. **Standalone Shop Mode (Direct Tenant)**: Omit `hideTechnicalAiConfig`. The shop can configure
273
+ * its own OpenAI/Gemini/Claude API Key, System Prompt, or External Webhook URL, plus Canned Responses.
274
+ * 2. **B2B2B Platform Mode (SaaS Host App)**: Set `hideTechnicalAiConfig={true}` and pass `customParameters`
275
+ * and `starterTemplates`. Technical AI fields are hidden, and the shop only sees easy business toggles/inputs.
276
+ *
277
+ * @example
278
+ * // Platform-Managed Mode example:
279
+ * <ChannelHubSettings
280
+ * apiUrl="https://api.channelhub.io.vn"
281
+ * token={tenantToken}
282
+ * hideTechnicalAiConfig={true}
283
+ * customParameters={[
284
+ * { key: 'autoCheckStock', type: 'toggle', label: 'Tự động báo tồn kho', defaultValue: true },
285
+ * { key: 'promoText', type: 'text', label: 'Khuyến mãi đang chạy' },
286
+ * ]}
287
+ * onSettingsChange={(updated) => console.log('Saved parameters:', updated.ai.parameters)}
288
+ * />
289
+ */
290
+ export interface ChannelHubSettingsProps {
291
+ apiUrl: string;
292
+ token: string;
293
+ theme?: WidgetTheme;
294
+ /** Initial active tab (default: `'ai'`) */
295
+ initialTab?: ChannelHubSettingsTab;
296
+ /** Visible tabs (default: `['ai', 'templates', 'inbox']`; add `'channels'` to embed channel connection manager) */
297
+ tabs?: ChannelHubSettingsTab[];
298
+ /**
299
+ * Hide technical AI connection fields (API Key / Model / Webhook URL).
300
+ * Recommended when a SaaS Platform manages the AI backend centrally for its tenants.
301
+ */
302
+ hideTechnicalAiConfig?: boolean;
303
+ /**
304
+ * Custom business parameters injected by the SaaS Platform into the AI settings tab.
305
+ * Values are persisted in `settings.ai.parameters` (`GET / PUT /v1/settings`).
306
+ */
307
+ customParameters?: ChannelHubCustomParameter[];
308
+ /**
309
+ * Industry-specific starter canned responses offered when a shop has 0 templates.
310
+ */
311
+ starterTemplates?: { title: string; content: string; shortcut?: string }[];
312
+ /** Callback fired whenever settings are saved via `PUT /v1/settings` */
313
+ onSettingsChange?: (settings: ChannelHubTenantSettings) => void;
314
+ /** Optional close handler when rendered inside a modal/drawer */
315
+ onClose?: () => void;
316
+ }
317
+
126
318
  // ─────────────────────────────────────────────────────────────────────────────
127
319
 
320
+ /**
321
+ * Props for `<ChannelHubInbox />` — the main omnichannel messaging inbox widget.
322
+ *
323
+ * @example
324
+ * <ChannelHubInbox
325
+ * apiUrl="https://api.channelhub.io.vn"
326
+ * token={tenantToken}
327
+ * currentAgent={{ id: 'emp_1', name: 'Nguyễn Văn A', title: 'CSKH' }}
328
+ * teamAgents={[
329
+ * { id: 'emp_1', name: 'Nguyễn Văn A', title: 'CSKH' },
330
+ * { id: 'emp_2', name: 'Trần Thị B', title: 'Sale' },
331
+ * ]}
332
+ * settingsConfig={{
333
+ * hideTechnicalAiConfig: true,
334
+ * customParameters: [
335
+ * { key: 'allowStockCheck', type: 'toggle', label: 'Cho phép AI báo tồn kho', defaultValue: true },
336
+ * ],
337
+ * }}
338
+ * />
339
+ */
128
340
  export type WidgetProps = {
129
341
  apiUrl: string;
130
342
  token: string;
@@ -134,9 +346,18 @@ export type WidgetProps = {
134
346
  disableAttachments?: boolean;
135
347
  disableNotificationSound?: boolean;
136
348
  hideKeyboardHint?: boolean;
349
+ /** Hide the top-left `⚙️` Settings button in the inbox sidebar header */
350
+ hideSettingsButton?: boolean;
351
+ /**
352
+ * Configuration forwarded to the built-in `<ChannelHubSettings />` modal
353
+ * when opened from the inbox `⚙️` button or `+ Quản lý mẫu câu` action.
354
+ */
355
+ settingsConfig?: Pick<ChannelHubSettingsProps, 'tabs' | 'hideTechnicalAiConfig' | 'customParameters' | 'starterTemplates'>;
137
356
  locale?: 'vi' | 'en';
138
357
  extensions?: Extension[];
358
+ /** Currently logged-in staff member (used for "+ Nhận phụ trách" and outbound message sender attribution) */
139
359
  currentAgent?: ChannelHubAgent | null;
360
+ /** List of team members available in the conversation assignment dropdown */
140
361
  teamAgents?: ChannelHubAgent[];
141
362
  onNewMessage?: (conversationId: string) => void;
142
363
  onConversationSelect?: (conversationId: string) => void;