1157 lines
33 KiB
Go
1157 lines
33 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
|
|
}
|
|
|
|
func NewServer(store *Store) *Server {
|
|
return &Server{Store: store}
|
|
}
|
|
|
|
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 custom header (useful for client SPA / API calls)
|
|
username := r.Header.Get("X-Khira-User")
|
|
if username == "" {
|
|
// 2. Check cookie
|
|
if cookie, err := r.Cookie("khira_session_user"); err == nil && cookie.Value != "" {
|
|
username = cookie.Value
|
|
}
|
|
}
|
|
if username != "" {
|
|
if u, err := s.Store.GetUser(username); err == 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) {
|
|
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.Post("/auth/register", s.handleRegister)
|
|
api.Post("/auth/login", s.handleLogin)
|
|
api.Post("/auth/logout", s.handleLogout)
|
|
api.Get("/auth/me", s.handleMe)
|
|
api.Put("/auth/profile", s.handleUpdateProfile)
|
|
api.Post("/auth/profile", s.handleUpdateProfile)
|
|
|
|
// Users
|
|
api.Get("/users", s.handleListUsers)
|
|
|
|
// 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}/complete", s.handleCompleteTicket)
|
|
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}/status", s.handleUpdateErrorStatus)
|
|
api.Post("/errors/{id}/status", s.handleUpdateErrorStatus)
|
|
api.Post("/errors/{id}/escalate", s.handleEscalateError)
|
|
|
|
// 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)
|
|
})
|
|
}
|
|
|
|
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"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid request payload"})
|
|
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
|
|
}
|
|
|
|
http.SetCookie(w, &http.Cookie{
|
|
Name: "khira_session_user",
|
|
Value: u.Username,
|
|
Path: "/",
|
|
MaxAge: 86400 * 30, // 30 days
|
|
HttpOnly: false,
|
|
SameSite: http.SameSiteLaxMode,
|
|
})
|
|
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"user": u.Public(),
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
Username string `json:"username"`
|
|
Password string `json:"password"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid request payload"})
|
|
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
|
|
}
|
|
|
|
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",
|
|
"user": u.Public(),
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
|
|
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) 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"`
|
|
}
|
|
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 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) handleListTickets(w http.ResponseWriter, r *http.Request) {
|
|
status := r.URL.Query().Get("status")
|
|
priority := r.URL.Query().Get("priority")
|
|
assignee := r.URL.Query().Get("assignee")
|
|
creator := r.URL.Query().Get("creator")
|
|
role := r.URL.Query().Get("role")
|
|
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, assignee, creator, role, ticketType, q)
|
|
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"`
|
|
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)
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|
|
|
|
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,
|
|
Links: req.Links,
|
|
}
|
|
|
|
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) 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) 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)
|
|
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(),
|
|
}
|
|
|
|
s.writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"attachment": att,
|
|
})
|
|
}
|
|
|
|
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 AppError
|
|
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, actor)
|
|
if err != nil {
|
|
s.writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
s.writeJSON(w, http.StatusCreated, map[string]any{
|
|
"status": "ok",
|
|
"error": saved,
|
|
})
|
|
}
|
|
|
|
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) 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"`
|
|
}
|
|
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.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)
|
|
}
|