qf46578 commited on
Commit
01cc313
·
verified ·
1 Parent(s): e194dc1

🦞 Add: backend/src/services/keyword.service.ts

Browse files
backend/src/services/keyword.service.ts ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Service } from 'typedi';
2
+ import { InjectRepository } from 'typeorm-typedi-extensions';
3
+ import { Repository } from 'typeorm';
4
+ import { KeywordRule } from '../entities/keyword-rule.entity';
5
+ import { createLogger } from '../utils/logger';
6
+
7
+ const logger = createLogger('keyword-service');
8
+
9
+ export interface KeywordCheckResult {
10
+ triggered: boolean;
11
+ action: 'transfer' | 'alert' | 'block' | 'auto_reply' | null;
12
+ matchedKeywords: string[];
13
+ transferToRoleId?: string;
14
+ transferToUserId?: string;
15
+ subAccount?: string;
16
+ autoReply?: string;
17
+ rule: KeywordRule | null;
18
+ }
19
+
20
+ @Service()
21
+ export class KeywordService {
22
+ private ruleCache: KeywordRule[] = [];
23
+ private lastCacheUpdate: number = 0;
24
+ private cacheTTL: number = 5 * 60 * 1000; // 5分钟缓存
25
+
26
+ constructor(
27
+ @InjectRepository(KeywordRule)
28
+ private ruleRepo: Repository<KeywordRule>
29
+ ) {
30
+ this.updateCache();
31
+ }
32
+
33
+ /**
34
+ * 更新缓存
35
+ */
36
+ private async updateCache(): Promise<void> {
37
+ const now = Date.now();
38
+ if (now - this.lastCacheUpdate < this.cacheTTL && this.ruleCache.length > 0) {
39
+ return;
40
+ }
41
+
42
+ this.ruleCache = await this.ruleRepo.find({
43
+ where: { isActive: true },
44
+ order: { priority: 'DESC' },
45
+ });
46
+
47
+ this.lastCacheUpdate = now;
48
+ logger.info(`Updated keyword rule cache: ${this.ruleCache.length} rules`);
49
+ }
50
+
51
+ /**
52
+ * 检查关键词
53
+ */
54
+ async checkKeywords(text: string): Promise<KeywordCheckResult> {
55
+ await this.updateCache();
56
+
57
+ const textLower = text.toLowerCase();
58
+
59
+ for (const rule of this.ruleCache) {
60
+ const matchedKeywords: string[] = [];
61
+
62
+ for (const keyword of rule.keywords) {
63
+ if (textLower.includes(keyword.toLowerCase())) {
64
+ matchedKeywords.push(keyword);
65
+ }
66
+ }
67
+
68
+ // 检查匹配模式
69
+ const isMatched =
70
+ rule.matchMode === 'all'
71
+ ? matchedKeywords.length === rule.keywords.length
72
+ : matchedKeywords.length > 0;
73
+
74
+ if (isMatched) {
75
+ // 记录触发次数
76
+ this.ruleRepo.increment({ id: rule.id }, 'triggerCount', 1);
77
+
78
+ logger.info(`Keyword rule triggered: ${rule.ruleName}`, {
79
+ matchedKeywords,
80
+ action: rule.action,
81
+ });
82
+
83
+ return {
84
+ triggered: true,
85
+ action: rule.action,
86
+ matchedKeywords,
87
+ transferToRoleId: rule.transferToRoleId || undefined,
88
+ transferToUserId: rule.transferToUserId || undefined,
89
+ subAccount: rule.subAccount || undefined,
90
+ autoReply: rule.autoReply || undefined,
91
+ rule,
92
+ };
93
+ }
94
+ }
95
+
96
+ return {
97
+ triggered: false,
98
+ action: null,
99
+ matchedKeywords: [],
100
+ rule: null,
101
+ };
102
+ }
103
+
104
+ /**
105
+ * 添加关键词规则
106
+ */
107
+ async addRule(
108
+ ruleName: string,
109
+ keywords: string[],
110
+ action: KeywordRule['action'],
111
+ options: {
112
+ transferToRoleId?: string;
113
+ transferToUserId?: string;
114
+ subAccount?: string;
115
+ autoReply?: string;
116
+ priority?: number;
117
+ matchMode?: 'any' | 'all';
118
+ description?: string;
119
+ } = {}
120
+ ): Promise<KeywordRule> {
121
+ const rule = this.ruleRepo.create({
122
+ ruleName,
123
+ keywords,
124
+ action,
125
+ transferToRoleId: options.transferToRoleId || null,
126
+ transferToUserId: options.transferToUserId || null,
127
+ subAccount: options.subAccount || null,
128
+ autoReply: options.autoReply || null,
129
+ priority: options.priority || 0,
130
+ matchMode: options.matchMode || 'any',
131
+ description: options.description || null,
132
+ isActive: true,
133
+ });
134
+
135
+ await this.ruleRepo.save(rule);
136
+ this.lastCacheUpdate = 0; // 强制刷新缓存
137
+
138
+ return rule;
139
+ }
140
+
141
+ /**
142
+ * 更新关键词规则
143
+ */
144
+ async updateRule(
145
+ id: string,
146
+ updates: Partial<{
147
+ ruleName: string;
148
+ keywords: string[];
149
+ action: KeywordRule['action'];
150
+ transferToRoleId: string;
151
+ transferToUserId: string;
152
+ subAccount: string;
153
+ autoReply: string;
154
+ priority: number;
155
+ matchMode: 'any' | 'all';
156
+ description: string;
157
+ isActive: boolean;
158
+ }>
159
+ ): Promise<KeywordRule> {
160
+ const rule = await this.ruleRepo.findOne({ where: { id } });
161
+ if (!rule) {
162
+ throw new Error(`Keyword rule ${id} not found`);
163
+ }
164
+
165
+ Object.assign(rule, updates);
166
+ await this.ruleRepo.save(rule);
167
+ this.lastCacheUpdate = 0;
168
+
169
+ return rule;
170
+ }
171
+
172
+ /**
173
+ * 删除关键词规则
174
+ */
175
+ async removeRule(id: string): Promise<boolean> {
176
+ const result = await this.ruleRepo.delete({ id });
177
+ this.lastCacheUpdate = 0;
178
+ return (result.affected || 0) > 0;
179
+ }
180
+
181
+ /**
182
+ * 获取所有规则
183
+ */
184
+ async getAllRules(): Promise<KeywordRule[]> {
185
+ return this.ruleRepo.find({
186
+ order: { priority: 'DESC', createdAt: 'DESC' },
187
+ });
188
+ }
189
+
190
+ /**
191
+ * 初始化默认规则
192
+ */
193
+ async initializeDefaultRules(): Promise<void> {
194
+ const existingCount = await this.ruleRepo.count();
195
+ if (existingCount > 0) {
196
+ return;
197
+ }
198
+
199
+ const defaultRules = [
200
+ {
201
+ ruleName: '售后转接',
202
+ keywords: ['售后', '退款', '退货', '换货', '维修', '质量问题', '坏了', '坏了'],
203
+ action: 'transfer' as const,
204
+ description: '售后相关关键词触发转接',
205
+ priority: 100,
206
+ },
207
+ {
208
+ ruleName: '投诉转接',
209
+ keywords: ['投诉', '差评', '举报', '315', '消费者协会', '工商'],
210
+ action: 'transfer' as const,
211
+ description: '投诉相关关键词触发转接',
212
+ priority: 200,
213
+ },
214
+ {
215
+ ruleName: '议价提醒',
216
+ keywords: ['便宜', '优惠', '折扣', '降价', '优惠码', '优惠券', '能少点吗'],
217
+ action: 'alert' as const,
218
+ description: '议价相关关键词触发提醒',
219
+ priority: 50,
220
+ },
221
+ {
222
+ ruleName: '发货询问自动回复',
223
+ keywords: ['发货', '什么时候发', '多久发', '今天发'],
224
+ action: 'auto_reply' as const,
225
+ autoReply: '您好,我们会在付款后24小时内安排发货,届时会有物流信息更新,请您耐心等待哦~',
226
+ priority: 30,
227
+ },
228
+ {
229
+ ruleName: '物流查询自动回复',
230
+ keywords: ['物流', '快递', '到哪了', '到哪了', '快递到哪了'],
231
+ action: 'auto_reply' as const,
232
+ autoReply: '您好,您可以在订单详情中查看物流进度。如有疑问,可以提供订单号,我们帮您查询~',
233
+ priority: 30,
234
+ },
235
+ ];
236
+
237
+ for (const rule of defaultRules) {
238
+ await this.addRule(
239
+ rule.ruleName,
240
+ rule.keywords,
241
+ rule.action,
242
+ rule
243
+ );
244
+ }
245
+
246
+ logger.info('Default keyword rules initialized');
247
+ }
248
+ }