Spaces:
Running
Running
Anousone Worlakoumman commited on
Commit ·
49b9550
1
Parent(s): f87ebcc
remove set cache
Browse files- cmd/exec.go +44 -0
- internal/chatbot/chatbot.go +43 -36
cmd/exec.go
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
package cmd
|
| 2 |
|
| 3 |
import (
|
|
|
|
| 4 |
"api/internal/dashboard"
|
| 5 |
"api/migrations"
|
| 6 |
"fmt"
|
|
@@ -12,6 +13,7 @@ import (
|
|
| 12 |
"github.com/pocketbase/pocketbase/apis"
|
| 13 |
"github.com/pocketbase/pocketbase/core"
|
| 14 |
"github.com/pocketbase/pocketbase/tools/hook"
|
|
|
|
| 15 |
)
|
| 16 |
|
| 17 |
var app *pocketbase.PocketBase
|
|
@@ -79,6 +81,7 @@ func Execute(app *pocketbase.PocketBase) (*pocketbase.PocketBase, error) {
|
|
| 79 |
}).Unbind("something")
|
| 80 |
|
| 81 |
se.Router.POST("/cust/auth/phone-login", func(e *core.RequestEvent) error {
|
|
|
|
| 82 |
data := struct {
|
| 83 |
Phone string `json:"phone" form:"phone"`
|
| 84 |
Password string `json:"password" form:"password"`
|
|
@@ -87,6 +90,7 @@ func Execute(app *pocketbase.PocketBase) (*pocketbase.PocketBase, error) {
|
|
| 87 |
return e.BadRequestError("Failed to read request data", err)
|
| 88 |
}
|
| 89 |
|
|
|
|
| 90 |
record, err := e.App.FindFirstRecordByData("customers", "phone_number", data.Phone)
|
| 91 |
if err != nil || !record.ValidatePassword(data.Password) {
|
| 92 |
return e.BadRequestError("Invalid credentials", err)
|
|
@@ -147,6 +151,46 @@ func Execute(app *pocketbase.PocketBase) (*pocketbase.PocketBase, error) {
|
|
| 147 |
bo.GET("/dashboard/status-count", dashboard.StatusCount)
|
| 148 |
bo.GET("/dashboard/sell-revenue", dashboard.SellRevenue)
|
| 149 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
return se.Next()
|
| 151 |
})
|
| 152 |
|
|
|
|
| 1 |
package cmd
|
| 2 |
|
| 3 |
import (
|
| 4 |
+
"api/internal/chatbot"
|
| 5 |
"api/internal/dashboard"
|
| 6 |
"api/migrations"
|
| 7 |
"fmt"
|
|
|
|
| 13 |
"github.com/pocketbase/pocketbase/apis"
|
| 14 |
"github.com/pocketbase/pocketbase/core"
|
| 15 |
"github.com/pocketbase/pocketbase/tools/hook"
|
| 16 |
+
"github.com/redis/go-redis/v9"
|
| 17 |
)
|
| 18 |
|
| 19 |
var app *pocketbase.PocketBase
|
|
|
|
| 81 |
}).Unbind("something")
|
| 82 |
|
| 83 |
se.Router.POST("/cust/auth/phone-login", func(e *core.RequestEvent) error {
|
| 84 |
+
println("=> start this")
|
| 85 |
data := struct {
|
| 86 |
Phone string `json:"phone" form:"phone"`
|
| 87 |
Password string `json:"password" form:"password"`
|
|
|
|
| 90 |
return e.BadRequestError("Failed to read request data", err)
|
| 91 |
}
|
| 92 |
|
| 93 |
+
println("=> pass")
|
| 94 |
record, err := e.App.FindFirstRecordByData("customers", "phone_number", data.Phone)
|
| 95 |
if err != nil || !record.ValidatePassword(data.Password) {
|
| 96 |
return e.BadRequestError("Invalid credentials", err)
|
|
|
|
| 151 |
bo.GET("/dashboard/status-count", dashboard.StatusCount)
|
| 152 |
bo.GET("/dashboard/sell-revenue", dashboard.SellRevenue)
|
| 153 |
|
| 154 |
+
// Initialize Redis client for chatbot
|
| 155 |
+
redisClient := redis.NewClient(&redis.Options{
|
| 156 |
+
Addr: "localhost:6379", // Configure this via environment variables in production
|
| 157 |
+
Password: "", // No password set
|
| 158 |
+
DB: 0, // Use default DB
|
| 159 |
+
})
|
| 160 |
+
|
| 161 |
+
// Initialize chatbot service
|
| 162 |
+
chatbotService := chatbot.NewChatbotService(app, redisClient)
|
| 163 |
+
|
| 164 |
+
// Chatbot endpoints
|
| 165 |
+
chatbotGroup := se.Router.Group("/chatbot").Bind(apis.RequireAuth("users"))
|
| 166 |
+
chatbotGroup.POST("/message", func(e *core.RequestEvent) error {
|
| 167 |
+
data := struct {
|
| 168 |
+
Message string `json:"message"`
|
| 169 |
+
}{}
|
| 170 |
+
|
| 171 |
+
if err := e.BindBody(&data); err != nil {
|
| 172 |
+
return e.BadRequestError("Failed to read request data", err)
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
user := e.Auth
|
| 176 |
+
response, err := chatbotService.ProcessMessage(e.Request.Context(), user.Id, data.Message)
|
| 177 |
+
if err != nil {
|
| 178 |
+
return e.InternalServerError("Failed to process message", err)
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
return e.JSON(200, response)
|
| 182 |
+
})
|
| 183 |
+
|
| 184 |
+
// WebSocket endpoint for real-time chat
|
| 185 |
+
se.Router.GET("/chatbot/ws", func(e *core.RequestEvent) error {
|
| 186 |
+
// Set user in request context for WebSocket handler
|
| 187 |
+
ctx := e.Request.Context()
|
| 188 |
+
ctx = context.WithValue(ctx, "user", e.Auth)
|
| 189 |
+
e.Request = e.Request.WithContext(ctx)
|
| 190 |
+
|
| 191 |
+
return chatbotService.HandleWebSocket(e.Response, e.Request)
|
| 192 |
+
}).Bind(apis.RequireAuth("customers"))
|
| 193 |
+
|
| 194 |
return se.Next()
|
| 195 |
})
|
| 196 |
|
internal/chatbot/chatbot.go
CHANGED
|
@@ -18,7 +18,6 @@ import (
|
|
| 18 |
// ChatbotService handles all chatbot operations
|
| 19 |
type ChatbotService struct {
|
| 20 |
app *pocketbase.PocketBase
|
| 21 |
-
redis *redis.Client
|
| 22 |
rateLimiter *RateLimiter
|
| 23 |
intents map[string]IntentHandler
|
| 24 |
}
|
|
@@ -46,8 +45,7 @@ type RateLimiter struct {
|
|
| 46 |
// Initialize the chatbot service
|
| 47 |
func NewChatbotService(app *pocketbase.PocketBase, redisClient *redis.Client) *ChatbotService {
|
| 48 |
service := &ChatbotService{
|
| 49 |
-
app:
|
| 50 |
-
redis: redisClient,
|
| 51 |
rateLimiter: &RateLimiter{
|
| 52 |
redis: redisClient,
|
| 53 |
maxRequests: 20, // 20 requests per user
|
|
@@ -72,6 +70,7 @@ func (s *ChatbotService) registerIntents() {
|
|
| 72 |
|
| 73 |
// Main message processing function
|
| 74 |
func (s *ChatbotService) ProcessMessage(ctx context.Context, userID, message string) (*ChatMessage, error) {
|
|
|
|
| 75 |
// Check rate limit
|
| 76 |
allowed, err := s.rateLimiter.CheckLimit(ctx, userID)
|
| 77 |
if err != nil {
|
|
@@ -79,34 +78,21 @@ func (s *ChatbotService) ProcessMessage(ctx context.Context, userID, message str
|
|
| 79 |
}
|
| 80 |
if !allowed {
|
| 81 |
return &ChatMessage{
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
| 86 |
}, nil
|
| 87 |
}
|
| 88 |
|
| 89 |
// Detect intent
|
| 90 |
intent, params := s.detectIntent(message)
|
| 91 |
|
| 92 |
-
// Check cache first with proper error handling
|
| 93 |
-
cacheKey := fmt.Sprintf("chat:%s:%s", userID, intent)
|
| 94 |
-
cached, err := s.redis.Get(ctx, cacheKey).Result()
|
| 95 |
-
if err == nil && cached != "" {
|
| 96 |
-
return &ChatMessage{
|
| 97 |
-
UserID: userID,
|
| 98 |
-
Message: message,
|
| 99 |
-
Response: cached,
|
| 100 |
-
Intent: intent,
|
| 101 |
-
}, nil
|
| 102 |
-
}
|
| 103 |
-
// Log cache miss or error for debugging
|
| 104 |
-
if err != nil && err != redis.Nil {
|
| 105 |
-
s.app.Logger().Warn("Cache read error", "error", err, "key", cacheKey)
|
| 106 |
-
}
|
| 107 |
-
|
| 108 |
// Process based on intent
|
| 109 |
var response string
|
|
|
|
| 110 |
if handler, exists := s.intents[intent]; exists {
|
| 111 |
response, err = handler(ctx, userID, params)
|
| 112 |
if err != nil {
|
|
@@ -116,12 +102,6 @@ func (s *ChatbotService) ProcessMessage(ctx context.Context, userID, message str
|
|
| 116 |
response = s.handleUnknownIntent(ctx, userID, message)
|
| 117 |
}
|
| 118 |
|
| 119 |
-
// Cache the response with error handling
|
| 120 |
-
if err := s.redis.Set(ctx, cacheKey, response, 30*time.Minute).Err(); err != nil {
|
| 121 |
-
// Log cache error but don't fail the request
|
| 122 |
-
s.app.Logger().Warn("Failed to cache response", "error", err, "key", cacheKey)
|
| 123 |
-
}
|
| 124 |
-
|
| 125 |
// Log conversation
|
| 126 |
chatMsg := &ChatMessage{
|
| 127 |
ID: generateID(),
|
|
@@ -157,6 +137,7 @@ func (s *ChatbotService) detectIntent(message string) (string, map[string]string
|
|
| 157 |
strings.Contains(message, "details") || strings.Contains(message, "information") {
|
| 158 |
if productID := extractProductID(message); productID != "" {
|
| 159 |
params["productID"] = productID
|
|
|
|
| 160 |
}
|
| 161 |
return "product_info", params
|
| 162 |
}
|
|
@@ -217,6 +198,7 @@ func (s *ChatbotService) handleOrderStatus(ctx context.Context, userID string, p
|
|
| 217 |
// Handler: Product Information
|
| 218 |
func (s *ChatbotService) handleProductInfo(ctx context.Context, userID string, params map[string]string) (string, error) {
|
| 219 |
productID, ok := params["productID"]
|
|
|
|
| 220 |
if !ok {
|
| 221 |
return "Please specify which product you'd like information about.", nil
|
| 222 |
}
|
|
@@ -315,7 +297,7 @@ func (r *RateLimiter) CheckLimit(ctx context.Context, userID string) (bool, erro
|
|
| 315 |
}
|
| 316 |
|
| 317 |
// WebSocket handler for real-time chat
|
| 318 |
-
func (s *ChatbotService) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
|
| 319 |
upgrader := websocket.Upgrader{
|
| 320 |
CheckOrigin: func(r *http.Request) bool {
|
| 321 |
// Configure origin checking in production
|
|
@@ -325,13 +307,21 @@ func (s *ChatbotService) HandleWebSocket(w http.ResponseWriter, r *http.Request)
|
|
| 325 |
|
| 326 |
conn, err := upgrader.Upgrade(w, r, nil)
|
| 327 |
if err != nil {
|
| 328 |
-
return
|
| 329 |
}
|
| 330 |
defer conn.Close()
|
| 331 |
|
| 332 |
-
// Get user from context
|
| 333 |
-
user := r.Context().Value("user")
|
| 334 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
|
| 336 |
for {
|
| 337 |
var msg struct {
|
|
@@ -354,6 +344,8 @@ func (s *ChatbotService) HandleWebSocket(w http.ResponseWriter, r *http.Request)
|
|
| 354 |
// Send response
|
| 355 |
conn.WriteJSON(response)
|
| 356 |
}
|
|
|
|
|
|
|
| 357 |
}
|
| 358 |
|
| 359 |
// Utility functions
|
|
@@ -370,11 +362,26 @@ func extractOrderID(message string) string {
|
|
| 370 |
}
|
| 371 |
|
| 372 |
func extractProductID(message string) string {
|
| 373 |
-
// Extract product ID from message
|
| 374 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
return ""
|
| 376 |
}
|
| 377 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
func generateID() string {
|
| 379 |
return fmt.Sprintf("%d", time.Now().UnixNano())
|
| 380 |
}
|
|
|
|
| 18 |
// ChatbotService handles all chatbot operations
|
| 19 |
type ChatbotService struct {
|
| 20 |
app *pocketbase.PocketBase
|
|
|
|
| 21 |
rateLimiter *RateLimiter
|
| 22 |
intents map[string]IntentHandler
|
| 23 |
}
|
|
|
|
| 45 |
// Initialize the chatbot service
|
| 46 |
func NewChatbotService(app *pocketbase.PocketBase, redisClient *redis.Client) *ChatbotService {
|
| 47 |
service := &ChatbotService{
|
| 48 |
+
app: app,
|
|
|
|
| 49 |
rateLimiter: &RateLimiter{
|
| 50 |
redis: redisClient,
|
| 51 |
maxRequests: 20, // 20 requests per user
|
|
|
|
| 70 |
|
| 71 |
// Main message processing function
|
| 72 |
func (s *ChatbotService) ProcessMessage(ctx context.Context, userID, message string) (*ChatMessage, error) {
|
| 73 |
+
fmt.Print("=> start\n")
|
| 74 |
// Check rate limit
|
| 75 |
allowed, err := s.rateLimiter.CheckLimit(ctx, userID)
|
| 76 |
if err != nil {
|
|
|
|
| 78 |
}
|
| 79 |
if !allowed {
|
| 80 |
return &ChatMessage{
|
| 81 |
+
ID: generateID(),
|
| 82 |
+
UserID: userID,
|
| 83 |
+
Message: message,
|
| 84 |
+
Response: "You've reached the chat limit. Please try again later.",
|
| 85 |
+
Intent: "rate_limited",
|
| 86 |
+
Timestamp: time.Now(),
|
| 87 |
}, nil
|
| 88 |
}
|
| 89 |
|
| 90 |
// Detect intent
|
| 91 |
intent, params := s.detectIntent(message)
|
| 92 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
// Process based on intent
|
| 94 |
var response string
|
| 95 |
+
fmt.Printf("=> intent: %v\n", intent)
|
| 96 |
if handler, exists := s.intents[intent]; exists {
|
| 97 |
response, err = handler(ctx, userID, params)
|
| 98 |
if err != nil {
|
|
|
|
| 102 |
response = s.handleUnknownIntent(ctx, userID, message)
|
| 103 |
}
|
| 104 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
// Log conversation
|
| 106 |
chatMsg := &ChatMessage{
|
| 107 |
ID: generateID(),
|
|
|
|
| 137 |
strings.Contains(message, "details") || strings.Contains(message, "information") {
|
| 138 |
if productID := extractProductID(message); productID != "" {
|
| 139 |
params["productID"] = productID
|
| 140 |
+
fmt.Printf("=> params: %+v\n", params)
|
| 141 |
}
|
| 142 |
return "product_info", params
|
| 143 |
}
|
|
|
|
| 198 |
// Handler: Product Information
|
| 199 |
func (s *ChatbotService) handleProductInfo(ctx context.Context, userID string, params map[string]string) (string, error) {
|
| 200 |
productID, ok := params["productID"]
|
| 201 |
+
fmt.Printf("=> productID: %v\n", productID)
|
| 202 |
if !ok {
|
| 203 |
return "Please specify which product you'd like information about.", nil
|
| 204 |
}
|
|
|
|
| 297 |
}
|
| 298 |
|
| 299 |
// WebSocket handler for real-time chat
|
| 300 |
+
func (s *ChatbotService) HandleWebSocket(w http.ResponseWriter, r *http.Request) error {
|
| 301 |
upgrader := websocket.Upgrader{
|
| 302 |
CheckOrigin: func(r *http.Request) bool {
|
| 303 |
// Configure origin checking in production
|
|
|
|
| 307 |
|
| 308 |
conn, err := upgrader.Upgrade(w, r, nil)
|
| 309 |
if err != nil {
|
| 310 |
+
return err
|
| 311 |
}
|
| 312 |
defer conn.Close()
|
| 313 |
|
| 314 |
+
// Get user from context - this will be set by the auth middleware
|
| 315 |
+
user := r.Context().Value("user")
|
| 316 |
+
if user == nil {
|
| 317 |
+
return fmt.Errorf("user not found in context")
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
userRecord, ok := user.(*core.Record)
|
| 321 |
+
if !ok {
|
| 322 |
+
return fmt.Errorf("invalid user type in context")
|
| 323 |
+
}
|
| 324 |
+
userID := userRecord.Id
|
| 325 |
|
| 326 |
for {
|
| 327 |
var msg struct {
|
|
|
|
| 344 |
// Send response
|
| 345 |
conn.WriteJSON(response)
|
| 346 |
}
|
| 347 |
+
|
| 348 |
+
return nil
|
| 349 |
}
|
| 350 |
|
| 351 |
// Utility functions
|
|
|
|
| 362 |
}
|
| 363 |
|
| 364 |
func extractProductID(message string) string {
|
| 365 |
+
// Extract product ID from message - look for alphanumeric sequences
|
| 366 |
+
parts := strings.Fields(message)
|
| 367 |
+
for _, part := range parts {
|
| 368 |
+
// Look for product ID pattern (alphanumeric, typically 10+ chars)
|
| 369 |
+
if len(part) >= 10 && isAlphanumeric(part) {
|
| 370 |
+
return part
|
| 371 |
+
}
|
| 372 |
+
}
|
| 373 |
return ""
|
| 374 |
}
|
| 375 |
|
| 376 |
+
func isAlphanumeric(s string) bool {
|
| 377 |
+
for _, r := range s {
|
| 378 |
+
if !((r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9')) {
|
| 379 |
+
return false
|
| 380 |
+
}
|
| 381 |
+
}
|
| 382 |
+
return true
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
func generateID() string {
|
| 386 |
return fmt.Sprintf("%d", time.Now().UnixNano())
|
| 387 |
}
|