1592 lines
47 KiB
Go
1592 lines
47 KiB
Go
package khira
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type Store struct {
|
|
mu sync.RWMutex
|
|
dataDir string
|
|
users map[string]*User
|
|
tickets map[string]*Ticket
|
|
errors map[string]*AppError
|
|
notifications map[string][]Notification
|
|
ticketSeq int
|
|
errorSeq int
|
|
}
|
|
|
|
func hashPassword(pass string) string {
|
|
sum := sha256.Sum256([]byte("khira_salt_2026:" + pass))
|
|
return fmt.Sprintf("%x", sum)
|
|
}
|
|
|
|
func NewStore(dataDir string) (*Store, error) {
|
|
if err := os.MkdirAll(dataDir, 0755); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
s := &Store{
|
|
dataDir: dataDir,
|
|
users: make(map[string]*User),
|
|
tickets: make(map[string]*Ticket),
|
|
errors: make(map[string]*AppError),
|
|
notifications: make(map[string][]Notification),
|
|
ticketSeq: 100,
|
|
errorSeq: 200,
|
|
}
|
|
|
|
if err := s.load(); err != nil {
|
|
// if error loading, start fresh with seed
|
|
s.seedData()
|
|
_ = s.save()
|
|
} else if len(s.users) == 0 || len(s.errors) == 0 {
|
|
s.seedData()
|
|
_ = s.save()
|
|
}
|
|
|
|
return s, nil
|
|
}
|
|
|
|
func (s *Store) seedData() {
|
|
now := time.Now()
|
|
|
|
// Seed team members across roles
|
|
defaultUsers := []struct {
|
|
username string
|
|
name string
|
|
pass string
|
|
role Role
|
|
avatar string
|
|
}{
|
|
{"alice", "Alice Sharma", "alice123", RoleFrontend, "👩💻"},
|
|
{"bob", "Bob Anderson", "bob123", RoleBackend, "👨💻"},
|
|
{"charlie", "Charlie Patel", "charlie123", RoleTester, "🕵️♂️"},
|
|
{"admin", "System Administrator", "admin123", RoleLead, "⚡"},
|
|
}
|
|
|
|
for _, u := range defaultUsers {
|
|
s.users[u.username] = &User{
|
|
ID: uuid.New().String(),
|
|
Username: u.username,
|
|
Name: u.name,
|
|
PasswordHash: hashPassword(u.pass),
|
|
Role: string(u.role),
|
|
RoleDisplay: u.role.DisplayName(),
|
|
Avatar: u.avatar,
|
|
CreatedAt: now.Add(-72 * time.Hour),
|
|
}
|
|
}
|
|
|
|
// Seed realistic sample tickets
|
|
t1 := &Ticket{
|
|
ID: "KHR-101",
|
|
TicketType: "application",
|
|
Title: "Hair Color Changer 500 Error when mask_image is omitted",
|
|
AppName: "Creator Suite Web",
|
|
Version: "v2.4.1",
|
|
FeatureName: "Hair Color Changer",
|
|
APIKey: "Stable_Diffusion_Hair_Color_Changer_And_Hair_Style_Changer",
|
|
IssueType: "api_failure",
|
|
Priority: string(PriorityCritical),
|
|
Description: "Calling /flux_fill/hair_color_changer/image/ without providing mask_image throws 500 Internal Server Error instead of falling back to Sapiens hair segmentation.",
|
|
AssistanceRequired: "Endpoint Debugging",
|
|
AdditionalInfo: "cURL test:\ncurl -X POST https://apigp0006.creinnovations.in/apis/flxf/flux_fill/hair_color_changer/image/ -F [email protected] -F colorId=C1 -F secretKey=abcdef\nResponse: 500 Internal Server Error (KeyError: 'mask_image')",
|
|
CreatedBy: "charlie",
|
|
CreatedByName: "Charlie Patel",
|
|
CreatedByRole: "Tester",
|
|
AssignedTo: "bob",
|
|
AssignedToName: "Bob Anderson",
|
|
AssignedToRole: "Backend Dev",
|
|
Status: string(StatusInProgress),
|
|
Remarks: []Remark{
|
|
{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: "charlie",
|
|
AuthorName: "Charlie Patel",
|
|
AuthorRole: "Tester",
|
|
Type: "created",
|
|
Text: "Reported issue during v2.4.1 regression testing suite.",
|
|
CreatedAt: now.Add(-6 * time.Hour),
|
|
},
|
|
{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: "bob",
|
|
AuthorName: "Bob Anderson",
|
|
AuthorRole: "Backend Dev",
|
|
Type: "comment",
|
|
Text: "Investigating the handler in Python worker. The optional mask check had a missing None default.",
|
|
CreatedAt: now.Add(-4 * time.Hour),
|
|
},
|
|
},
|
|
CreatedAt: now.Add(-6 * time.Hour),
|
|
UpdatedAt: now.Add(-4 * time.Hour),
|
|
}
|
|
|
|
t2 := &Ticket{
|
|
ID: "KHR-102",
|
|
TicketType: "application",
|
|
Title: "Face Swapper UI container overflow on high-DPI screens",
|
|
AppName: "Unified Dashboard Client",
|
|
Version: "v2.4.0",
|
|
FeatureName: "InsightFace Swap",
|
|
APIKey: "Face_Swapper",
|
|
IssueType: "ui_glitch",
|
|
Priority: string(PriorityHigh),
|
|
Status: string(StatusOpen),
|
|
Description: "The preview container overflows horizontally when two 4K source images are selected for couple face swapping.",
|
|
AssistanceRequired: "UI Layout Fix",
|
|
AdditionalInfo: "Tested on Chrome 124 / 4K resolution (3840x2160, 150% scaling).",
|
|
CreatedBy: "charlie",
|
|
CreatedByName: "Charlie Patel",
|
|
CreatedByRole: "Tester",
|
|
AssignedTo: "alice",
|
|
AssignedToName: "Alice Sharma",
|
|
AssignedToRole: "Frontend Dev",
|
|
Remarks: []Remark{
|
|
{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: "charlie",
|
|
AuthorName: "Charlie Patel",
|
|
AuthorRole: "Tester",
|
|
Type: "created",
|
|
Text: "Opened bug with screenshots attached in test report.",
|
|
CreatedAt: now.Add(-12 * time.Hour),
|
|
},
|
|
},
|
|
CreatedAt: now.Add(-12 * time.Hour),
|
|
UpdatedAt: now.Add(-12 * time.Hour),
|
|
}
|
|
|
|
t3 := &Ticket{
|
|
ID: "KHR-103",
|
|
TicketType: "application",
|
|
Title: "Waiting on FLUX.1 Fill GPU cluster expansion for batch inpainting",
|
|
AppName: "Batch Inpaint Service",
|
|
Version: "v2.5.0-rc1",
|
|
FeatureName: "Batch Inpainting",
|
|
APIKey: "Flux_Dress_Changer",
|
|
IssueType: "performance",
|
|
Priority: string(PriorityMedium),
|
|
Status: string(StatusOnHold),
|
|
Description: "Batch dress changer requests queue up when 10+ concurrent requests are received. Need additional GPU worker before benchmark signoff.",
|
|
AssistanceRequired: "Investigation",
|
|
AdditionalInfo: "Average queue time: 48s per request.",
|
|
CreatedBy: "bob",
|
|
CreatedByName: "Bob Anderson",
|
|
CreatedByRole: "Backend Dev",
|
|
AssignedTo: "admin",
|
|
AssignedToName: "System Administrator",
|
|
AssignedToRole: "Team Lead",
|
|
HoldReason: "Blocked waiting for DevOps GPU node provisioning on port 18001.",
|
|
HeldBy: "bob",
|
|
HeldAt: &now,
|
|
Remarks: []Remark{
|
|
{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: "bob",
|
|
AuthorName: "Bob Anderson",
|
|
AuthorRole: "Backend Dev",
|
|
Type: "hold",
|
|
Text: "Holding ticket until Cloud Infra team provisions second RTX 4090 GPU node.",
|
|
CreatedAt: now.Add(-2 * time.Hour),
|
|
},
|
|
},
|
|
CreatedAt: now.Add(-24 * time.Hour),
|
|
UpdatedAt: now.Add(-2 * time.Hour),
|
|
}
|
|
|
|
t4 := &Ticket{
|
|
ID: "KHR-104",
|
|
TicketType: "application",
|
|
Title: "Align SDXL Parameter types and default resolutions in documentation",
|
|
AppName: "FastAPI Documentation",
|
|
Version: "v2.4.0",
|
|
FeatureName: "Documentation & Schemas",
|
|
APIKey: "Stable_Diffusion_Text_To_Image_Model",
|
|
IssueType: "schema_mismatch",
|
|
Priority: string(PriorityHigh),
|
|
Status: string(StatusCompleted),
|
|
Description: "Parameters for SDXL models in data.json were defaulting to 720x720 instead of the documented 1024x1024.",
|
|
AssistanceRequired: "Schema Update",
|
|
AdditionalInfo: "Verified against FASTAPI_BACKEND_API_DOCUMENTATION.md section 5.",
|
|
CreatedBy: "alice",
|
|
CreatedByName: "Alice Sharma",
|
|
CreatedByRole: "Frontend Dev",
|
|
AssignedTo: "bob",
|
|
AssignedToName: "Bob Anderson",
|
|
AssignedToRole: "Backend Dev",
|
|
CompletionRemarks: "Updated data.json schemas, reconciled 21 parameter constraints, verified live at /docs/data.json.",
|
|
CompletedBy: "bob",
|
|
CompletedAt: &now,
|
|
Remarks: []Remark{
|
|
{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: "alice",
|
|
AuthorName: "Alice Sharma",
|
|
AuthorRole: "Frontend Dev",
|
|
Type: "created",
|
|
Text: "Flagged parameter mismatch between backend doc and UI.",
|
|
CreatedAt: now.Add(-48 * time.Hour),
|
|
},
|
|
{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: "bob",
|
|
AuthorName: "Bob Anderson",
|
|
AuthorRole: "Backend Dev",
|
|
Type: "complete",
|
|
Text: "Completed: Synced all schemas, resolved 21 constraints, tested with live validation.",
|
|
CreatedAt: now.Add(-1 * time.Hour),
|
|
},
|
|
},
|
|
CreatedAt: now.Add(-48 * time.Hour),
|
|
UpdatedAt: now.Add(-1 * time.Hour),
|
|
}
|
|
|
|
t5 := &Ticket{
|
|
ID: "KHR-105",
|
|
TicketType: "general",
|
|
GeneralCategory: "DevOps & Infrastructure",
|
|
Department: "Compute Cluster Ops",
|
|
Title: "Provision dedicated NVIDIA A100 (80GB) node on private GPU cluster",
|
|
Priority: string(PriorityCritical),
|
|
Status: string(StatusInProgress),
|
|
Description: "Batch diffusion workers require an 80GB VRAM GPU instance to handle 2048x2048 high-res FLUX inpainting without CUDA OOM crashes. Please spin up node gpu-worker-08 and bind it to private subnet.",
|
|
AssistanceRequired: "Infrastructure Provisioning & Subnet Attachment",
|
|
AdditionalInfo: "Instance spec:\n- GPU: 1x NVIDIA A100-SXM4-80GB\n- RAM: 128GB\n- NVMe Scratch: 500GB mounted at /mnt/fast-cache\n- Docker + NVIDIA Container Toolkit v1.14 installed",
|
|
CreatedBy: "bob",
|
|
CreatedByName: "Bob Anderson",
|
|
CreatedByRole: "Backend Dev",
|
|
AssignedTo: "admin",
|
|
AssignedToName: "System Administrator",
|
|
AssignedToRole: "Team Lead",
|
|
Remarks: []Remark{
|
|
{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: "bob",
|
|
AuthorName: "Bob Anderson",
|
|
AuthorRole: "Backend Dev",
|
|
Type: "created",
|
|
Text: "Created general infrastructure provisioning ticket.",
|
|
CreatedAt: now.Add(-10 * time.Hour),
|
|
},
|
|
{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: "admin",
|
|
AuthorName: "System Administrator",
|
|
AuthorRole: "Team Lead",
|
|
Type: "comment",
|
|
Text: "Reserved instance quota on cloud provider. Running Ansible provisioning playbook now.",
|
|
CreatedAt: now.Add(-3 * time.Hour),
|
|
},
|
|
},
|
|
CreatedAt: now.Add(-10 * time.Hour),
|
|
UpdatedAt: now.Add(-3 * time.Hour),
|
|
}
|
|
|
|
t6 := &Ticket{
|
|
ID: "KHR-106",
|
|
TicketType: "general",
|
|
GeneralCategory: "Access & Permissions",
|
|
Department: "Security & IAM",
|
|
Title: "Rotate staging API gateway bearer tokens and update QA automation secrets",
|
|
Priority: string(PriorityMedium),
|
|
Status: string(StatusOpen),
|
|
Description: "Quarterly secret token rotation for staging API gateway proxies. Please issue new rotation tokens and update team CI/CD pipeline secrets.",
|
|
AssistanceRequired: "Secret Rotation & CI/CD Vault Update",
|
|
AdditionalInfo: "Endpoints affected:\n- https://apigp0006.creinnovations.in/apis/*\n- Staging ingress proxy on port 10000",
|
|
CreatedBy: "charlie",
|
|
CreatedByName: "Charlie Patel",
|
|
CreatedByRole: "Tester",
|
|
AssignedTo: "alice",
|
|
AssignedToName: "Alice Sharma",
|
|
AssignedToRole: "Frontend Dev",
|
|
Remarks: []Remark{
|
|
{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: "charlie",
|
|
AuthorName: "Charlie Patel",
|
|
AuthorRole: "Tester",
|
|
Type: "created",
|
|
Text: "Opened quarterly token rotation ticket.",
|
|
CreatedAt: now.Add(-16 * time.Hour),
|
|
},
|
|
},
|
|
CreatedAt: now.Add(-16 * time.Hour),
|
|
UpdatedAt: now.Add(-16 * time.Hour),
|
|
}
|
|
|
|
s.tickets[t1.ID] = t1
|
|
s.tickets[t2.ID] = t2
|
|
s.tickets[t3.ID] = t3
|
|
s.tickets[t4.ID] = t4
|
|
s.tickets[t5.ID] = t5
|
|
s.tickets[t6.ID] = t6
|
|
s.ticketSeq = 106
|
|
|
|
// Seed notifications
|
|
s.notifications["bob"] = []Notification{
|
|
{
|
|
ID: uuid.New().String(),
|
|
UserID: "bob",
|
|
TicketID: "KHR-101",
|
|
Title: "New Ticket Assigned",
|
|
Message: "Charlie assigned KHR-101 (Critical: Hair Color Changer 500 Error) to you.",
|
|
Type: "assignment",
|
|
Read: false,
|
|
CreatedAt: now.Add(-6 * time.Hour),
|
|
},
|
|
}
|
|
s.notifications["alice"] = []Notification{
|
|
{
|
|
ID: uuid.New().String(),
|
|
UserID: "alice",
|
|
TicketID: "KHR-102",
|
|
Title: "New Ticket Assigned",
|
|
Message: "Charlie assigned KHR-102 (High: Face Swapper UI container overflow) to you.",
|
|
Type: "assignment",
|
|
Read: false,
|
|
CreatedAt: now.Add(-12 * time.Hour),
|
|
},
|
|
}
|
|
|
|
// Seed Application Errors for Error Tracking
|
|
err1 := &AppError{
|
|
ID: "ERR-201",
|
|
Fingerprint: "ZeroDivisionError:mask_processor:142",
|
|
AppName: "Unified Dashboard Client",
|
|
Version: "v2.5.0",
|
|
Environment: "production",
|
|
Service: "Hair Color Changer",
|
|
Endpoint: "POST /apis/flxk/hair-color-change",
|
|
ExceptionType: "ZeroDivisionError",
|
|
Message: "division by zero: normalized alpha matte has zero total density during boundary feathering",
|
|
StackTrace: `Traceback (most recent call last):
|
|
File "workers/hair_service.py", line 184, in handle_hair_color_request
|
|
processed_mask = feather_edges(mask_tensor, radius=5)
|
|
File "utils/mask_processor.py", line 142, in feather_edges
|
|
normalized = (alpha - alpha.min()) / (alpha.max() - alpha.min())
|
|
ZeroDivisionError: division by zero`,
|
|
Severity: string(SeverityHigh),
|
|
Status: string(ErrorStatusUnresolved),
|
|
Occurrences: 42,
|
|
FirstSeen: now.Add(-24 * time.Hour),
|
|
LastSeen: now.Add(-12 * time.Minute),
|
|
CreatedBy: "system-telemetry",
|
|
RequestPayload: `{"api_key":"Stable_Diffusion_Hair_Color_Changer","feather_radius":5,"model":"flux-fill"}`,
|
|
Tags: []string{"python", "worker", "division-by-zero"},
|
|
}
|
|
|
|
err2 := &AppError{
|
|
ID: "ERR-202",
|
|
Fingerprint: "torch.cuda.OutOfMemoryError:flux_diffusers:310",
|
|
AppName: "Batch Inpaint Service",
|
|
Version: "v2.5.0-rc1",
|
|
Environment: "production",
|
|
Service: "Flux Dress Changer",
|
|
Endpoint: "POST /apis/flxk/batch-inpaint",
|
|
ExceptionType: "torch.cuda.OutOfMemoryError",
|
|
Message: "CUDA out of memory. Tried to allocate 2.40 GiB (GPU 0; 23.68 GiB total capacity; 21.80 GiB already allocated; 1.20 GiB free; 22.10 GiB reserved in total by PyTorch)",
|
|
StackTrace: `Traceback (most recent call last):
|
|
File "pipeline/flux_inpaint.py", line 290, in run_batch_inference
|
|
latents = self.transformer(hidden_states, encoder_hidden_states=prompt_embeds)
|
|
File "site-packages/torch/nn/modules/module.py", line 1532, in _wrapped_call_impl
|
|
return self._call_impl(*args, **kwargs)
|
|
File "site-packages/diffusers/models/transformers/transformer_flux.py", line 310, in forward
|
|
out = torch.bmm(query, key.transpose(1, 2))
|
|
torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 2.40 GiB`,
|
|
Severity: string(SeverityCritical),
|
|
Status: string(ErrorStatusInvestigating),
|
|
Occurrences: 18,
|
|
FirstSeen: now.Add(-14 * time.Hour),
|
|
LastSeen: now.Add(-35 * time.Minute),
|
|
LinkedTicketID: "KHR-103",
|
|
CreatedBy: "system-telemetry",
|
|
RequestPayload: `{"batch_size": 16, "height": 2048, "width": 2048, "steps": 30}`,
|
|
Tags: []string{"gpu", "cuda-oom", "flux-fill", "high-priority"},
|
|
}
|
|
|
|
err3 := &AppError{
|
|
ID: "ERR-203",
|
|
Fingerprint: "ValidationError:api_schema:88",
|
|
AppName: "FastAPI GenAI Backend",
|
|
Version: "v2.4.9",
|
|
Environment: "production",
|
|
Service: "SDXL Turbo Generator",
|
|
Endpoint: "POST /apis/flxk/generate",
|
|
ExceptionType: "pydantic.ValidationError",
|
|
Message: "1 validation error for GenerateRequest: Field 'version' is required but got None or omitted in payload",
|
|
StackTrace: `pydantic_core._pydantic_core.ValidationError: 1 validation error for GenerateRequest
|
|
version
|
|
Field required [type=missing, input_value={'prompt': 'neon portrait', 'steps': 4}, input_type=dict]
|
|
For further information visit https://errors.pydantic.dev/2.6/v/missing`,
|
|
Severity: string(SeverityMedium),
|
|
Status: string(ErrorStatusUnresolved),
|
|
Occurrences: 87,
|
|
FirstSeen: now.Add(-48 * time.Hour),
|
|
LastSeen: now.Add(-4 * time.Minute),
|
|
CreatedBy: "gateway-ingress",
|
|
RequestPayload: `{"prompt": "cyberpunk neon portrait 8k", "steps": 4}`,
|
|
Tags: []string{"validation", "pydantic", "fastapi"},
|
|
}
|
|
|
|
err4 := &AppError{
|
|
ID: "ERR-204",
|
|
Fingerprint: "DatabaseConnectionTimeout:db_pool:52",
|
|
AppName: "Credits Admin API",
|
|
Version: "v2.4.0",
|
|
Environment: "production",
|
|
Service: "System Health & Auth",
|
|
Endpoint: "GET /credits/status",
|
|
ExceptionType: "DatabaseConnectionTimeout",
|
|
Message: "database pool connection timeout: all 50 connection slots occupied during concurrent tenant quota sync",
|
|
StackTrace: `asyncpg.exceptions.TooManyConnectionsError: remaining connection slots are reserved for non-replication superuser connections
|
|
File "db/pool.py", line 52, in acquire_connection
|
|
conn = await self._pool.acquire(timeout=5.0)
|
|
asyncio.exceptions.TimeoutError: QueuePool acquire timeout after 5.00s`,
|
|
Severity: string(SeverityCritical),
|
|
Status: string(ErrorStatusResolved),
|
|
Occurrences: 7,
|
|
FirstSeen: now.Add(-72 * time.Hour),
|
|
LastSeen: now.Add(-6 * time.Hour),
|
|
ResolvedAt: &now,
|
|
ResolvedBy: "Bob Anderson",
|
|
ResolutionNotes: "Increased pgBouncer pool ceiling to 150 max_connections and configured idle transaction timeout.",
|
|
CreatedBy: "system-telemetry",
|
|
Tags: []string{"postgres", "pool-exhaustion", "resolved"},
|
|
}
|
|
|
|
err5 := &AppError{
|
|
ID: "ERR-205",
|
|
Fingerprint: "UIContainerOverflow:face_swap_preview:90",
|
|
AppName: "Unified Dashboard Client",
|
|
Version: "v2.4.0",
|
|
Environment: "staging",
|
|
Service: "InsightFace Swap",
|
|
Endpoint: "CLIENT: /tool/image-merger/",
|
|
ExceptionType: "UIContainerOverflowException",
|
|
Message: "preview canvas flexbox overflow: rendered children width 4320px exceeded viewport container (3840px, scaling 150%)",
|
|
StackTrace: `Error: Canvas layout boundary exceeded
|
|
at renderFaceSwapDualPreview (preview.js:90:14)
|
|
at HTMLInputElement.onImageSelect (index.js:412:9)
|
|
at triggerDualCanvasLayout (dom.js:210:5)`,
|
|
Severity: string(SeverityLow),
|
|
Status: string(ErrorStatusIgnored),
|
|
Occurrences: 14,
|
|
FirstSeen: now.Add(-36 * time.Hour),
|
|
LastSeen: now.Add(-18 * time.Hour),
|
|
CreatedBy: "charlie",
|
|
Tags: []string{"frontend", "css-overflow", "hidpi"},
|
|
}
|
|
|
|
s.errors[err1.ID] = err1
|
|
s.errors[err2.ID] = err2
|
|
s.errors[err3.ID] = err3
|
|
s.errors[err4.ID] = err4
|
|
s.errors[err5.ID] = err5
|
|
s.errorSeq = 205
|
|
}
|
|
|
|
func (s *Store) load() error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
usersFile := filepath.Join(s.dataDir, "users.json")
|
|
if b, err := os.ReadFile(usersFile); err == nil {
|
|
var list []*User
|
|
if err := json.Unmarshal(b, &list); err == nil {
|
|
for _, u := range list {
|
|
if u.PasswordHash == "" {
|
|
switch u.Username {
|
|
case "alice":
|
|
u.PasswordHash = hashPassword("alice123")
|
|
case "bob":
|
|
u.PasswordHash = hashPassword("bob123")
|
|
case "charlie":
|
|
u.PasswordHash = hashPassword("charlie123")
|
|
case "admin":
|
|
u.PasswordHash = hashPassword("admin123")
|
|
default:
|
|
u.PasswordHash = hashPassword("password123")
|
|
}
|
|
}
|
|
s.users[u.Username] = u
|
|
}
|
|
}
|
|
}
|
|
|
|
ticketsFile := filepath.Join(s.dataDir, "tickets.json")
|
|
if b, err := os.ReadFile(ticketsFile); err == nil {
|
|
var list []*Ticket
|
|
if err := json.Unmarshal(b, &list); err == nil {
|
|
maxNum := 100
|
|
for _, t := range list {
|
|
if t.TicketType == "" {
|
|
if t.GeneralCategory != "" {
|
|
t.TicketType = "general"
|
|
} else {
|
|
t.TicketType = "application"
|
|
}
|
|
}
|
|
s.tickets[t.ID] = t
|
|
var num int
|
|
if n, _ := fmt.Sscanf(t.ID, "KHR-%d", &num); n == 1 && num > maxNum {
|
|
maxNum = num
|
|
}
|
|
}
|
|
s.ticketSeq = maxNum
|
|
}
|
|
}
|
|
|
|
errorsFile := filepath.Join(s.dataDir, "errors.json")
|
|
if b, err := os.ReadFile(errorsFile); err == nil {
|
|
var list []*AppError
|
|
if err := json.Unmarshal(b, &list); err == nil {
|
|
maxNum := 200
|
|
for _, e := range list {
|
|
s.errors[e.ID] = e
|
|
var num int
|
|
if n, _ := fmt.Sscanf(e.ID, "ERR-%d", &num); n == 1 && num > maxNum {
|
|
maxNum = num
|
|
}
|
|
}
|
|
s.errorSeq = maxNum
|
|
}
|
|
}
|
|
|
|
notifsFile := filepath.Join(s.dataDir, "notifications.json")
|
|
if b, err := os.ReadFile(notifsFile); err == nil {
|
|
_ = json.Unmarshal(b, &s.notifications)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *Store) save() error {
|
|
usersFile := filepath.Join(s.dataDir, "users.json")
|
|
var userList []*User
|
|
for _, u := range s.users {
|
|
userList = append(userList, u)
|
|
}
|
|
sort.Slice(userList, func(i, j int) bool {
|
|
return userList[i].Username < userList[j].Username
|
|
})
|
|
if b, err := json.MarshalIndent(userList, "", " "); err == nil {
|
|
_ = os.WriteFile(usersFile, b, 0644)
|
|
}
|
|
|
|
ticketsFile := filepath.Join(s.dataDir, "tickets.json")
|
|
var ticketList []*Ticket
|
|
for _, t := range s.tickets {
|
|
ticketList = append(ticketList, t)
|
|
}
|
|
sort.Slice(ticketList, func(i, j int) bool {
|
|
return ticketList[i].CreatedAt.After(ticketList[j].CreatedAt)
|
|
})
|
|
if b, err := json.MarshalIndent(ticketList, "", " "); err == nil {
|
|
_ = os.WriteFile(ticketsFile, b, 0644)
|
|
}
|
|
|
|
errorsFile := filepath.Join(s.dataDir, "errors.json")
|
|
var errorList []*AppError
|
|
for _, e := range s.errors {
|
|
errorList = append(errorList, e)
|
|
}
|
|
sort.Slice(errorList, func(i, j int) bool {
|
|
return errorList[i].LastSeen.After(errorList[j].LastSeen)
|
|
})
|
|
if b, err := json.MarshalIndent(errorList, "", " "); err == nil {
|
|
_ = os.WriteFile(errorsFile, b, 0644)
|
|
}
|
|
|
|
notifsFile := filepath.Join(s.dataDir, "notifications.json")
|
|
if b, err := json.MarshalIndent(s.notifications, "", " "); err == nil {
|
|
_ = os.WriteFile(notifsFile, b, 0644)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *Store) RegisterUser(username, name, password, role string) (*User, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
username = strings.ToLower(strings.TrimSpace(username))
|
|
name = strings.TrimSpace(name)
|
|
if username == "" || password == "" {
|
|
return nil, errors.New("username and password are required")
|
|
}
|
|
if name == "" {
|
|
name = username
|
|
}
|
|
|
|
if _, exists := s.users[username]; exists {
|
|
return nil, errors.New("username already exists")
|
|
}
|
|
|
|
r := Role(role)
|
|
avatar := "👤"
|
|
switch r {
|
|
case RoleFrontend:
|
|
avatar = "👩💻"
|
|
case RoleBackend:
|
|
avatar = "👨💻"
|
|
case RoleTester:
|
|
avatar = "🕵️♂️"
|
|
case RoleLead:
|
|
avatar = "⚡"
|
|
}
|
|
|
|
u := &User{
|
|
ID: uuid.New().String(),
|
|
Username: username,
|
|
Name: name,
|
|
PasswordHash: hashPassword(password),
|
|
Role: string(r),
|
|
RoleDisplay: r.DisplayName(),
|
|
Avatar: avatar,
|
|
CreatedAt: time.Now(),
|
|
}
|
|
|
|
s.users[username] = u
|
|
_ = s.save()
|
|
return u, nil
|
|
}
|
|
|
|
func (s *Store) AuthenticateUser(username, password string) (*User, error) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
|
|
username = strings.ToLower(strings.TrimSpace(username))
|
|
u, exists := s.users[username]
|
|
if !exists {
|
|
return nil, errors.New("invalid username or password")
|
|
}
|
|
|
|
if u.PasswordHash != hashPassword(password) {
|
|
return nil, errors.New("invalid username or password")
|
|
}
|
|
|
|
return u, nil
|
|
}
|
|
|
|
func (s *Store) GetUser(username string) (*User, error) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
|
|
username = strings.ToLower(strings.TrimSpace(username))
|
|
u, exists := s.users[username]
|
|
if !exists {
|
|
return nil, errors.New("user not found")
|
|
}
|
|
return u, nil
|
|
}
|
|
|
|
func (s *Store) UpdateUserProfile(username, name, role, avatar, newPassword string) (*User, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
username = strings.ToLower(strings.TrimSpace(username))
|
|
u, exists := s.users[username]
|
|
if !exists {
|
|
return nil, errors.New("user not found")
|
|
}
|
|
|
|
if strings.TrimSpace(name) != "" {
|
|
u.Name = strings.TrimSpace(name)
|
|
}
|
|
if strings.TrimSpace(role) != "" {
|
|
r := Role(strings.ToLower(strings.TrimSpace(role)))
|
|
if r.IsValid() {
|
|
u.Role = string(r)
|
|
u.RoleDisplay = r.DisplayName()
|
|
}
|
|
}
|
|
if strings.TrimSpace(avatar) != "" {
|
|
u.Avatar = strings.TrimSpace(avatar)
|
|
}
|
|
if strings.TrimSpace(newPassword) != "" {
|
|
u.PasswordHash = hashPassword(newPassword)
|
|
}
|
|
|
|
_ = s.save()
|
|
return u, nil
|
|
}
|
|
|
|
func (s *Store) ListUsers() []*User {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
|
|
var list []*User
|
|
for _, u := range s.users {
|
|
list = append(list, u.Public())
|
|
}
|
|
sort.Slice(list, func(i, j int) bool {
|
|
return list[i].Name < list[j].Name
|
|
})
|
|
return list
|
|
}
|
|
|
|
func (s *Store) CreateTicket(t *Ticket, actor *User) (*Ticket, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
s.ticketSeq++
|
|
t.ID = fmt.Sprintf("KHR-%d", s.ticketSeq)
|
|
now := time.Now()
|
|
t.CreatedAt = now
|
|
t.UpdatedAt = now
|
|
if t.Status == "" {
|
|
t.Status = string(StatusOpen)
|
|
}
|
|
if t.Priority == "" {
|
|
t.Priority = string(PriorityMedium)
|
|
}
|
|
if strings.ToLower(t.TicketType) == "general" {
|
|
t.TicketType = "general"
|
|
if t.AppName == "" {
|
|
t.AppName = "General / Non-App"
|
|
}
|
|
if t.FeatureName == "" && t.GeneralCategory != "" {
|
|
t.FeatureName = t.GeneralCategory
|
|
}
|
|
} else {
|
|
t.TicketType = "application"
|
|
}
|
|
|
|
t.CreatedBy = actor.Username
|
|
t.CreatedByName = actor.Name
|
|
t.CreatedByRole = actor.RoleDisplay
|
|
|
|
// Resolve assignee details
|
|
if t.AssignedTo != "" {
|
|
if assignedUser, ok := s.users[strings.ToLower(t.AssignedTo)]; ok {
|
|
t.AssignedTo = assignedUser.Username
|
|
t.AssignedToName = assignedUser.Name
|
|
t.AssignedToRole = assignedUser.RoleDisplay
|
|
}
|
|
}
|
|
|
|
// Add initial remark
|
|
t.Remarks = []Remark{
|
|
{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: actor.Username,
|
|
AuthorName: actor.Name,
|
|
AuthorRole: actor.RoleDisplay,
|
|
Type: "created",
|
|
Text: fmt.Sprintf("Created ticket for %s with priority %s.", t.AssignedToName, strings.ToUpper(t.Priority)),
|
|
CreatedAt: now,
|
|
},
|
|
}
|
|
|
|
s.tickets[t.ID] = t
|
|
|
|
// Notification to assignee
|
|
if t.AssignedTo != "" && t.AssignedTo != actor.Username {
|
|
s.addNotificationLocked(t.AssignedTo, t.ID, "New Ticket Assigned", fmt.Sprintf("%s (%s) assigned %s: '%s' to you.", actor.Name, actor.RoleDisplay, t.ID, t.Title), "assignment")
|
|
}
|
|
|
|
_ = s.save()
|
|
return t, nil
|
|
}
|
|
|
|
func (s *Store) GetTicket(id string) (*Ticket, error) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
|
|
id = strings.ToUpper(strings.TrimSpace(id))
|
|
t, ok := s.tickets[id]
|
|
if !ok {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
return t, nil
|
|
}
|
|
|
|
func (s *Store) ListTickets(filterStatus, filterPriority, filterAssignee, filterCreator, filterRole, filterType, query string) []*Ticket {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
|
|
filterStatus = strings.ToLower(strings.TrimSpace(filterStatus))
|
|
filterPriority = strings.ToLower(strings.TrimSpace(filterPriority))
|
|
filterAssignee = strings.ToLower(strings.TrimSpace(filterAssignee))
|
|
filterCreator = strings.ToLower(strings.TrimSpace(filterCreator))
|
|
filterRole = strings.ToLower(strings.TrimSpace(filterRole))
|
|
filterType = strings.ToLower(strings.TrimSpace(filterType))
|
|
query = strings.ToLower(strings.TrimSpace(query))
|
|
|
|
var res []*Ticket
|
|
for _, t := range s.tickets {
|
|
if filterStatus != "" && filterStatus != "all" && strings.ToLower(t.Status) != filterStatus {
|
|
continue
|
|
}
|
|
if filterPriority != "" && filterPriority != "all" && strings.ToLower(t.Priority) != filterPriority {
|
|
continue
|
|
}
|
|
if filterAssignee != "" && strings.ToLower(t.AssignedTo) != filterAssignee {
|
|
continue
|
|
}
|
|
if filterCreator != "" && strings.ToLower(t.CreatedBy) != filterCreator {
|
|
continue
|
|
}
|
|
if filterRole != "" && filterRole != "all" {
|
|
assignedUser, ok := s.users[strings.ToLower(t.AssignedTo)]
|
|
if !ok || strings.ToLower(assignedUser.Role) != filterRole {
|
|
continue
|
|
}
|
|
}
|
|
if filterType != "" && filterType != "all" {
|
|
tType := strings.ToLower(t.TicketType)
|
|
if tType == "" {
|
|
tType = "application"
|
|
}
|
|
if tType != filterType {
|
|
continue
|
|
}
|
|
}
|
|
if query != "" {
|
|
tType := strings.ToLower(t.TicketType)
|
|
if tType == "" {
|
|
tType = "application"
|
|
}
|
|
combined := strings.ToLower(t.ID + " " + t.Title + " " + t.AppName + " " + t.FeatureName + " " + t.APIKey + " " + t.Description + " " + t.AssignedToName + " " + t.CreatedByName + " " + tType + " " + t.GeneralCategory + " " + t.Department)
|
|
if !strings.Contains(combined, query) {
|
|
continue
|
|
}
|
|
}
|
|
res = append(res, t)
|
|
}
|
|
|
|
sort.Slice(res, func(i, j int) bool {
|
|
return res[i].UpdatedAt.After(res[j].UpdatedAt)
|
|
})
|
|
return res
|
|
}
|
|
|
|
func (s *Store) AddRemark(ticketID string, actor *User, rType, text string) (*Ticket, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
ticketID = strings.ToUpper(strings.TrimSpace(ticketID))
|
|
t, ok := s.tickets[ticketID]
|
|
if !ok {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
now := time.Now()
|
|
rem := Remark{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: actor.Username,
|
|
AuthorName: actor.Name,
|
|
AuthorRole: actor.RoleDisplay,
|
|
Type: rType,
|
|
Text: text,
|
|
CreatedAt: now,
|
|
}
|
|
t.Remarks = append(t.Remarks, rem)
|
|
t.UpdatedAt = now
|
|
|
|
// Notify assignee or creator
|
|
target := t.AssignedTo
|
|
if target == actor.Username {
|
|
target = t.CreatedBy
|
|
}
|
|
if target != "" && target != actor.Username {
|
|
s.addNotificationLocked(target, t.ID, "New Remark on Ticket", fmt.Sprintf("%s commented on %s: %s", actor.Name, t.ID, text), "remark")
|
|
}
|
|
|
|
_ = s.save()
|
|
return t, nil
|
|
}
|
|
|
|
func (s *Store) HoldTicket(ticketID string, actor *User, reason string) (*Ticket, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
ticketID = strings.ToUpper(strings.TrimSpace(ticketID))
|
|
t, ok := s.tickets[ticketID]
|
|
if !ok {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
now := time.Now()
|
|
t.Status = string(StatusOnHold)
|
|
t.HoldReason = reason
|
|
t.HeldBy = actor.Name
|
|
t.HeldAt = &now
|
|
t.UpdatedAt = now
|
|
|
|
t.Remarks = append(t.Remarks, Remark{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: actor.Username,
|
|
AuthorName: actor.Name,
|
|
AuthorRole: actor.RoleDisplay,
|
|
Type: "hold",
|
|
Text: fmt.Sprintf("TICKET PUT ON HOLD. Reason: %s", reason),
|
|
CreatedAt: now,
|
|
})
|
|
|
|
if t.AssignedTo != "" && t.AssignedTo != actor.Username {
|
|
s.addNotificationLocked(t.AssignedTo, t.ID, "Ticket Put On Hold", fmt.Sprintf("%s placed %s on hold: '%s'", actor.Name, t.ID, reason), "hold")
|
|
}
|
|
if t.CreatedBy != "" && t.CreatedBy != actor.Username {
|
|
s.addNotificationLocked(t.CreatedBy, t.ID, "Ticket Put On Hold", fmt.Sprintf("%s placed %s on hold: '%s'", actor.Name, t.ID, reason), "hold")
|
|
}
|
|
|
|
_ = s.save()
|
|
return t, nil
|
|
}
|
|
|
|
func (s *Store) ResumeTicket(ticketID string, actor *User, remarks string) (*Ticket, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
ticketID = strings.ToUpper(strings.TrimSpace(ticketID))
|
|
t, ok := s.tickets[ticketID]
|
|
if !ok {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
now := time.Now()
|
|
t.Status = string(StatusInProgress)
|
|
t.HoldReason = ""
|
|
t.HeldBy = ""
|
|
t.HeldAt = nil
|
|
t.UpdatedAt = now
|
|
|
|
msg := "Ticket resumed and active in progress."
|
|
if remarks != "" {
|
|
msg += " Remarks: " + remarks
|
|
}
|
|
|
|
t.Remarks = append(t.Remarks, Remark{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: actor.Username,
|
|
AuthorName: actor.Name,
|
|
AuthorRole: actor.RoleDisplay,
|
|
Type: "resume",
|
|
Text: msg,
|
|
CreatedAt: now,
|
|
})
|
|
|
|
if t.AssignedTo != "" && t.AssignedTo != actor.Username {
|
|
s.addNotificationLocked(t.AssignedTo, t.ID, "Ticket Resumed", fmt.Sprintf("%s resumed work on %s.", actor.Name, t.ID), "status_change")
|
|
}
|
|
|
|
_ = s.save()
|
|
return t, nil
|
|
}
|
|
|
|
func (s *Store) CompleteTicket(ticketID string, actor *User, completionRemarks string) (*Ticket, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
ticketID = strings.ToUpper(strings.TrimSpace(ticketID))
|
|
t, ok := s.tickets[ticketID]
|
|
if !ok {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
now := time.Now()
|
|
t.Status = string(StatusCompleted)
|
|
t.CompletionRemarks = completionRemarks
|
|
t.CompletedBy = actor.Name
|
|
t.CompletedAt = &now
|
|
t.UpdatedAt = now
|
|
|
|
t.Remarks = append(t.Remarks, Remark{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: actor.Username,
|
|
AuthorName: actor.Name,
|
|
AuthorRole: actor.RoleDisplay,
|
|
Type: "complete",
|
|
Text: fmt.Sprintf("TICKET COMPLETED. Resolution remarks: %s", completionRemarks),
|
|
CreatedAt: now,
|
|
})
|
|
|
|
if t.CreatedBy != "" && t.CreatedBy != actor.Username {
|
|
s.addNotificationLocked(t.CreatedBy, t.ID, "Ticket Completed! 🎉", fmt.Sprintf("%s marked %s as completed: '%s'", actor.Name, t.ID, completionRemarks), "complete")
|
|
}
|
|
|
|
_ = s.save()
|
|
return t, nil
|
|
}
|
|
|
|
func (s *Store) ChangePriority(ticketID string, actor *User, newPriority string, note string) (*Ticket, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
ticketID = strings.ToUpper(strings.TrimSpace(ticketID))
|
|
t, ok := s.tickets[ticketID]
|
|
if !ok {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
oldPriority := t.Priority
|
|
t.Priority = strings.ToLower(newPriority)
|
|
now := time.Now()
|
|
t.UpdatedAt = now
|
|
|
|
msg := fmt.Sprintf("Priority changed from %s to %s.", strings.ToUpper(oldPriority), strings.ToUpper(t.Priority))
|
|
if note != "" {
|
|
msg += " Note: " + note
|
|
}
|
|
|
|
t.Remarks = append(t.Remarks, Remark{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: actor.Username,
|
|
AuthorName: actor.Name,
|
|
AuthorRole: actor.RoleDisplay,
|
|
Type: "priority_change",
|
|
Text: msg,
|
|
CreatedAt: now,
|
|
})
|
|
|
|
if t.AssignedTo != "" && t.AssignedTo != actor.Username {
|
|
s.addNotificationLocked(t.AssignedTo, t.ID, "Priority Updated", fmt.Sprintf("%s changed priority of %s to %s.", actor.Name, t.ID, strings.ToUpper(t.Priority)), "status_change")
|
|
}
|
|
|
|
_ = s.save()
|
|
return t, nil
|
|
}
|
|
|
|
func (s *Store) ReassignTicket(ticketID string, actor *User, newAssigneeUsername string, note string) (*Ticket, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
ticketID = strings.ToUpper(strings.TrimSpace(ticketID))
|
|
t, ok := s.tickets[ticketID]
|
|
if !ok {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
newAssignee, ok := s.users[strings.ToLower(newAssigneeUsername)]
|
|
if !ok {
|
|
return nil, errors.New("new assignee user not found")
|
|
}
|
|
|
|
oldName := t.AssignedToName
|
|
t.AssignedTo = newAssignee.Username
|
|
t.AssignedToName = newAssignee.Name
|
|
t.AssignedToRole = newAssignee.RoleDisplay
|
|
now := time.Now()
|
|
t.UpdatedAt = now
|
|
|
|
msg := fmt.Sprintf("Ticket reassigned from %s to %s (%s).", oldName, newAssignee.Name, newAssignee.RoleDisplay)
|
|
if note != "" {
|
|
msg += " Note: " + note
|
|
}
|
|
|
|
t.Remarks = append(t.Remarks, Remark{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: actor.Username,
|
|
AuthorName: actor.Name,
|
|
AuthorRole: actor.RoleDisplay,
|
|
Type: "reassign",
|
|
Text: msg,
|
|
CreatedAt: now,
|
|
})
|
|
|
|
if newAssignee.Username != actor.Username {
|
|
s.addNotificationLocked(newAssignee.Username, t.ID, "Ticket Reassigned To You", fmt.Sprintf("%s reassigned %s to you: '%s'", actor.Name, t.ID, t.Title), "assignment")
|
|
}
|
|
|
|
_ = s.save()
|
|
return t, nil
|
|
}
|
|
|
|
func (s *Store) addNotificationLocked(userID, ticketID, title, msg, nType string) {
|
|
n := Notification{
|
|
ID: uuid.New().String(),
|
|
UserID: userID,
|
|
TicketID: ticketID,
|
|
Title: title,
|
|
Message: msg,
|
|
Type: nType,
|
|
Read: false,
|
|
CreatedAt: time.Now(),
|
|
}
|
|
s.notifications[userID] = append([]Notification{n}, s.notifications[userID]...)
|
|
if len(s.notifications[userID]) > 50 {
|
|
s.notifications[userID] = s.notifications[userID][:50]
|
|
}
|
|
}
|
|
|
|
func (s *Store) GetNotifications(userID string) []Notification {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
|
|
userID = strings.ToLower(userID)
|
|
list := s.notifications[userID]
|
|
res := make([]Notification, len(list))
|
|
copy(res, list)
|
|
return res
|
|
}
|
|
|
|
func (s *Store) MarkNotificationsRead(userID string) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
userID = strings.ToLower(userID)
|
|
for i := range s.notifications[userID] {
|
|
s.notifications[userID][i].Read = true
|
|
}
|
|
_ = s.save()
|
|
}
|
|
|
|
func (s *Store) GetDataDir() string {
|
|
return s.dataDir
|
|
}
|
|
|
|
func (s *Store) AddAttachment(ticketID string, actor *User, att Attachment) (*Ticket, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
ticketID = strings.ToUpper(strings.TrimSpace(ticketID))
|
|
t, ok := s.tickets[ticketID]
|
|
if !ok {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
if att.ID == "" {
|
|
att.ID = uuid.New().String()
|
|
}
|
|
if att.CreatedAt.IsZero() {
|
|
att.CreatedAt = time.Now()
|
|
}
|
|
if att.UploadedBy == "" {
|
|
att.UploadedBy = actor.Name
|
|
}
|
|
|
|
t.Attachments = append(t.Attachments, att)
|
|
now := time.Now()
|
|
t.UpdatedAt = now
|
|
|
|
t.Remarks = append(t.Remarks, Remark{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: actor.Username,
|
|
AuthorName: actor.Name,
|
|
AuthorRole: actor.RoleDisplay,
|
|
Type: "attachment",
|
|
Text: fmt.Sprintf("Uploaded attachment: %s", att.Name),
|
|
Attachments: []Attachment{att},
|
|
CreatedAt: now,
|
|
})
|
|
|
|
if t.AssignedTo != "" && t.AssignedTo != actor.Username {
|
|
s.addNotificationLocked(t.AssignedTo, t.ID, "New Attachment", fmt.Sprintf("%s uploaded '%s' to %s.", actor.Name, att.Name, t.ID), "attachment")
|
|
}
|
|
|
|
_ = s.save()
|
|
return t, nil
|
|
}
|
|
|
|
func (s *Store) AddLink(ticketID string, actor *User, link string) (*Ticket, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
ticketID = strings.ToUpper(strings.TrimSpace(ticketID))
|
|
t, ok := s.tickets[ticketID]
|
|
if !ok {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
link = strings.TrimSpace(link)
|
|
if link == "" {
|
|
return nil, errors.New("link cannot be empty")
|
|
}
|
|
if !strings.HasPrefix(link, "http://") && !strings.HasPrefix(link, "https://") {
|
|
link = "https://" + link
|
|
}
|
|
|
|
t.Links = append(t.Links, link)
|
|
now := time.Now()
|
|
t.UpdatedAt = now
|
|
|
|
t.Remarks = append(t.Remarks, Remark{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: actor.Username,
|
|
AuthorName: actor.Name,
|
|
AuthorRole: actor.RoleDisplay,
|
|
Type: "link",
|
|
Text: fmt.Sprintf("Added reference link: %s", link),
|
|
CreatedAt: now,
|
|
})
|
|
|
|
if t.AssignedTo != "" && t.AssignedTo != actor.Username {
|
|
s.addNotificationLocked(t.AssignedTo, t.ID, "New Reference Link", fmt.Sprintf("%s linked '%s' to %s.", actor.Name, link, t.ID), "link")
|
|
}
|
|
|
|
_ = s.save()
|
|
return t, nil
|
|
}
|
|
|
|
func (s *Store) ListErrors(status, severity, app, query string) []*AppError {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
|
|
var result []*AppError
|
|
status = strings.ToLower(strings.TrimSpace(status))
|
|
severity = strings.ToLower(strings.TrimSpace(severity))
|
|
app = strings.ToLower(strings.TrimSpace(app))
|
|
query = strings.ToLower(strings.TrimSpace(query))
|
|
|
|
for _, e := range s.errors {
|
|
if status != "" && status != "all" && strings.ToLower(e.Status) != status {
|
|
continue
|
|
}
|
|
if severity != "" && severity != "all" && strings.ToLower(e.Severity) != severity {
|
|
continue
|
|
}
|
|
if app != "" && app != "all" && !strings.Contains(strings.ToLower(e.AppName), app) {
|
|
continue
|
|
}
|
|
if query != "" {
|
|
match := strings.Contains(strings.ToLower(e.ID), query) ||
|
|
strings.Contains(strings.ToLower(e.Message), query) ||
|
|
strings.Contains(strings.ToLower(e.ExceptionType), query) ||
|
|
strings.Contains(strings.ToLower(e.Service), query) ||
|
|
strings.Contains(strings.ToLower(e.Endpoint), query) ||
|
|
strings.Contains(strings.ToLower(e.AppName), query)
|
|
if !match {
|
|
for _, tag := range e.Tags {
|
|
if strings.Contains(strings.ToLower(tag), query) {
|
|
match = true
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if !match {
|
|
continue
|
|
}
|
|
}
|
|
result = append(result, e)
|
|
}
|
|
|
|
sort.Slice(result, func(i, j int) bool {
|
|
return result[i].LastSeen.After(result[j].LastSeen)
|
|
})
|
|
|
|
return result
|
|
}
|
|
|
|
func (s *Store) GetError(id string) (*AppError, error) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
|
|
id = strings.ToUpper(strings.TrimSpace(id))
|
|
e, ok := s.errors[id]
|
|
if !ok {
|
|
for _, item := range s.errors {
|
|
if strings.EqualFold(item.ID, id) {
|
|
return item, nil
|
|
}
|
|
}
|
|
return nil, errors.New("error not found")
|
|
}
|
|
return e, nil
|
|
}
|
|
|
|
func (s *Store) IngestError(errData *AppError, actor *User) (*AppError, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
if strings.TrimSpace(errData.AppName) == "" {
|
|
errData.AppName = "Unified Dashboard"
|
|
}
|
|
if strings.TrimSpace(errData.ExceptionType) == "" {
|
|
errData.ExceptionType = "UnhandledException"
|
|
}
|
|
if strings.TrimSpace(errData.Message) == "" {
|
|
return nil, errors.New("error message is required")
|
|
}
|
|
|
|
if errData.Fingerprint == "" {
|
|
raw := fmt.Sprintf("%s:%s:%s", errData.AppName, errData.ExceptionType, strings.Split(strings.TrimSpace(errData.Message), "\n")[0])
|
|
sum := sha256.Sum256([]byte(raw))
|
|
errData.Fingerprint = fmt.Sprintf("%x", sum)[:16]
|
|
}
|
|
|
|
now := time.Now()
|
|
|
|
for _, existing := range s.errors {
|
|
if existing.Fingerprint == errData.Fingerprint && strings.EqualFold(existing.AppName, errData.AppName) {
|
|
existing.Occurrences++
|
|
existing.LastSeen = now
|
|
if errData.StackTrace != "" {
|
|
existing.StackTrace = errData.StackTrace
|
|
}
|
|
if errData.Endpoint != "" {
|
|
existing.Endpoint = errData.Endpoint
|
|
}
|
|
if errData.RequestPayload != "" {
|
|
existing.RequestPayload = errData.RequestPayload
|
|
}
|
|
if existing.Status == string(ErrorStatusResolved) {
|
|
existing.Status = string(ErrorStatusUnresolved)
|
|
existing.ResolutionNotes = "Reopened due to recurring occurrence"
|
|
}
|
|
_ = s.save()
|
|
return existing, nil
|
|
}
|
|
}
|
|
|
|
s.errorSeq++
|
|
errData.ID = fmt.Sprintf("ERR-%d", s.errorSeq)
|
|
errData.Occurrences = 1
|
|
errData.FirstSeen = now
|
|
errData.LastSeen = now
|
|
|
|
if errData.Severity == "" {
|
|
errData.Severity = string(SeverityMedium)
|
|
}
|
|
if errData.Status == "" {
|
|
errData.Status = string(ErrorStatusUnresolved)
|
|
}
|
|
if errData.Environment == "" {
|
|
errData.Environment = "production"
|
|
}
|
|
if actor != nil {
|
|
errData.CreatedBy = actor.Username
|
|
} else if errData.CreatedBy == "" {
|
|
errData.CreatedBy = "system-telemetry"
|
|
}
|
|
|
|
s.errors[errData.ID] = errData
|
|
|
|
if errData.Severity == string(SeverityCritical) || errData.Severity == string(SeverityHigh) {
|
|
for _, u := range s.users {
|
|
if u.Role == string(RoleLead) || u.Username == "admin" {
|
|
s.addNotificationLocked(
|
|
u.Username,
|
|
errData.ID,
|
|
fmt.Sprintf("🚨 %s Runtime Error: %s", strings.ToUpper(errData.Severity), errData.ExceptionType),
|
|
fmt.Sprintf("[%s] %s in %s", errData.AppName, errData.Message, errData.Service),
|
|
"error_alert",
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
_ = s.save()
|
|
return errData, nil
|
|
}
|
|
|
|
func (s *Store) UpdateErrorStatus(id string, status ErrorStatus, notes string, actor *User) (*AppError, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
id = strings.ToUpper(strings.TrimSpace(id))
|
|
e, ok := s.errors[id]
|
|
if !ok {
|
|
return nil, errors.New("error not found")
|
|
}
|
|
|
|
now := time.Now()
|
|
e.Status = string(status)
|
|
if status == ErrorStatusResolved {
|
|
e.ResolvedAt = &now
|
|
if actor != nil {
|
|
e.ResolvedBy = actor.Name
|
|
} else {
|
|
e.ResolvedBy = "System"
|
|
}
|
|
if notes != "" {
|
|
e.ResolutionNotes = notes
|
|
}
|
|
} else {
|
|
if notes != "" {
|
|
e.ResolutionNotes = notes
|
|
}
|
|
}
|
|
|
|
_ = s.save()
|
|
return e, nil
|
|
}
|
|
|
|
func (s *Store) EscalateErrorToTicket(errorID string, title, assigneeUsername, priority, notes string, actor *User) (*Ticket, *AppError, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
errorID = strings.ToUpper(strings.TrimSpace(errorID))
|
|
e, ok := s.errors[errorID]
|
|
if !ok {
|
|
return nil, nil, errors.New("error not found")
|
|
}
|
|
|
|
if e.LinkedTicketID != "" {
|
|
if existingTicket, exists := s.tickets[e.LinkedTicketID]; exists {
|
|
return existingTicket, e, nil
|
|
}
|
|
}
|
|
|
|
if title == "" {
|
|
msgShort := e.Message
|
|
if len(msgShort) > 80 {
|
|
msgShort = msgShort[:80] + "..."
|
|
}
|
|
title = fmt.Sprintf("[%s] %s: %s", e.AppName, e.ExceptionType, msgShort)
|
|
}
|
|
|
|
ticketPriority := string(PriorityMedium)
|
|
switch strings.ToLower(e.Severity) {
|
|
case string(SeverityCritical):
|
|
ticketPriority = string(PriorityCritical)
|
|
case string(SeverityHigh):
|
|
ticketPriority = string(PriorityHigh)
|
|
case string(SeverityMedium):
|
|
ticketPriority = string(PriorityMedium)
|
|
case string(SeverityLow):
|
|
ticketPriority = string(PriorityLow)
|
|
}
|
|
if priority != "" {
|
|
ticketPriority = priority
|
|
}
|
|
|
|
var assignedUser *User
|
|
if assigneeUsername != "" {
|
|
assignedUser = s.users[strings.ToLower(assigneeUsername)]
|
|
}
|
|
if assignedUser == nil {
|
|
for _, u := range s.users {
|
|
if u.Role == string(RoleBackend) {
|
|
assignedUser = u
|
|
break
|
|
}
|
|
}
|
|
if assignedUser == nil {
|
|
assignedUser = actor
|
|
}
|
|
}
|
|
|
|
s.ticketSeq++
|
|
newTicketID := fmt.Sprintf("KHR-%d", s.ticketSeq)
|
|
now := time.Now()
|
|
|
|
desc := fmt.Sprintf("### Telemetry Exception Report\n- **Error ID**: `%s`\n- **Service/Feature**: %s\n- **Endpoint**: `%s`\n- **Exception**: `%s`\n- **Occurrences**: %d times\n- **First Seen**: %s\n- **Last Seen**: %s\n\n**Error Message**:\n```\n%s\n```",
|
|
e.ID, e.Service, e.Endpoint, e.ExceptionType, e.Occurrences,
|
|
e.FirstSeen.Format("2006-01-02 15:04:05"), e.LastSeen.Format("2006-01-02 15:04:05"), e.Message)
|
|
|
|
addl := ""
|
|
if e.StackTrace != "" {
|
|
addl += fmt.Sprintf("#### Stack Trace:\n```\n%s\n```\n", e.StackTrace)
|
|
}
|
|
if e.RequestPayload != "" {
|
|
addl += fmt.Sprintf("\n#### Sample Payload:\n```json\n%s\n```\n", e.RequestPayload)
|
|
}
|
|
if notes != "" {
|
|
addl += fmt.Sprintf("\n#### Escalation Notes:\n%s\n", notes)
|
|
}
|
|
|
|
t := &Ticket{
|
|
ID: newTicketID,
|
|
TicketType: "application",
|
|
Title: title,
|
|
AppName: e.AppName,
|
|
Version: e.Version,
|
|
FeatureName: e.Service,
|
|
APIKey: e.Endpoint,
|
|
IssueType: "bug",
|
|
Priority: ticketPriority,
|
|
Status: string(StatusOpen),
|
|
Description: desc,
|
|
AssistanceRequired: "Exception & Crash Investigation",
|
|
AdditionalInfo: addl,
|
|
CreatedBy: actor.Username,
|
|
CreatedByName: actor.Name,
|
|
CreatedByRole: actor.RoleDisplay,
|
|
AssignedTo: assignedUser.Username,
|
|
AssignedToName: assignedUser.Name,
|
|
AssignedToRole: assignedUser.RoleDisplay,
|
|
LinkedErrorID: e.ID,
|
|
Remarks: []Remark{
|
|
{
|
|
ID: uuid.New().String(),
|
|
AuthorUsername: actor.Username,
|
|
AuthorName: actor.Name,
|
|
AuthorRole: actor.RoleDisplay,
|
|
Type: "escalated",
|
|
Text: fmt.Sprintf("⚡ Escalated from Error %s (%s). Assigned to %s.", e.ID, e.ExceptionType, assignedUser.Name),
|
|
CreatedAt: now,
|
|
},
|
|
},
|
|
CreatedAt: now,
|
|
UpdatedAt: now,
|
|
}
|
|
|
|
s.tickets[t.ID] = t
|
|
|
|
e.LinkedTicketID = t.ID
|
|
e.Status = string(ErrorStatusInvestigating)
|
|
|
|
s.addNotificationLocked(
|
|
assignedUser.Username,
|
|
t.ID,
|
|
"🚨 Escalated Error Assigned to You",
|
|
fmt.Sprintf("%s escalated runtime error %s (%s) into ticket %s and assigned it to you.", actor.Name, e.ID, e.ExceptionType, t.ID),
|
|
"assignment",
|
|
)
|
|
|
|
_ = s.save()
|
|
return t, e, nil
|
|
}
|
|
|
|
func (s *Store) GetErrorStats() map[string]int {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
|
|
stats := map[string]int{
|
|
"total": 0,
|
|
"unresolved": 0,
|
|
"investigating": 0,
|
|
"resolved": 0,
|
|
"ignored": 0,
|
|
"critical": 0,
|
|
"high": 0,
|
|
"medium": 0,
|
|
"low": 0,
|
|
"escalated": 0,
|
|
}
|
|
|
|
for _, e := range s.errors {
|
|
stats["total"]++
|
|
switch strings.ToLower(e.Status) {
|
|
case string(ErrorStatusUnresolved):
|
|
stats["unresolved"]++
|
|
case string(ErrorStatusInvestigating):
|
|
stats["investigating"]++
|
|
case string(ErrorStatusResolved):
|
|
stats["resolved"]++
|
|
case string(ErrorStatusIgnored):
|
|
stats["ignored"]++
|
|
}
|
|
|
|
switch strings.ToLower(e.Severity) {
|
|
case string(SeverityCritical):
|
|
stats["critical"]++
|
|
case string(SeverityHigh):
|
|
stats["high"]++
|
|
case string(SeverityMedium):
|
|
stats["medium"]++
|
|
case string(SeverityLow):
|
|
stats["low"]++
|
|
}
|
|
|
|
if e.LinkedTicketID != "" {
|
|
stats["escalated"]++
|
|
}
|
|
}
|
|
|
|
return stats
|
|
}
|