Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 13x 13x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 28x 5x 5x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 28x 6x 6x 4x 4x 4x 1x 1x 1x 1x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 165x 32x 32x 165x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 8x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x |
/**
* Chatbot Utility Functions
*
* Provides intelligent FAQ matching and response generation
* for the customer support chatbot.
*/
import { prisma } from '@/lib/prisma';
import { SupportArticle, ChatbotResponse, ChatbotQuickAction } from '@/types/support';
import { CHATBOT } from '@/constants/support';
import { TicketCategory } from '@/types/support';
// Common words to ignore when matching (stop words)
const STOP_WORDS = new Set([
'a', 'an', 'the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for',
'of', 'with', 'by', 'from', 'as', 'is', 'was', 'are', 'were', 'been',
'be', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could',
'should', 'may', 'might', 'must', 'can', 'this', 'that', 'these', 'those',
'i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'you', 'your', 'yours',
'he', 'him', 'his', 'she', 'her', 'hers', 'it', 'its', 'they', 'them',
'their', 'what', 'which', 'who', 'whom', 'when', 'where', 'why', 'how',
'all', 'each', 'every', 'both', 'few', 'more', 'most', 'other', 'some',
'such', 'no', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very',
'just', 'about', 'any', 'also', 'like', 'need', 'want', 'get', 'please',
]);
// Synonyms for common support terms
const SYNONYMS: Record<string, string[]> = {
'refund': ['money back', 'reimbursement', 'return money', 'get money back'],
'return': ['send back', 'give back', 'exchange', 'swap'],
'shipping': ['delivery', 'ship', 'send', 'transit', 'mail'],
'track': ['tracking', 'locate', 'find', 'where is', 'status'],
'order': ['purchase', 'bought', 'buy'],
'account': ['profile', 'login', 'sign in'],
'password': ['login', 'access', 'credentials'],
'cancel': ['cancellation', 'stop', 'void'],
'payment': ['pay', 'charge', 'billing', 'card', 'credit'],
'problem': ['issue', 'trouble', 'error', 'wrong', 'broken'],
'help': ['assist', 'support', 'aid']};
/**
* Normalize text for comparison
*/
function normalizeText(text: string): string {
return text
.toLowerCase()
.replace(/[^\w\s]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
}
/**
* Extract meaningful words from text (removes stop words)
*/
function extractKeywords(text: string): string[] {
return normalizeText(text)
.split(' ')
.filter((word) => word.length > 2 && !STOP_WORDS.has(word));
}
/**
* Expand query with synonyms
*/
function expandWithSynonyms(words: string[]): string[] {
const expanded = new Set(words);
for (const word of words) {
// Check if this word is a synonym of any key
for (const [key, synonyms] of Object.entries(SYNONYMS)) {
if (word === key || synonyms.some(s => s.includes(word))) {
expanded.add(key);
synonyms.forEach(s => {
s.split(' ').forEach(w => {
if (w.length > 2) expanded.add(w);
});
});
}
}
}
return Array.from(expanded);
}
/**
* Calculate advanced match score with TF-IDF-like scoring
* Returns a score between 0 and 1
*/
function calculateMatchScore(query: string, article: SupportArticle): number {
const queryWords = extractKeywords(query);
const expandedQuery = expandWithSynonyms(queryWords);
if (queryWords.length === 0) {
return 0;
}
// Get searchable text from different fields with different weights
const titleText = normalizeText(article.title);
const titleWords = extractKeywords(article.title);
const summaryWords = extractKeywords(article.summary);
const keywordsList = article.keywords.toLowerCase().split(',').map(k => k.trim());
const contentWords = extractKeywords(article.content);
let score = 0;
// Title matches (highest weight - 0.4)
const titleMatches = expandedQuery.filter(word =>
titleText.includes(word) || titleWords.includes(word)
).length;
score += (titleMatches / Math.max(1, queryWords.length)) * 0.4;
// Exact phrase in title (bonus)
const queryPhrase = normalizeText(query);
if (titleText.includes(queryPhrase)) {
score += 0.15;
}
// Keyword matches (high weight - 0.25)
const keywordMatches = expandedQuery.filter(word =>
keywordsList.some(k => k.includes(word) || word.includes(k))
).length;
score += (keywordMatches / Math.max(1, queryWords.length)) * 0.25;
// Summary matches (medium weight - 0.2)
const summaryMatches = expandedQuery.filter(word =>
summaryWords.includes(word)
).length;
score += (summaryMatches / Math.max(1, queryWords.length)) * 0.2;
// Content matches (lower weight - 0.15)
const contentMatches = expandedQuery.filter(word =>
contentWords.includes(word)
).length;
score += (contentMatches / Math.max(1, queryWords.length)) * 0.15;
// Boost based on article popularity (helpful votes vs views)
const popularityBoost = article.viewCount > 0
? Math.min(0.1, (article.helpfulCount / article.viewCount) * 0.1)
: 0;
score += popularityBoost;
return Math.min(1, score);
}
/**
* Find articles matching a query
*/
export async function findMatchingArticles(
query: string,
limit: number = CHATBOT.maxSuggestedArticles
): Promise<SupportArticle[]> {
// Get all published articles
const articles = await prisma.supportArticle.findMany({
where: {
isPublished: true}});
// Score and rank articles
const scoredArticles = articles
.map((article) => ({
article: article as unknown as SupportArticle,
score: calculateMatchScore(query, article as unknown as SupportArticle)}))
.filter((item) => item.score >= CHATBOT.minMatchScore)
.sort((a, b) => b.score - a.score)
.slice(0, limit);
return scoredArticles.map((item) => item.article);
}
/**
* Detect intent from user message
*/
export function detectIntent(
message: string
): 'track_order' | 'create_ticket' | 'view_faq' | 'general' {
const messageLower = message.toLowerCase();
// Order tracking patterns
const orderPatterns = [
'track',
'order status',
'where is my order',
'shipping status',
'delivery',
'when will',
'order number',
];
if (orderPatterns.some((pattern) => messageLower.includes(pattern))) {
return 'track_order';
}
// Support ticket patterns
const ticketPatterns = [
'speak to',
'talk to',
'agent',
'human',
'representative',
'help me',
'problem with',
'issue with',
'complaint',
'escalate',
];
if (ticketPatterns.some((pattern) => messageLower.includes(pattern))) {
return 'create_ticket';
}
// FAQ patterns
const faqPatterns = [
'how do i',
'how to',
'what is',
'can i',
'do you',
'policy',
'return',
'refund',
'shipping',
'payment',
];
if (faqPatterns.some((pattern) => messageLower.includes(pattern))) {
return 'view_faq';
}
return 'general';
}
/**
* Detect ticket category from message
*/
export function detectCategory(message: string): TicketCategory {
const messageLower = message.toLowerCase();
const categoryPatterns: Record<TicketCategory, string[]> = {
[TicketCategory.ORDER_ISSUE]: [
'order',
'wrong item',
'missing item',
'damaged',
'not received',
],
[TicketCategory.SHIPPING]: [
'shipping',
'delivery',
'track',
'carrier',
'shipped',
],
[TicketCategory.RETURNS_REFUNDS]: [
'return',
'refund',
'exchange',
'send back',
'money back',
],
[TicketCategory.PAYMENT]: [
'payment',
'charge',
'credit card',
'billing',
'invoice',
'price',
],
[TicketCategory.PRODUCT_INQUIRY]: [
'product',
'item',
'availability',
'stock',
'specifications',
],
[TicketCategory.ACCOUNT]: [
'account',
'password',
'login',
'sign in',
'profile',
'email',
],
[TicketCategory.TECHNICAL]: [
'error',
'bug',
'not working',
'broken',
'crash',
'technical',
],
[TicketCategory.FEEDBACK]: ['feedback', 'suggestion', 'improve', 'feature request'],
[TicketCategory.OTHER]: []};
for (const [category, patterns] of Object.entries(categoryPatterns)) {
if (patterns.some((pattern) => messageLower.includes(pattern))) {
return category as TicketCategory;
}
}
return TicketCategory.OTHER;
}
/**
* Generate chatbot response based on user message
*/
export async function generateChatbotResponse(message: string): Promise<ChatbotResponse> {
const intent = detectIntent(message);
const matchingArticles = await findMatchingArticles(message);
switch (intent) {
case 'track_order':
return {
message:
'I can help you track your order! Please provide your order number, or you can check your order status in your account dashboard.',
quickActions: [
{ label: 'View My Orders', action: 'track_order' },
{ label: 'Create Ticket', action: 'create_ticket' },
],
suggestedArticles: matchingArticles};
case 'create_ticket':
return {
message:
"I'll connect you with our support team. Please create a ticket and one of our agents will assist you shortly.",
quickActions: [{ label: 'Create Support Ticket', action: 'create_ticket' }],
shouldEscalate: true};
case 'view_faq':
if (matchingArticles.length > 0) {
return {
message:
'I found some articles that might help answer your question:',
suggestedArticles: matchingArticles,
quickActions: [
{ label: 'View All FAQs', action: 'view_faq' },
{ label: 'Contact Support', action: 'create_ticket' },
]};
}
return {
message:
"I couldn't find a specific article for your question. Would you like to browse our FAQ or create a support ticket?",
quickActions: [
{ label: 'Browse FAQ', action: 'view_faq' },
{ label: 'Create Ticket', action: 'create_ticket' },
]};
default:
// General query - try to find matching articles
if (matchingArticles.length > 0) {
return {
message: 'Here are some articles that might help:',
suggestedArticles: matchingArticles,
quickActions: [
{ label: 'View FAQ', action: 'view_faq' },
{ label: 'Contact Support', action: 'create_ticket' },
]};
}
return {
message: CHATBOT.fallbackMessage,
quickActions: [
{ label: 'Browse FAQ', action: 'view_faq' },
{ label: 'Create Support Ticket', action: 'create_ticket' },
],
shouldEscalate: true};
}
}
/**
* Get welcome message with quick actions
*/
export function getWelcomeResponse(): ChatbotResponse {
return {
message: CHATBOT.welcomeMessage,
quickActions: CHATBOT.quickActions.map((action) => ({
label: action.label,
action: action.id as ChatbotQuickAction['action']}))};
}
/**
* Search articles by keyword
*/
export async function searchArticles(
query: string,
category?: string,
limit: number = 10
): Promise<SupportArticle[]> {
const where: Record<string, unknown> = {
isPublished: true};
if (category) {
where.category = category;
}
if (query) {
where.OR = [
{ title: { contains: query } },
{ content: { contains: query } },
{ summary: { contains: query } },
{ keywords: { contains: query } },
];
}
const articles = await prisma.supportArticle.findMany({
where,
take: limit,
orderBy: [{ viewCount: 'desc' }, { helpfulCount: 'desc' }]});
return articles as unknown as SupportArticle[];
}
/**
* Get popular articles
*/
export async function getPopularArticles(
limit: number = 5
): Promise<SupportArticle[]> {
const articles = await prisma.supportArticle.findMany({
where: {
isPublished: true},
take: limit,
orderBy: [{ viewCount: 'desc' }, { helpfulCount: 'desc' }]});
return articles as unknown as SupportArticle[];
}
/**
* Get articles by category
*/
export async function getArticlesByCategory(
category: string,
limit: number = 10
): Promise<SupportArticle[]> {
const articles = await prisma.supportArticle.findMany({
where: {
isPublished: true,
category},
take: limit,
orderBy: [{ viewCount: 'desc' }, { createdAt: 'desc' }]});
return articles as unknown as SupportArticle[];
}
/**
* Increment article view count
*/
export async function incrementArticleViews(articleId: string): Promise<void> {
await prisma.supportArticle.update({
where: { id: articleId },
data: {
viewCount: { increment: 1 }}});
}
/**
* Record article helpfulness vote
*/
export async function recordArticleVote(
articleId: string,
helpful: boolean
): Promise<void> {
await prisma.supportArticle.update({
where: { id: articleId },
data: helpful
? { helpfulCount: { increment: 1 } }
: { notHelpfulCount: { increment: 1 } }});
}
/**
* Get all unique article categories
*/
export async function getArticleCategories(): Promise<string[]> {
const categories = await prisma.supportArticle.findMany({
where: { isPublished: true },
select: { category: true },
distinct: ['category']});
return categories.map((c) => c.category);
}
/**
* Extract common keywords from articles for suggestions
*/
export async function getCommonKeywords(limit: number = 20): Promise<string[]> {
const articles = await prisma.supportArticle.findMany({
where: { isPublished: true },
select: { keywords: true }});
// Count keyword frequency
const keywordCounts: Record<string, number> = {};
for (const article of articles) {
const keywords = article.keywords.split(',').map((k) => k.trim().toLowerCase());
for (const keyword of keywords) {
if (keyword) {
keywordCounts[keyword] = (keywordCounts[keyword] || 0) + 1;
}
}
}
// Sort by frequency and return top keywords
return Object.entries(keywordCounts)
.sort((a, b) => b[1] - a[1])
.slice(0, limit)
.map(([keyword]) => keyword);
}
|