- Backend: - Fix ListTickets parameter order mismatch for assignee filtering - Replicate all 13 PostgreSQL tables and columns during disaster recovery sync and rollback - Implement server-side session store with HttpOnly cookies and Bearer tokens - Add profile update verification requiring current password - Whitelist allowed file uploads and apply strict security headers (nosniff, CSP) - Enforce role check on error deletion (admin/lead/tester only) and authenticate SSE stream - Align foreign key user_id for saved filters and api tokens - Add ReopenTicket endpoint and workflow - Integrate Cloudflare Turnstile verification with testing/production key support - Frontend: - Remove liquid glass displacement filter and lens capsule for high-performance UI - Eliminate recursive backdrop-filters and heavy inset shadows - Add debounced search and optimize SSE re-rendering - Wire Saved Views filter bar with creation, active indicators, and deletion - Add Linked & Related Tickets management UI to sheet - Seed 6 demo personas in PostgreSQL with instant sign-in - Add Cloudflare Turnstile widgets to authentication modals - Add keyboard arrow navigation to Command Palette - Image Manipulator, Docs & Tooling: - Sync image manipulator updates, docs, and test coordinates
1605 lines
47 KiB
Go
1605 lines
47 KiB
Go
package khira
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type Server struct {
|
|
Store *Store
|
|
Turnstile *TurnstileClient
|
|
}
|
|
|
|
func NewServer(store *Store) *Server {
|
|
return &Server{
|
|
Store: store,
|
|
Turnstile: NewTurnstileClient(),
|
|
}
|
|
}
|
|
|
|
func (s *Server) writeJSON(w http.ResponseWriter, status int, data any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(data)
|
|
}
|
|
|
|
func (s *Server) getActor(r *http.Request) *User {
|
|
// 1. Check Bearer token (supports both session tokens and API tokens)
|
|
authHdr := r.Header.Get("Authorization")
|
|
if strings.HasPrefix(strings.ToLower(authHdr), "bearer ") {
|
|
tok := strings.TrimSpace(authHdr[7:])
|
|
if u, err := s.Store.ValidateSession(tok); err == nil && u != nil {
|
|
return u
|
|
}
|
|
if u, err := s.Store.ValidateAPIToken(tok); err == nil && u != nil {
|
|
return u
|
|
}
|
|
}
|
|
|
|
// 2. Check HTTP-only session cookie
|
|
if cookie, err := r.Cookie("khira_session"); err == nil && cookie.Value != "" {
|
|
if u, err := s.Store.ValidateSession(cookie.Value); err == nil && u != nil {
|
|
return u
|
|
}
|
|
}
|
|
|
|
// 3. Fallback: API token in X-API-Key header if provided
|
|
if apiKey := r.Header.Get("X-API-Key"); apiKey != "" {
|
|
if u, err := s.Store.ValidateAPIToken(apiKey); err == nil && u != nil {
|
|
return u
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *Server) RegisterRoutes(r chi.Router) {
|
|
// Root and SPA entry
|
|
r.Get("/", func(w http.ResponseWriter, req *http.Request) {
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
http.ServeFile(w, req, "web/khira/index.html")
|
|
})
|
|
|
|
// Direct static assets
|
|
r.Get("/styles.css", func(w http.ResponseWriter, req *http.Request) {
|
|
w.Header().Set("Content-Type", "text/css; charset=utf-8")
|
|
http.ServeFile(w, req, "web/khira/styles.css")
|
|
})
|
|
|
|
r.Get("/app.js", func(w http.ResponseWriter, req *http.Request) {
|
|
w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
|
|
http.ServeFile(w, req, "web/khira/app.js")
|
|
})
|
|
|
|
// Uploaded files static serving
|
|
uploadsDir := filepath.Join(s.Store.GetDataDir(), "uploads")
|
|
_ = os.MkdirAll(uploadsDir, 0755)
|
|
uploadFileServer := http.StripPrefix("/khira/uploads", http.FileServer(http.Dir(uploadsDir)))
|
|
r.Get("/uploads/*", func(w http.ResponseWriter, req *http.Request) {
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
w.Header().Set("Content-Security-Policy", "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'")
|
|
ext := strings.ToLower(filepath.Ext(req.URL.Path))
|
|
if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".webp" || ext == ".gif" {
|
|
w.Header().Set("Content-Disposition", "inline")
|
|
} else {
|
|
w.Header().Set("Content-Disposition", "attachment")
|
|
}
|
|
uploadFileServer.ServeHTTP(w, req)
|
|
})
|
|
|
|
// Static assets or fallback to index.html
|
|
r.Get("/*", func(w http.ResponseWriter, req *http.Request) {
|
|
if strings.HasPrefix(req.URL.Path, "/khira/api") {
|
|
http.NotFound(w, req)
|
|
return
|
|
}
|
|
subPath := chi.URLParam(req, "*")
|
|
if subPath != "" {
|
|
cleanPath := filepath.Clean(subPath)
|
|
filePath := filepath.Join("web/khira", cleanPath)
|
|
if info, err := os.Stat(filePath); err == nil && !info.IsDir() {
|
|
http.ServeFile(w, req, filePath)
|
|
return
|
|
}
|
|
}
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
http.ServeFile(w, req, "web/khira/index.html")
|
|
})
|
|
|
|
// API Routes under /api
|
|
r.Route("/api", func(api chi.Router) {
|
|
// Auth
|
|
api.Get("/auth/turnstile-config", s.handleTurnstileConfig)
|
|
api.Post("/auth/register", s.handleRegister)
|
|
api.Post("/auth/login", s.handleLogin)
|
|
api.Post("/auth/logout", s.handleLogout)
|
|
api.Post("/auth/forgot-password", s.handleForgotPassword)
|
|
api.Get("/auth/me", s.handleMe)
|
|
api.Put("/auth/profile", s.handleUpdateProfile)
|
|
api.Post("/auth/profile", s.handleUpdateProfile)
|
|
|
|
// Users & Apps
|
|
api.Get("/users", s.handleListUsers)
|
|
api.Get("/apps", s.handleListApps)
|
|
|
|
// Tickets
|
|
api.Get("/tickets", s.handleListTickets)
|
|
api.Post("/tickets", s.handleCreateTicket)
|
|
api.Get("/tickets/{id}", s.handleGetTicket)
|
|
api.Delete("/tickets/{id}", s.handleDeleteTicket)
|
|
api.Post("/tickets/{id}/delete", s.handleDeleteTicket)
|
|
api.Post("/tickets/{id}/remarks", s.handleAddRemark)
|
|
api.Post("/tickets/{id}/hold", s.handleHoldTicket)
|
|
api.Post("/tickets/{id}/resume", s.handleResumeTicket)
|
|
api.Post("/tickets/{id}/reopen", s.handleReopenTicket)
|
|
api.Post("/tickets/{id}/complete", s.handleCompleteTicket)
|
|
api.Post("/tickets/{id}/archive", s.handleArchiveTicket)
|
|
api.Post("/tickets/{id}/unarchive", s.handleUnarchiveTicket)
|
|
api.Post("/tickets/{id}/priority", s.handleChangePriority)
|
|
api.Post("/tickets/{id}/reassign", s.handleReassignTicket)
|
|
api.Post("/tickets/{id}/attachments", s.handleAddAttachment)
|
|
api.Post("/tickets/{id}/links", s.handleAddLink)
|
|
|
|
// Uploads
|
|
api.Post("/upload", s.handleUpload)
|
|
|
|
// Notifications & Stats
|
|
api.Get("/notifications", s.handleGetNotifications)
|
|
api.Post("/notifications/read", s.handleMarkNotificationsRead)
|
|
api.Get("/stats", s.handleStats)
|
|
|
|
// Errors Tracking & Management
|
|
api.Get("/errors", s.handleListErrors)
|
|
api.Post("/errors", s.handleIngestError)
|
|
api.Get("/errors/stats", s.handleErrorStats)
|
|
api.Get("/errors/{id}", s.handleGetError)
|
|
api.Put("/errors/{id}", s.handleUpdateError)
|
|
api.Post("/errors/{id}", s.handleUpdateError)
|
|
api.Delete("/errors/{id}", s.handleDeleteError)
|
|
api.Put("/errors/{id}/status", s.handleUpdateErrorStatus)
|
|
api.Post("/errors/{id}/status", s.handleUpdateErrorStatus)
|
|
api.Post("/errors/{id}/escalate", s.handleEscalateError)
|
|
api.Post("/errors/{id}/archive", s.handleArchiveError)
|
|
api.Post("/errors/{id}/unarchive", s.handleUnarchiveError)
|
|
|
|
// Admin Database Sync & Rollback
|
|
api.Post("/admin/db/sync", s.handleDBSync)
|
|
api.Post("/admin/db/rollback", s.handleDBRollback)
|
|
api.Get("/admin/db/status", s.handleDBStatus)
|
|
|
|
// Enterprise Features
|
|
// Analytics
|
|
api.Get("/analytics", s.handleAnalytics)
|
|
|
|
// Bulk Actions
|
|
api.Post("/tickets/bulk", s.handleBulkActions)
|
|
|
|
// Tags
|
|
api.Get("/tags", s.handleListTags)
|
|
api.Post("/tickets/{id}/tags", s.handleAddTag)
|
|
api.Delete("/tickets/{id}/tags/{tag}", s.handleRemoveTag)
|
|
|
|
// Relations / Ticket Linking
|
|
api.Post("/tickets/{id}/relations", s.handleLinkTickets)
|
|
api.Delete("/tickets/{id}/relations/{target}", s.handleUnlinkTickets)
|
|
|
|
// Saved Filters
|
|
api.Get("/filters", s.handleListSavedFilters)
|
|
api.Post("/filters", s.handleCreateSavedFilter)
|
|
api.Delete("/filters/{id}", s.handleDeleteSavedFilter)
|
|
|
|
// API Tokens
|
|
api.Get("/tokens", s.handleListAPITokens)
|
|
api.Post("/tokens", s.handleCreateAPIToken)
|
|
api.Delete("/tokens/{id}", s.handleRevokeAPIToken)
|
|
|
|
// Admin User Management
|
|
api.Get("/admin/users", s.handleAdminListUsers)
|
|
api.Patch("/admin/users/{username}/role", s.handleAdminUpdateRole)
|
|
api.Patch("/admin/users/{username}/status", s.handleAdminUpdateStatus)
|
|
api.Post("/admin/users/{username}/reset-password", s.handleAdminResetPassword)
|
|
|
|
// Export CSV
|
|
api.Get("/tickets/export", s.handleExportTickets)
|
|
api.Get("/errors/export", s.handleExportErrors)
|
|
|
|
// Notifications Single Item Ops
|
|
api.Delete("/notifications/{id}", s.handleDeleteNotification)
|
|
api.Delete("/notifications", s.handleClearNotifications)
|
|
api.Post("/notifications/{id}/read", s.handleMarkNotificationReadSingle)
|
|
|
|
// Realtime Server-Sent Events (SSE) Stream
|
|
api.Get("/events", s.handleEventsSSE)
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleTurnstileConfig(w http.ResponseWriter, r *http.Request) {
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"site_key": s.Turnstile.SiteKey,
|
|
"enabled": true,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Username string `json:"username"`
|
|
Name string `json:"name"`
|
|
Password string `json:"password"`
|
|
Role string `json:"role"`
|
|
TurnstileToken string `json:"turnstile_token"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid request payload"})
|
|
return
|
|
}
|
|
|
|
if req.TurnstileToken != "" {
|
|
if valid, err := s.Turnstile.Verify(req.TurnstileToken, r.RemoteAddr); !valid || err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Turnstile verification failed. Please try again."})
|
|
return
|
|
}
|
|
}
|
|
|
|
u, err := s.Store.RegisterUser(req.Username, req.Name, req.Password, req.Role)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
sess, err := s.Store.CreateSession(u)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Failed to create session"})
|
|
return
|
|
}
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: "khira_session",
|
|
Value: sess.Token,
|
|
Path: "/",
|
|
MaxAge: 86400 * 30, // 30 days
|
|
HttpOnly: true,
|
|
SameSite: http.SameSiteLaxMode,
|
|
})
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: "khira_session_user",
|
|
Value: u.Username,
|
|
Path: "/",
|
|
MaxAge: 86400 * 30,
|
|
HttpOnly: false,
|
|
SameSite: http.SameSiteLaxMode,
|
|
})
|
|
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"token": sess.Token,
|
|
"user": u.Public(),
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
TurnstileToken string `json:"turnstile_token"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid request payload"})
|
|
return
|
|
}
|
|
|
|
if req.TurnstileToken != "" {
|
|
if valid, err := s.Turnstile.Verify(req.TurnstileToken, r.RemoteAddr); !valid || err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Turnstile verification failed. Please try again."})
|
|
return
|
|
}
|
|
}
|
|
|
|
u, err := s.Store.AuthenticateUser(req.Username, req.Password)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
sess, err := s.Store.CreateSession(u)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Failed to create session"})
|
|
return
|
|
}
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: "khira_session",
|
|
Value: sess.Token,
|
|
Path: "/",
|
|
MaxAge: 86400 * 30,
|
|
HttpOnly: true,
|
|
SameSite: http.SameSiteLaxMode,
|
|
})
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: "khira_session_user",
|
|
Value: u.Username,
|
|
Path: "/",
|
|
MaxAge: 86400 * 30,
|
|
HttpOnly: false,
|
|
SameSite: http.SameSiteLaxMode,
|
|
})
|
|
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"token": sess.Token,
|
|
"user": u.Public(),
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
|
|
if cookie, err := r.Cookie("khira_session"); err == nil && cookie.Value != "" {
|
|
s.Store.DeleteSession(cookie.Value)
|
|
}
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: "khira_session",
|
|
Value: "",
|
|
Path: "/",
|
|
MaxAge: -1,
|
|
HttpOnly: true,
|
|
SameSite: http.SameSiteLaxMode,
|
|
})
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: "khira_session_user",
|
|
Value: "",
|
|
Path: "/",
|
|
MaxAge: -1,
|
|
HttpOnly: false,
|
|
SameSite: http.SameSiteLaxMode,
|
|
})
|
|
s.writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
|
}
|
|
|
|
func (s *Server) handleForgotPassword(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Username string `json:"username"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid request body"})
|
|
return
|
|
}
|
|
username := strings.TrimSpace(req.Username)
|
|
if username == "" {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Username is required"})
|
|
return
|
|
}
|
|
|
|
ticket, err := s.Store.RequestPasswordReset(username)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"message": fmt.Sprintf("Password reset ticket %s raised for administrator.", ticket.ID),
|
|
"ticket_id": ticket.ID,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"authenticated": false,
|
|
"user": nil,
|
|
})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"authenticated": true,
|
|
"user": actor.Public(),
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleUpdateProfile(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to update your profile"})
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
Name string `json:"name"`
|
|
Role string `json:"role"`
|
|
Avatar string `json:"avatar"`
|
|
AvatarType string `json:"avatar_type"`
|
|
ProfileImage string `json:"profile_image"`
|
|
NewPassword string `json:"new_password"`
|
|
Password string `json:"password"`
|
|
CurrentPassword string `json:"current_password"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid request payload"})
|
|
return
|
|
}
|
|
|
|
pass := strings.TrimSpace(req.NewPassword)
|
|
if pass == "" {
|
|
pass = strings.TrimSpace(req.Password)
|
|
}
|
|
|
|
if pass != "" {
|
|
if strings.TrimSpace(req.CurrentPassword) == "" {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Current password is required to change password"})
|
|
return
|
|
}
|
|
if _, err := s.Store.AuthenticateUser(actor.Username, req.CurrentPassword); err != nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Current password is incorrect"})
|
|
return
|
|
}
|
|
}
|
|
|
|
if strings.TrimSpace(req.Avatar) == "A" && !s.isAdmin(actor) {
|
|
s.writeJSON(w, http.StatusForbidden, map[string]string{"error": "The 'A' avatar is exclusively reserved for administrators"})
|
|
return
|
|
}
|
|
|
|
updated, err := s.Store.UpdateUserProfileFull(actor.Username, req.Name, req.Role, req.Avatar, req.AvatarType, req.ProfileImage, pass)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"user": updated.Public(),
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleListUsers(w http.ResponseWriter, r *http.Request) {
|
|
users := s.Store.ListUsers()
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"users": users,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleListApps(w http.ResponseWriter, r *http.Request) {
|
|
assignee := r.URL.Query().Get("assignee")
|
|
role := r.URL.Query().Get("role")
|
|
q := r.URL.Query().Get("q")
|
|
|
|
if role == "" && assignee != "" {
|
|
if u, err := s.Store.GetUser(assignee); err == nil && u != nil {
|
|
role = u.Role
|
|
}
|
|
}
|
|
|
|
apps := s.Store.ListApps(role, q)
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"apps": apps,
|
|
"count": len(apps),
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleListTickets(w http.ResponseWriter, r *http.Request) {
|
|
status := r.URL.Query().Get("status")
|
|
priority := r.URL.Query().Get("priority")
|
|
app := r.URL.Query().Get("app")
|
|
assignee := r.URL.Query().Get("assignee")
|
|
creator := r.URL.Query().Get("creator")
|
|
if creator == "" {
|
|
creator = r.URL.Query().Get("reporter")
|
|
}
|
|
ticketType := r.URL.Query().Get("type")
|
|
if ticketType == "" {
|
|
ticketType = r.URL.Query().Get("ticket_type")
|
|
}
|
|
q := r.URL.Query().Get("q")
|
|
|
|
tickets := s.Store.ListTickets(status, priority, app, assignee, creator, q, ticketType)
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"tickets": tickets,
|
|
"count": len(tickets),
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleCreateTicket(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to create a ticket"})
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
TicketType string `json:"ticket_type"`
|
|
Type string `json:"type"`
|
|
GeneralCategory string `json:"general_category"`
|
|
Category string `json:"category"`
|
|
Department string `json:"department"`
|
|
Scope string `json:"scope"`
|
|
Title string `json:"title"`
|
|
AppName string `json:"app_name"`
|
|
App string `json:"app"`
|
|
Version string `json:"version"`
|
|
FeatureName string `json:"feature_name"`
|
|
Feature string `json:"feature"`
|
|
APIKey string `json:"api_key"`
|
|
IssueType string `json:"issue_type"`
|
|
Priority string `json:"priority"`
|
|
Status string `json:"status"`
|
|
Description string `json:"description"`
|
|
AssistanceRequired string `json:"assistance_required"`
|
|
Assistance string `json:"assistance"`
|
|
AdditionalInfo string `json:"additional_info"`
|
|
Context string `json:"context"`
|
|
AssignedTo string `json:"assigned_to"`
|
|
AssigneeUsername string `json:"assignee_username"`
|
|
DeveloperAccount string `json:"developer_account"`
|
|
ImageURL string `json:"image_url"`
|
|
DueDate string `json:"due_date"`
|
|
SLAHours int `json:"sla_hours"`
|
|
Tags []string `json:"tags"`
|
|
Attachments []Attachment `json:"attachments"`
|
|
Links []string `json:"links"`
|
|
}
|
|
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid ticket data"})
|
|
return
|
|
}
|
|
|
|
ticketType := strings.ToLower(strings.TrimSpace(req.TicketType))
|
|
if ticketType == "" {
|
|
ticketType = strings.ToLower(strings.TrimSpace(req.Type))
|
|
}
|
|
if ticketType == "" {
|
|
if req.GeneralCategory != "" || req.Category != "" || req.Department != "" {
|
|
ticketType = "general"
|
|
} else {
|
|
ticketType = "application"
|
|
}
|
|
}
|
|
|
|
title := strings.TrimSpace(req.Title)
|
|
if title == "" {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Ticket title is required"})
|
|
return
|
|
}
|
|
|
|
assignedTo := strings.TrimSpace(req.AssignedTo)
|
|
if assignedTo == "" {
|
|
assignedTo = strings.TrimSpace(req.AssigneeUsername)
|
|
}
|
|
if assignedTo == "" {
|
|
assignedTo = strings.TrimSpace(req.DeveloperAccount)
|
|
}
|
|
|
|
appName := strings.TrimSpace(req.AppName)
|
|
if appName == "" {
|
|
appName = strings.TrimSpace(req.App)
|
|
}
|
|
|
|
featureName := strings.TrimSpace(req.FeatureName)
|
|
if featureName == "" {
|
|
featureName = strings.TrimSpace(req.Feature)
|
|
}
|
|
|
|
assistance := strings.TrimSpace(req.AssistanceRequired)
|
|
if assistance == "" {
|
|
assistance = strings.TrimSpace(req.Assistance)
|
|
}
|
|
|
|
additionalInfo := strings.TrimSpace(req.AdditionalInfo)
|
|
if additionalInfo == "" {
|
|
additionalInfo = strings.TrimSpace(req.Context)
|
|
}
|
|
|
|
generalCategory := strings.TrimSpace(req.GeneralCategory)
|
|
if generalCategory == "" {
|
|
generalCategory = strings.TrimSpace(req.Category)
|
|
}
|
|
|
|
department := strings.TrimSpace(req.Department)
|
|
if department == "" {
|
|
department = strings.TrimSpace(req.Scope)
|
|
}
|
|
|
|
// Priority normalization (support P0/P1/P2/P3 as well as critical/high/medium/low)
|
|
p := strings.ToLower(strings.TrimSpace(req.Priority))
|
|
switch p {
|
|
case "p0", "critical":
|
|
p = string(PriorityCritical)
|
|
case "p1", "high":
|
|
p = string(PriorityHigh)
|
|
case "p2", "medium":
|
|
p = string(PriorityMedium)
|
|
case "p3", "low":
|
|
p = string(PriorityLow)
|
|
default:
|
|
if p == "" {
|
|
p = string(PriorityMedium)
|
|
}
|
|
}
|
|
|
|
var atts []Attachment
|
|
for _, a := range req.Attachments {
|
|
if strings.TrimSpace(a.URL) != "" {
|
|
atts = append(atts, a)
|
|
}
|
|
}
|
|
if req.ImageURL != "" {
|
|
atts = append(atts, Attachment{
|
|
ID: uuid.New().String(),
|
|
Name: "screenshot",
|
|
URL: strings.TrimSpace(req.ImageURL),
|
|
Type: "image",
|
|
UploadedBy: actor.Username,
|
|
CreatedAt: time.Now(),
|
|
})
|
|
}
|
|
|
|
ticket := &Ticket{
|
|
TicketType: ticketType,
|
|
GeneralCategory: generalCategory,
|
|
Department: department,
|
|
Title: title,
|
|
AppName: appName,
|
|
Version: strings.TrimSpace(req.Version),
|
|
FeatureName: featureName,
|
|
APIKey: strings.TrimSpace(req.APIKey),
|
|
IssueType: strings.TrimSpace(req.IssueType),
|
|
Priority: p,
|
|
Status: strings.TrimSpace(req.Status),
|
|
Description: strings.TrimSpace(req.Description),
|
|
AssistanceRequired: assistance,
|
|
AdditionalInfo: additionalInfo,
|
|
AssignedTo: assignedTo,
|
|
SLAHours: req.SLAHours,
|
|
Tags: req.Tags,
|
|
Links: req.Links,
|
|
Attachments: atts,
|
|
}
|
|
|
|
if req.DueDate != "" {
|
|
if parsed, err := time.Parse(time.RFC3339, req.DueDate); err == nil {
|
|
ticket.DueDate = &parsed
|
|
} else if parsed, err := time.Parse("2006-01-02", req.DueDate); err == nil {
|
|
ticket.DueDate = &parsed
|
|
}
|
|
}
|
|
|
|
created, err := s.Store.CreateTicket(ticket, actor)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
s.writeJSON(w, http.StatusCreated, map[string]any{
|
|
"status": "ok",
|
|
"ticket": created,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleGetTicket(w http.ResponseWriter, r *http.Request) {
|
|
id := chi.URLParam(r, "id")
|
|
t, err := s.Store.GetTicket(id)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusNotFound, map[string]string{"error": "Ticket not found"})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"ticket": t,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleDeleteTicket(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to delete tickets"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
if err := s.Store.DeleteTicket(id, actor); err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"message": fmt.Sprintf("Ticket %s deleted successfully", id),
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleAddRemark(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to post remarks"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
|
|
var req struct {
|
|
Text string `json:"text"`
|
|
Body string `json:"body"`
|
|
Type string `json:"type"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid request payload"})
|
|
return
|
|
}
|
|
text := strings.TrimSpace(req.Text)
|
|
if text == "" {
|
|
text = strings.TrimSpace(req.Body)
|
|
}
|
|
if text == "" {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Remark text is required"})
|
|
return
|
|
}
|
|
if req.Type == "" {
|
|
req.Type = "comment"
|
|
}
|
|
|
|
t, err := s.Store.AddRemark(id, actor, req.Type, text)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"ticket": t,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleHoldTicket(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to place tickets on hold"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
|
|
var req struct {
|
|
Reason string `json:"reason"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.Reason) == "" {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Holding reason is required"})
|
|
return
|
|
}
|
|
|
|
t, err := s.Store.HoldTicket(id, actor, req.Reason)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"ticket": t,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleResumeTicket(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to resume tickets"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
|
|
var req struct {
|
|
Remarks string `json:"remarks"`
|
|
}
|
|
_ = json.NewDecoder(r.Body).Decode(&req)
|
|
|
|
t, err := s.Store.ResumeTicket(id, actor, req.Remarks)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"ticket": t,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleReopenTicket(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to reopen tickets"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
|
|
var req struct {
|
|
Remarks string `json:"remarks"`
|
|
}
|
|
_ = json.NewDecoder(r.Body).Decode(&req)
|
|
|
|
t, err := s.Store.ReopenTicket(id, actor, req.Remarks)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"ticket": t,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleCompleteTicket(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to complete tickets"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
|
|
var req struct {
|
|
Remarks string `json:"remarks"`
|
|
Resolution string `json:"resolution"`
|
|
}
|
|
_ = json.NewDecoder(r.Body).Decode(&req)
|
|
remarks := strings.TrimSpace(req.Remarks)
|
|
if remarks == "" {
|
|
remarks = strings.TrimSpace(req.Resolution)
|
|
}
|
|
if remarks == "" {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Completion resolution remarks are required"})
|
|
return
|
|
}
|
|
|
|
t, err := s.Store.CompleteTicket(id, actor, remarks)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"ticket": t,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleArchiveTicket(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to archive tickets"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
t, err := s.Store.ArchiveTicket(id, actor)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"message": "Ticket archived successfully",
|
|
"ticket": t,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleUnarchiveTicket(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to unarchive tickets"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
t, err := s.Store.UnarchiveTicket(id, actor)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"message": "Ticket restored from archive",
|
|
"ticket": t,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleChangePriority(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to update ticket priority"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
|
|
var req struct {
|
|
Priority string `json:"priority"`
|
|
Note string `json:"note"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.Priority) == "" {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Priority is required"})
|
|
return
|
|
}
|
|
|
|
t, err := s.Store.ChangePriority(id, actor, req.Priority, req.Note)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"ticket": t,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleReassignTicket(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to reassign tickets"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
|
|
var req struct {
|
|
Assignee string `json:"assignee"`
|
|
AssigneeUsername string `json:"assignee_username"`
|
|
Note string `json:"note"`
|
|
}
|
|
_ = json.NewDecoder(r.Body).Decode(&req)
|
|
assignee := strings.TrimSpace(req.Assignee)
|
|
if assignee == "" {
|
|
assignee = strings.TrimSpace(req.AssigneeUsername)
|
|
}
|
|
if assignee == "" {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "New assignee username is required"})
|
|
return
|
|
}
|
|
|
|
t, err := s.Store.ReassignTicket(id, actor, assignee, req.Note)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"ticket": t,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleGetNotifications(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"notifications": []Notification{},
|
|
"unread_count": 0,
|
|
})
|
|
return
|
|
}
|
|
notifs := s.Store.GetNotifications(actor.Username)
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"notifications": notifs,
|
|
"unread_count": countUnread(notifs),
|
|
})
|
|
}
|
|
|
|
func countUnread(list []Notification) int {
|
|
cnt := 0
|
|
for _, n := range list {
|
|
if !n.Read {
|
|
cnt++
|
|
}
|
|
}
|
|
return cnt
|
|
}
|
|
|
|
func (s *Server) handleMarkNotificationsRead(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor != nil {
|
|
s.Store.MarkNotificationsRead(actor.Username)
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
|
}
|
|
|
|
func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
all := s.Store.ListTickets("", "", "", "", "", "", "")
|
|
stats := map[string]int{
|
|
"total": len(all),
|
|
"open": 0,
|
|
"in_progress": 0,
|
|
"on_hold": 0,
|
|
"completed": 0,
|
|
"closed": 0,
|
|
"critical": 0,
|
|
"general": 0,
|
|
"application": 0,
|
|
"my_assigned": 0,
|
|
"my_created": 0,
|
|
"my_held": 0,
|
|
"my_completed": 0,
|
|
}
|
|
for _, t := range all {
|
|
if strings.ToLower(t.TicketType) == "general" {
|
|
stats["general"]++
|
|
} else {
|
|
stats["application"]++
|
|
}
|
|
switch strings.ToLower(t.Status) {
|
|
case "open":
|
|
stats["open"]++
|
|
case "in_progress":
|
|
stats["in_progress"]++
|
|
case "on_hold":
|
|
stats["on_hold"]++
|
|
case "completed":
|
|
stats["completed"]++
|
|
case "closed":
|
|
stats["closed"]++
|
|
}
|
|
if strings.ToLower(t.Priority) == "critical" {
|
|
stats["critical"]++
|
|
}
|
|
|
|
if actor != nil {
|
|
if strings.EqualFold(t.AssignedTo, actor.Username) {
|
|
stats["my_assigned"]++
|
|
if strings.ToLower(t.Status) == "on_hold" {
|
|
stats["my_held"]++
|
|
} else if strings.ToLower(t.Status) == "completed" {
|
|
stats["my_completed"]++
|
|
}
|
|
}
|
|
if strings.EqualFold(t.CreatedBy, actor.Username) {
|
|
stats["my_created"]++
|
|
}
|
|
}
|
|
}
|
|
s.writeJSON(w, http.StatusOK, stats)
|
|
}
|
|
|
|
func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to upload files"})
|
|
return
|
|
}
|
|
|
|
// Max 32MB file upload
|
|
if err := r.ParseMultipartForm(32 << 20); err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "File exceeds maximum size (32MB)"})
|
|
return
|
|
}
|
|
|
|
file, header, err := r.FormFile("file")
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Missing file in request"})
|
|
return
|
|
}
|
|
defer file.Close()
|
|
|
|
uploadsDir := filepath.Join(s.Store.GetDataDir(), "uploads")
|
|
if err := os.MkdirAll(uploadsDir, 0755); err != nil {
|
|
s.writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Failed to create uploads directory"})
|
|
return
|
|
}
|
|
|
|
ext := filepath.Ext(header.Filename)
|
|
extLower := strings.ToLower(ext)
|
|
allowed := map[string]bool{
|
|
".png": true, ".jpg": true, ".jpeg": true, ".webp": true, ".gif": true,
|
|
".txt": true, ".log": true, ".pdf": true, ".json": true,
|
|
}
|
|
if !allowed[extLower] {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid file type. Allowed formats: PNG, JPG, JPEG, WEBP, GIF, TXT, LOG, PDF, JSON"})
|
|
return
|
|
}
|
|
|
|
safeBase := strings.Map(func(r rune) rune {
|
|
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' || r == '.' {
|
|
return r
|
|
}
|
|
return '_'
|
|
}, filepath.Base(header.Filename))
|
|
|
|
savedFileName := fmt.Sprintf("%s_%s", uuid.New().String()[:8], safeBase)
|
|
destPath := filepath.Join(uploadsDir, savedFileName)
|
|
|
|
dest, err := os.Create(destPath)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Failed to save file"})
|
|
return
|
|
}
|
|
defer dest.Close()
|
|
|
|
size, err := io.Copy(dest, file)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Failed to write file"})
|
|
return
|
|
}
|
|
|
|
fileType := "file"
|
|
if extLower == ".png" || extLower == ".jpg" || extLower == ".jpeg" || extLower == ".webp" || extLower == ".gif" {
|
|
fileType = "image"
|
|
}
|
|
|
|
att := Attachment{
|
|
ID: uuid.New().String(),
|
|
Name: header.Filename,
|
|
URL: "/khira/uploads/" + savedFileName,
|
|
Size: size,
|
|
Type: fileType,
|
|
UploadedBy: actor.Name,
|
|
CreatedAt: time.Now(),
|
|
}
|
|
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"attachment": att,
|
|
"url": att.URL,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleAddAttachment(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to add attachments"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
|
|
if strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data") {
|
|
if err := r.ParseMultipartForm(32 << 20); err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "File exceeds maximum size (32MB)"})
|
|
return
|
|
}
|
|
file, header, err := r.FormFile("file")
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Missing file in request"})
|
|
return
|
|
}
|
|
defer file.Close()
|
|
|
|
uploadsDir := filepath.Join(s.Store.GetDataDir(), "uploads")
|
|
_ = os.MkdirAll(uploadsDir, 0755)
|
|
|
|
ext := filepath.Ext(header.Filename)
|
|
safeBase := strings.Map(func(r rune) rune {
|
|
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' || r == '.' {
|
|
return r
|
|
}
|
|
return '_'
|
|
}, filepath.Base(header.Filename))
|
|
|
|
savedFileName := fmt.Sprintf("%s_%s", uuid.New().String()[:8], safeBase)
|
|
destPath := filepath.Join(uploadsDir, savedFileName)
|
|
|
|
dest, err := os.Create(destPath)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Failed to save file"})
|
|
return
|
|
}
|
|
defer dest.Close()
|
|
|
|
size, err := io.Copy(dest, file)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Failed to write file"})
|
|
return
|
|
}
|
|
|
|
fileType := "file"
|
|
extLower := strings.ToLower(ext)
|
|
if extLower == ".png" || extLower == ".jpg" || extLower == ".jpeg" || extLower == ".webp" || extLower == ".gif" || extLower == ".svg" {
|
|
fileType = "image"
|
|
}
|
|
|
|
att := Attachment{
|
|
ID: uuid.New().String(),
|
|
Name: header.Filename,
|
|
URL: "/khira/uploads/" + savedFileName,
|
|
Size: size,
|
|
Type: fileType,
|
|
UploadedBy: actor.Name,
|
|
CreatedAt: time.Now(),
|
|
}
|
|
|
|
t, err := s.Store.AddAttachment(id, actor, att)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"ticket": t,
|
|
})
|
|
return
|
|
}
|
|
|
|
var att Attachment
|
|
if err := json.NewDecoder(r.Body).Decode(&att); err != nil || att.Name == "" || att.URL == "" {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid attachment data"})
|
|
return
|
|
}
|
|
|
|
t, err := s.Store.AddAttachment(id, actor, att)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"ticket": t,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleAddLink(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to add links"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
|
|
var req struct {
|
|
Link string `json:"link"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.Link) == "" {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Valid URL link is required"})
|
|
return
|
|
}
|
|
|
|
t, err := s.Store.AddLink(id, actor, req.Link)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"ticket": t,
|
|
})
|
|
}
|
|
|
|
// ----------------- Error Tracking Handlers -----------------
|
|
|
|
|
|
func (s *Server) handleListErrors(w http.ResponseWriter, r *http.Request) {
|
|
status := r.URL.Query().Get("status")
|
|
severity := r.URL.Query().Get("severity")
|
|
app := r.URL.Query().Get("app")
|
|
query := r.URL.Query().Get("q")
|
|
|
|
list := s.Store.ListErrors(status, severity, app, query)
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"errors": list,
|
|
"count": len(list),
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleGetError(w http.ResponseWriter, r *http.Request) {
|
|
id := chi.URLParam(r, "id")
|
|
errItem, err := s.Store.GetError(id)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusNotFound, map[string]string{"error": "Error not found"})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"error": errItem,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleErrorStats(w http.ResponseWriter, r *http.Request) {
|
|
stats := s.Store.GetErrorStats()
|
|
s.writeJSON(w, http.StatusOK, stats)
|
|
}
|
|
|
|
func (s *Server) handleIngestError(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
var req struct {
|
|
AppError
|
|
AssignedTo string `json:"assigned_to"`
|
|
AssigneeUsername string `json:"assignee_username"`
|
|
Notes string `json:"notes"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid request payload"})
|
|
return
|
|
}
|
|
|
|
saved, err := s.Store.IngestError(&req.AppError, actor)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
assignee := strings.TrimSpace(req.AssignedTo)
|
|
if assignee == "" {
|
|
assignee = strings.TrimSpace(req.AssigneeUsername)
|
|
}
|
|
|
|
var ticket *Ticket
|
|
if !saved.IsDraft && assignee != "" && actor != nil {
|
|
title := fmt.Sprintf("[%s] %s: %s", saved.AppName, saved.ExceptionType, saved.Message)
|
|
if len(title) > 80 {
|
|
title = title[:77] + "..."
|
|
}
|
|
t, errItem, errEsc := s.Store.EscalateErrorToTicket(saved.ID, title, assignee, saved.Severity, req.Notes, actor)
|
|
if errEsc == nil {
|
|
ticket = t
|
|
saved = errItem
|
|
}
|
|
}
|
|
|
|
s.writeJSON(w, http.StatusCreated, map[string]any{
|
|
"status": "ok",
|
|
"error": saved,
|
|
"ticket": ticket,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleUpdateError(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to update errors"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
|
|
var req struct {
|
|
AppError
|
|
AssignedTo string `json:"assigned_to"`
|
|
AssigneeUsername string `json:"assignee_username"`
|
|
Notes string `json:"notes"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid request payload"})
|
|
return
|
|
}
|
|
|
|
assignee := strings.TrimSpace(req.AssignedTo)
|
|
if assignee == "" {
|
|
assignee = strings.TrimSpace(req.AssigneeUsername)
|
|
}
|
|
if assignee != "" {
|
|
req.AppError.AssignedTo = assignee
|
|
}
|
|
|
|
updated, err := s.Store.UpdateError(id, &req.AppError, actor)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
var ticket *Ticket
|
|
if !updated.IsDraft && assignee != "" && updated.LinkedTicketID == "" {
|
|
title := fmt.Sprintf("[%s] %s: %s", updated.AppName, updated.ExceptionType, updated.Message)
|
|
if len(title) > 80 {
|
|
title = title[:77] + "..."
|
|
}
|
|
t, errItem, errEsc := s.Store.EscalateErrorToTicket(updated.ID, title, assignee, updated.Severity, req.Notes, actor)
|
|
if errEsc == nil {
|
|
ticket = t
|
|
updated = errItem
|
|
}
|
|
}
|
|
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"error": updated,
|
|
"ticket": ticket,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleDeleteError(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to delete errors"})
|
|
return
|
|
}
|
|
if !s.isAdmin(actor) && actor.Role != string(RoleTester) && actor.Role != string(RoleLead) {
|
|
s.writeJSON(w, http.StatusForbidden, map[string]string{"error": "Only administrators, leads, and testers can delete error telemetry"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
if err := s.Store.DeleteError(id, actor); err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"id": id,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleUpdateErrorStatus(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to update error status"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
|
|
var req struct {
|
|
Status string `json:"status"`
|
|
Notes string `json:"notes"`
|
|
ResolutionNotes string `json:"resolution_notes"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.Status) == "" {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Valid status is required"})
|
|
return
|
|
}
|
|
|
|
notes := strings.TrimSpace(req.Notes)
|
|
if notes == "" {
|
|
notes = strings.TrimSpace(req.ResolutionNotes)
|
|
}
|
|
|
|
status := ErrorStatus(strings.ToLower(strings.TrimSpace(req.Status)))
|
|
switch status {
|
|
case ErrorStatusUnresolved, ErrorStatusInvestigating, ErrorStatusResolved, ErrorStatusIgnored:
|
|
// valid
|
|
default:
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid status value. Allowed: unresolved, investigating, resolved, ignored"})
|
|
return
|
|
}
|
|
|
|
updated, err := s.Store.UpdateErrorStatus(id, status, notes, actor)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"error": updated,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleEscalateError(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to escalate errors"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
|
|
var req struct {
|
|
Title string `json:"title"`
|
|
AssignedTo string `json:"assigned_to"`
|
|
AssigneeUsername string `json:"assignee_username"`
|
|
Priority string `json:"priority"`
|
|
Notes string `json:"notes"`
|
|
}
|
|
_ = json.NewDecoder(r.Body).Decode(&req)
|
|
|
|
assignedTo := strings.TrimSpace(req.AssignedTo)
|
|
if assignedTo == "" {
|
|
assignedTo = strings.TrimSpace(req.AssigneeUsername)
|
|
}
|
|
|
|
ticket, errItem, err := s.Store.EscalateErrorToTicket(id, req.Title, assignedTo, req.Priority, req.Notes, actor)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"ticket": ticket,
|
|
"error": errItem,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleArchiveError(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to archive errors"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
errItem, err := s.Store.ArchiveError(id, actor)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"message": "Error archived successfully",
|
|
"error": errItem,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleUnarchiveError(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if actor == nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Please sign in to unarchive errors"})
|
|
return
|
|
}
|
|
id := chi.URLParam(r, "id")
|
|
errItem, err := s.Store.UnarchiveError(id, actor)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"message": "Error restored from archive",
|
|
"error": errItem,
|
|
})
|
|
}
|
|
|
|
func (s *Server) isAdmin(actor *User) bool {
|
|
if actor == nil {
|
|
return false
|
|
}
|
|
return strings.EqualFold(actor.Username, "admin") ||
|
|
actor.Role == string(RoleLead) ||
|
|
strings.EqualFold(actor.Role, "team_lead") ||
|
|
strings.EqualFold(actor.Role, "lead")
|
|
}
|
|
|
|
func (s *Server) handleDBSync(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if !s.isAdmin(actor) {
|
|
s.writeJSON(w, http.StatusForbidden, map[string]string{"error": "Admin access required to sync backup database"})
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
Password string `json:"password"`
|
|
}
|
|
_ = json.NewDecoder(r.Body).Decode(&req)
|
|
if strings.TrimSpace(req.Password) != "" {
|
|
_, err := s.Store.AuthenticateUser(actor.Username, req.Password)
|
|
if err != nil && !strings.EqualFold(actor.Username, "admin") {
|
|
_, err = s.Store.AuthenticateUser("admin", req.Password)
|
|
}
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Invalid administrator password"})
|
|
return
|
|
}
|
|
}
|
|
|
|
res, err := s.Store.SyncBackupDB()
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, res)
|
|
}
|
|
|
|
func (s *Server) handleDBRollback(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if !s.isAdmin(actor) {
|
|
s.writeJSON(w, http.StatusForbidden, map[string]string{"error": "Admin access required to rollback database"})
|
|
return
|
|
}
|
|
|
|
var req struct {
|
|
Password string `json:"password"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || strings.TrimSpace(req.Password) == "" {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Admin password is required"})
|
|
return
|
|
}
|
|
|
|
_, err := s.Store.AuthenticateUser(actor.Username, req.Password)
|
|
if err != nil && !strings.EqualFold(actor.Username, "admin") {
|
|
_, err = s.Store.AuthenticateUser("admin", req.Password)
|
|
}
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Invalid administrator password"})
|
|
return
|
|
}
|
|
|
|
res, err := s.Store.RollbackFromBackupDB()
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
s.writeJSON(w, http.StatusOK, res)
|
|
}
|
|
|
|
func (s *Server) handleDBStatus(w http.ResponseWriter, r *http.Request) {
|
|
actor := s.getActor(r)
|
|
if !s.isAdmin(actor) {
|
|
s.writeJSON(w, http.StatusForbidden, map[string]string{"error": "Admin access required"})
|
|
return
|
|
}
|
|
res := s.Store.GetDBStatus()
|
|
s.writeJSON(w, http.StatusOK, res)
|
|
}
|