@reglow/reglow 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/reglow/common/errors.d.ts +1 -0
  2. package/dist/reglow/common/errors.js +1 -0
  3. package/dist/reglow/common/errors.js.map +1 -1
  4. package/dist/reglow/core/config.js +1 -1
  5. package/dist/reglow/core/entities.d.ts +20 -0
  6. package/dist/reglow/core/models.d.ts +2 -0
  7. package/dist/reglow/core/models.js +1 -0
  8. package/dist/reglow/core/models.js.map +1 -1
  9. package/dist/reglow/modules/customer_service/controller.js +48 -0
  10. package/dist/reglow/modules/customer_service/controller.js.map +1 -1
  11. package/dist/reglow/modules/customer_service/repository.d.ts +2 -0
  12. package/dist/reglow/modules/customer_service/repository.js +19 -0
  13. package/dist/reglow/modules/customer_service/repository.js.map +1 -1
  14. package/dist/reglow/modules/customer_service/schema.d.ts +20 -0
  15. package/dist/reglow/modules/customer_service/schema.js +21 -0
  16. package/dist/reglow/modules/customer_service/schema.js.map +1 -1
  17. package/dist/reglow/modules/customer_service/sdk_template.html +1588 -223
  18. package/dist/reglow/modules/customer_service/service.d.ts +33 -0
  19. package/dist/reglow/modules/customer_service/service.js +223 -1
  20. package/dist/reglow/modules/customer_service/service.js.map +1 -1
  21. package/dist/reglow/modules/region/controller.d.ts +6 -0
  22. package/dist/reglow/modules/region/controller.js +77 -0
  23. package/dist/reglow/modules/region/controller.js.map +1 -0
  24. package/dist/reglow/modules/region/controller_admin.d.ts +6 -0
  25. package/dist/reglow/modules/region/controller_admin.js +126 -0
  26. package/dist/reglow/modules/region/controller_admin.js.map +1 -0
  27. package/dist/reglow/modules/region/data/pcas.json +1 -0
  28. package/dist/reglow/modules/region/model.d.ts +22 -0
  29. package/dist/reglow/modules/region/model.js +9 -0
  30. package/dist/reglow/modules/region/model.js.map +1 -0
  31. package/dist/reglow/modules/region/repository.d.ts +22 -0
  32. package/dist/reglow/modules/region/repository.js +75 -0
  33. package/dist/reglow/modules/region/repository.js.map +1 -0
  34. package/dist/reglow/modules/region/router.d.ts +16 -0
  35. package/dist/reglow/modules/region/router.js +11 -0
  36. package/dist/reglow/modules/region/router.js.map +1 -0
  37. package/dist/reglow/modules/region/schema.d.ts +38 -0
  38. package/dist/reglow/modules/region/schema.js +33 -0
  39. package/dist/reglow/modules/region/schema.js.map +1 -0
  40. package/dist/reglow/modules/region/seed.d.ts +2 -0
  41. package/dist/reglow/modules/region/seed.js +101 -0
  42. package/dist/reglow/modules/region/seed.js.map +1 -0
  43. package/dist/reglow/modules/region/service.d.ts +28 -0
  44. package/dist/reglow/modules/region/service.js +88 -0
  45. package/dist/reglow/modules/region/service.js.map +1 -0
  46. package/dist/reglow/modules/user/controller.js +31 -6
  47. package/dist/reglow/modules/user/controller.js.map +1 -1
  48. package/dist/reglow/modules/user/controller_client.js +2 -0
  49. package/dist/reglow/modules/user/controller_client.js.map +1 -1
  50. package/dist/reglow/modules/user/repository.d.ts +2 -0
  51. package/dist/reglow/modules/user/repository.js +11 -0
  52. package/dist/reglow/modules/user/repository.js.map +1 -1
  53. package/dist/reglow/modules/user/schema.d.ts +21 -0
  54. package/dist/reglow/modules/user/schema.js +20 -0
  55. package/dist/reglow/modules/user/schema.js.map +1 -1
  56. package/dist/reglow/modules/user/service.d.ts +3 -1
  57. package/dist/reglow/modules/user/service.js +43 -0
  58. package/dist/reglow/modules/user/service.js.map +1 -1
  59. package/dist/reglow/scripts/init-data.js +131 -59
  60. package/dist/reglow/scripts/init-data.js.map +1 -1
  61. package/dist/reglow/scripts/schema.js +29 -0
  62. package/dist/reglow/scripts/schema.js.map +1 -1
  63. package/package.json +2 -2
@@ -36,6 +36,11 @@ export declare class CSService {
36
36
  updateAgent(agentId: number, data: Record<string, unknown>): Promise<Record<string, unknown>>;
37
37
  deleteAgent(agentId: number): Promise<void>;
38
38
  setAgentEnabled(agentId: number, enabled: boolean): Promise<Record<string, unknown>>;
39
+ /**
40
+ * 为该访客创建/复用会话并自动分配在线坐席(对应 java CustomerServiceService.assignAgent)。
41
+ * 复用 _getOrCreateVisitorSession 复用/新建会话、_pickAgent 做在线坐席分配(最少会话优先)。
42
+ */
43
+ assignAgent(configId: number, visitorId: string): Promise<Record<string, unknown>>;
39
44
  agentSetOnline(agentId: number, online: boolean): Promise<void>;
40
45
  agentPing(agentId: number): Promise<void>;
41
46
  requireAgentByEmployee(employeeId: number): Promise<CSAgent>;
@@ -44,6 +49,13 @@ export declare class CSService {
44
49
  _agentIsOnline(agent: CSAgent): Promise<boolean>;
45
50
  _pickAgent(csConfig: CSConfig, agentKey?: string | null): Promise<CSAgent | null>;
46
51
  requestTransfer(appId: string, sessionId?: string | null, agentKey?: string | null, visitorName?: string | null): Promise<TransferResultDto>;
52
+ /**
53
+ * 创建/复用访客会话(对应 java CustomerServiceService.createSession)。
54
+ * 校验配置存在后,复用 _getOrCreateVisitorSession 获取会话。
55
+ */
56
+ createSession(configId: number, visitorId: string, visitorName?: string | null): Promise<Record<string, unknown>>;
57
+ /** 按 visitorId 复用未结束会话,否则新建(对应 java getOrCreateSession)。 */
58
+ private _getOrCreateVisitorSession;
47
59
  agentSendReply(agentId: number, sessionId: string, content: string): Promise<Record<string, unknown>>;
48
60
  agentTakeover(agentId: number, sessionId: string): Promise<void>;
49
61
  agentClose(agentId: number, sessionId: string, summary?: string | null): Promise<void>;
@@ -73,6 +85,17 @@ export declare class CSService {
73
85
  score: number;
74
86
  kb_id: number;
75
87
  }>>;
88
+ /**
89
+ * 检索配置关联知识库(对应 java CustomerServiceService.searchRelevantChunks)。
90
+ * 复用 searchKnowledge:先解析配置绑定的知识库 id,再执行向量检索。
91
+ */
92
+ searchRelevantChunks(configId: number, query: string, topK?: number): Promise<Array<{
93
+ chunk_id: number;
94
+ title: string;
95
+ content: string;
96
+ score: number;
97
+ kb_id: number;
98
+ }>>;
76
99
  _getLlmConfig(csConfig: CSConfig): Promise<[string, string, string]>;
77
100
  chatStream(appId: string, sessionId?: string | null, message?: string | null, imageUrl?: string | null, visitorName?: string | null): AsyncGenerator<string, void, unknown>;
78
101
  _forwardToAgent(session: CSSession, msgContent: string, contentType: string): Promise<void>;
@@ -88,5 +111,15 @@ export declare class CSService {
88
111
  _resolveSessionAppNames(sessions: Record<string, unknown>[], rawSessions: CSSession[]): Promise<Record<string, unknown>[]>;
89
112
  listMessages(sessionId: string, employee?: Employee | null): Promise<Record<string, unknown>[]>;
90
113
  _sessionVisible(session: CSSession, employee: Employee): Promise<boolean>;
114
+ /**
115
+ * 客户端 SDK 公开配置(含常见问题列表)。每个客服配置独立返回。
116
+ * 对应 backend-python 的 get_sdk_public_config
117
+ */
118
+ getSdkPublicConfig(appId: string): Promise<Record<string, unknown>>;
119
+ /**
120
+ * 提取配置关联知识库中的常见问题列表 [{id, title, content}]
121
+ * 对应 backend-python 的 _list_config_faqs
122
+ */
123
+ listConfigFaqs(configId: number, limit?: number): Promise<Array<Record<string, unknown>>>;
91
124
  generateSdkScript(appId: string): Promise<string>;
92
125
  }
@@ -229,6 +229,16 @@ function toConfigDto(c) {
229
229
  business_hours: fromJson(c.business_hours),
230
230
  agent_mode: c.agent_mode ?? null,
231
231
  agent_ids: fromJson(c.agent_ids),
232
+ qr_code_title: c.qr_code_title ?? null,
233
+ qr_code_desc: c.qr_code_desc ?? null,
234
+ qr_code_url: c.qr_code_url ?? null,
235
+ contact_phone: c.contact_phone ?? null,
236
+ contact_email: c.contact_email ?? null,
237
+ contact_online_url: c.contact_online_url ?? null,
238
+ contact_address: c.contact_address ?? null,
239
+ faq_enabled: c.faq_enabled ?? 1,
240
+ faq_title: c.faq_title ?? null,
241
+ primary_color: c.primary_color ?? null,
232
242
  is_active: c.is_active ?? 1,
233
243
  created_at: c.created_at ?? null,
234
244
  updated_at: c.updated_at ?? null,
@@ -360,6 +370,17 @@ export class CSService {
360
370
  business_hours: toJson(data.business_hours ?? null),
361
371
  agent_mode: data.agent_mode || "pool",
362
372
  agent_ids: toJson(data.agent_ids ?? null),
373
+ // SDK 展示配置
374
+ qr_code_title: data.qr_code_title ?? null,
375
+ qr_code_desc: data.qr_code_desc ?? null,
376
+ qr_code_url: data.qr_code_url ?? null,
377
+ contact_phone: data.contact_phone ?? null,
378
+ contact_email: data.contact_email ?? null,
379
+ contact_online_url: data.contact_online_url ?? null,
380
+ contact_address: data.contact_address ?? null,
381
+ faq_enabled: data.faq_enabled ?? 1,
382
+ faq_title: data.faq_title ?? null,
383
+ primary_color: data.primary_color ?? null,
363
384
  is_active: data.is_active ?? 1,
364
385
  creator_id: creatorId ?? null,
365
386
  });
@@ -380,6 +401,15 @@ export class CSService {
380
401
  "embedding_provider",
381
402
  "embedding_model",
382
403
  "agent_mode",
404
+ "qr_code_title",
405
+ "qr_code_desc",
406
+ "qr_code_url",
407
+ "contact_phone",
408
+ "contact_email",
409
+ "contact_online_url",
410
+ "contact_address",
411
+ "faq_title",
412
+ "primary_color",
383
413
  ];
384
414
  for (const f of textFields) {
385
415
  const v = data[f];
@@ -392,6 +422,9 @@ export class CSService {
392
422
  if (data.agent_ids !== undefined && data.agent_ids !== null) {
393
423
  updateData.agent_ids = toJson(data.agent_ids);
394
424
  }
425
+ if (data.faq_enabled !== undefined && data.faq_enabled !== null) {
426
+ updateData.faq_enabled = data.faq_enabled;
427
+ }
395
428
  if (data.is_active !== undefined && data.is_active !== null) {
396
429
  updateData.is_active = data.is_active;
397
430
  }
@@ -585,6 +618,57 @@ export class CSService {
585
618
  });
586
619
  return toAgentDto(updated);
587
620
  }
621
+ /**
622
+ * 为该访客创建/复用会话并自动分配在线坐席(对应 java CustomerServiceService.assignAgent)。
623
+ * 复用 _getOrCreateVisitorSession 复用/新建会话、_pickAgent 做在线坐席分配(最少会话优先)。
624
+ */
625
+ async assignAgent(configId, visitorId) {
626
+ const config = await this.repo.findConfigById(configId);
627
+ if (!config)
628
+ throw new AppException(ErrorCode.CS_CONFIG_NOT_FOUND, "客服配置不存在", 404);
629
+ let session = await this._getOrCreateVisitorSession(config, visitorId, "访客");
630
+ // 已在人工服务中(已分配坐席)则直接返回
631
+ if (session.status === 1 && session.agent_id != null) {
632
+ return (await this._resolveSessionAgentNames([session]))[0];
633
+ }
634
+ // 标记为待人工接待,并尝试自动分配在线坐席
635
+ await this.repo.updateSession(session.id, { status: 1 });
636
+ session = (await this.repo.findSessionByPk(session.id));
637
+ const agent = await this._pickAgent(config);
638
+ if (agent) {
639
+ await this.repo.updateSession(session.id, {
640
+ status: 1,
641
+ agent_id: agent.id,
642
+ last_agent_active_at: new Date(),
643
+ });
644
+ session = (await this.repo.findSessionByPk(session.id));
645
+ const history = await this.repo.listMessages(session.id, 20);
646
+ await wsManager.sendToAgent(agent.id, {
647
+ type: "session_assigned",
648
+ session_id: session.session_id,
649
+ visitor_name: session.visitor_name,
650
+ app_id: session.app_id,
651
+ history: history.map((m) => ({
652
+ role: m.role,
653
+ content: m.content,
654
+ content_type: m.content_type,
655
+ created_at: m.created_at
656
+ ? new Date(m.created_at)
657
+ .toISOString()
658
+ .slice(0, 19)
659
+ .replace("T", " ")
660
+ : null,
661
+ })),
662
+ });
663
+ await wsManager.sendToUser(session.session_id, {
664
+ type: "agent_online",
665
+ agent_id: agent.id,
666
+ agent_name: agent.display_name,
667
+ agent_avatar: agent.avatar,
668
+ });
669
+ }
670
+ return (await this._resolveSessionAgentNames([session]))[0];
671
+ }
588
672
  async agentSetOnline(agentId, online) {
589
673
  const store = getRedisStore();
590
674
  if (online) {
@@ -800,6 +884,36 @@ export class CSService {
800
884
  message: notice,
801
885
  };
802
886
  }
887
+ /**
888
+ * 创建/复用访客会话(对应 java CustomerServiceService.createSession)。
889
+ * 校验配置存在后,复用 _getOrCreateVisitorSession 获取会话。
890
+ */
891
+ async createSession(configId, visitorId, visitorName) {
892
+ const config = await this.repo.findConfigById(configId);
893
+ if (!config)
894
+ throw new AppException(ErrorCode.CS_CONFIG_NOT_FOUND, "客服配置不存在", 404);
895
+ const session = await this._getOrCreateVisitorSession(config, visitorId, visitorName);
896
+ return (await this._resolveSessionAgentNames([session]))[0];
897
+ }
898
+ /** 按 visitorId 复用未结束会话,否则新建(对应 java getOrCreateSession)。 */
899
+ async _getOrCreateVisitorSession(config, visitorId, visitorName) {
900
+ const vid = (visitorId || "").trim();
901
+ if (vid) {
902
+ const existing = await this.repo.findOpenSessionByVisitorId(vid);
903
+ if (existing)
904
+ return existing;
905
+ }
906
+ const session = await this.repo.createSession({
907
+ session_id: "sess_" + tokenHex(16),
908
+ app_id: config.app_id,
909
+ visitor_id: vid || "visitor_" + tokenHex(8),
910
+ visitor_name: visitorName ?? null,
911
+ source: "h5",
912
+ status: 0,
913
+ });
914
+ await this._notifyAgentsNewSession(session);
915
+ return session;
916
+ }
803
917
  async agentSendReply(agentId, sessionId, content) {
804
918
  const session = await this.repo.findSessionBySessionId(sessionId);
805
919
  if (!session)
@@ -1131,6 +1245,18 @@ export class CSService {
1131
1245
  results.sort((a, b) => b.score - a.score);
1132
1246
  return results.slice(0, topK);
1133
1247
  }
1248
+ /**
1249
+ * 检索配置关联知识库(对应 java CustomerServiceService.searchRelevantChunks)。
1250
+ * 复用 searchKnowledge:先解析配置绑定的知识库 id,再执行向量检索。
1251
+ */
1252
+ async searchRelevantChunks(configId, query, topK = 5) {
1253
+ if (!query || !query.trim())
1254
+ return [];
1255
+ const kbIds = (await this.repo.listConfigKbs(configId)).map((kb) => kb.id);
1256
+ if (!kbIds.length)
1257
+ return [];
1258
+ return this.searchKnowledge(query, kbIds, topK);
1259
+ }
1134
1260
  // ─── 对话编排 ───
1135
1261
  async _getLlmConfig(csConfig) {
1136
1262
  const providerConfig = await getProviderConfig(csConfig.provider || "deepseek");
@@ -1601,6 +1727,85 @@ export class CSService {
1601
1727
  return false;
1602
1728
  }
1603
1729
  // ─── SDK 脚本生成 ───
1730
+ /**
1731
+ * 客户端 SDK 公开配置(含常见问题列表)。每个客服配置独立返回。
1732
+ * 对应 backend-python 的 get_sdk_public_config
1733
+ */
1734
+ async getSdkPublicConfig(appId) {
1735
+ const config = await this.repo.findConfigByAppId(appId);
1736
+ if (!config) {
1737
+ throw new AppException(ErrorCode.CS_CONFIG_NOT_FOUND, "无效的应用ID", 404);
1738
+ }
1739
+ // API Base 解析(对齐 Python):sys_config(cs_api_base) > CDN_DOMAIN > ""
1740
+ const row = (await knex(ModelRegistry.get("SysConfig"))
1741
+ .where("key", "cs_api_base")
1742
+ .select("value")
1743
+ .first());
1744
+ let apiBase = (row?.value || "").trim().replace(/\/+$/, "");
1745
+ if (!apiBase) {
1746
+ apiBase = (settings.CDN_DOMAIN || "").replace(/\/+$/, "");
1747
+ }
1748
+ // 常见问题:从配置关联的知识库中提取(优先 source_type=faq,否则取有标题的知识块)
1749
+ const faqs = await this.listConfigFaqs(config.id, 50);
1750
+ const qr = {};
1751
+ if (config.qr_code_url) {
1752
+ qr.title = config.qr_code_title || "扫码加入";
1753
+ qr.desc = config.qr_code_desc || "";
1754
+ qr.url = config.qr_code_url;
1755
+ }
1756
+ const businessHours = fromJson(config.business_hours) || null;
1757
+ const contact = {
1758
+ phone: config.contact_phone || "",
1759
+ email: config.contact_email || "",
1760
+ online_url: config.contact_online_url || "",
1761
+ address: config.contact_address || "",
1762
+ business_hours: businessHours,
1763
+ };
1764
+ return {
1765
+ app_id: config.app_id,
1766
+ app_name: config.app_name,
1767
+ welcome_message: config.welcome_message || "您好,有什么可以帮您的吗?",
1768
+ api_base: apiBase,
1769
+ primary_color: config.primary_color || "",
1770
+ qr_code: qr,
1771
+ contact,
1772
+ faq_enabled: config.faq_enabled !== undefined && config.faq_enabled !== null
1773
+ ? Boolean(config.faq_enabled !== 0)
1774
+ : true,
1775
+ faq_title: config.faq_title || "常见问题",
1776
+ faqs,
1777
+ };
1778
+ }
1779
+ /**
1780
+ * 提取配置关联知识库中的常见问题列表 [{id, title, content}]
1781
+ * 对应 backend-python 的 _list_config_faqs
1782
+ */
1783
+ async listConfigFaqs(configId, limit = 50) {
1784
+ const kbs = await this.repo.listConfigKbs(configId);
1785
+ if (!kbs.length)
1786
+ return [];
1787
+ const kbIds = kbs.map((kb) => kb.id);
1788
+ // 优先 faq 类型;其次有标题的知识块(常见问题面板展示)
1789
+ try {
1790
+ const rows = (await knex(ModelRegistry.get("CSKnowledgeChunk"))
1791
+ .whereIn("kb_id", kbIds)
1792
+ .whereNull("deleted_at")
1793
+ .whereNotNull("title")
1794
+ .whereNot("title", "")
1795
+ .orderByRaw("(source_type <> 'faq') asc")
1796
+ .orderBy("id", "asc")
1797
+ .limit(limit));
1798
+ return rows.map((c) => ({
1799
+ id: c.id,
1800
+ title: c.title,
1801
+ content: (c.content || "").slice(0, 2000), // 面板只展示摘要,点击后发送问题给机器人
1802
+ }));
1803
+ }
1804
+ catch (e) {
1805
+ logger.warning("查询常见问题失败 config_id=%s: %s", configId, e.message);
1806
+ return [];
1807
+ }
1808
+ }
1604
1809
  async generateSdkScript(appId) {
1605
1810
  const config = await this.repo.findConfigByAppId(appId);
1606
1811
  if (!config)
@@ -1616,12 +1821,29 @@ export class CSService {
1616
1821
  }
1617
1822
  const welcome = (config.welcome_message || "您好,有什么可以帮您的吗?").replace(/'/g, "\\'");
1618
1823
  const apiBaseJs = apiBase ? `'${apiBase}'` : "window.location.origin";
1824
+ // 注入该配置的 SDK 展示默认值(页面可用 window.CS_SDK_CONFIG 覆盖,运行时会再拉取最新配置)
1825
+ const sdkConfig = {
1826
+ qr_code_title: config.qr_code_title || "",
1827
+ qr_code_desc: config.qr_code_desc || "",
1828
+ qr_code_url: config.qr_code_url || "",
1829
+ contact_phone: config.contact_phone || "",
1830
+ contact_email: config.contact_email || "",
1831
+ contact_online_url: config.contact_online_url || "",
1832
+ contact_address: config.contact_address || "",
1833
+ faq_enabled: config.faq_enabled !== undefined && config.faq_enabled !== null
1834
+ ? Boolean(config.faq_enabled !== 0)
1835
+ : true,
1836
+ faq_title: config.faq_title || "常见问题",
1837
+ primary_color: config.primary_color || "",
1838
+ };
1839
+ const configJson = JSON.stringify(sdkConfig).replace(/'/g, "\\'");
1619
1840
  const templatePath = new URL("./sdk_template.html", import.meta.url);
1620
1841
  const template = fs.readFileSync(templatePath, "utf-8");
1621
1842
  return template
1622
1843
  .replace("{{APP_ID}}", appId)
1623
1844
  .replace("{{WELCOME}}", welcome)
1624
- .replace("{{API_BASE_JS}}", apiBaseJs);
1845
+ .replace("{{API_BASE_JS}}", apiBaseJs)
1846
+ .replace("{{CONFIG_JSON}}", configJson);
1625
1847
  }
1626
1848
  }
1627
1849
  function cosineSimilarity(a, b) {