1703 lines
53 KiB
Go
1703 lines
53 KiB
Go
package khira
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
_ "github.com/lib/pq"
|
|
)
|
|
|
|
type Store struct {
|
|
primaryDB *sql.DB
|
|
backupDB *sql.DB
|
|
dataDir string
|
|
Broker *EventBroker
|
|
mu sync.RWMutex
|
|
}
|
|
|
|
func envOrDefault(k, d string) string {
|
|
if v := os.Getenv(k); v != "" {
|
|
return v
|
|
}
|
|
return d
|
|
}
|
|
|
|
// NewStore initializes connections to primary and backup PostgreSQL databases
|
|
func NewStore(dataDir string) (*Store, error) {
|
|
_ = os.MkdirAll(filepath.Join(dataDir, "uploads", "avatars"), 0755)
|
|
|
|
primaryURL := envOrDefault("KHIRA_PRIMARY_DB_URL", "postgres://[email protected]:5432/khira_primary?sslmode=disable")
|
|
backupURL := envOrDefault("KHIRA_BACKUP_DB_URL", "postgres://[email protected]:5432/khira_backup?sslmode=disable")
|
|
|
|
primaryDB, err := connectDB(primaryURL)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to connect to primary database: %w", err)
|
|
}
|
|
|
|
backupDB, err := connectDB(backupURL)
|
|
if err != nil {
|
|
slog.Warn("failed to connect to backup database (will retry on operations)", "err", err)
|
|
}
|
|
|
|
// Initialize schemas
|
|
if err := initSchema(primaryDB); err != nil {
|
|
return nil, fmt.Errorf("failed to init primary database schema: %w", err)
|
|
}
|
|
if backupDB != nil {
|
|
if err := initSchema(backupDB); err != nil {
|
|
slog.Warn("failed to init backup database schema", "err", err)
|
|
}
|
|
}
|
|
|
|
// Seed admin & default users in primary
|
|
if err := seedDefaultUsers(primaryDB); err != nil {
|
|
slog.Error("failed to seed default users in primary", "err", err)
|
|
}
|
|
|
|
s := &Store{
|
|
primaryDB: primaryDB,
|
|
backupDB: backupDB,
|
|
dataDir: dataDir,
|
|
Broker: NewEventBroker(),
|
|
}
|
|
|
|
// Check if backup is empty; if so, initial sync
|
|
if backupDB != nil {
|
|
var backupUserCount int
|
|
_ = backupDB.QueryRow("SELECT count(*) FROM users").Scan(&backupUserCount)
|
|
if backupUserCount == 0 {
|
|
_, _ = SyncDatabases(primaryDB, backupDB)
|
|
}
|
|
}
|
|
|
|
// Start background SLA monitor
|
|
s.StartSLAMonitor()
|
|
|
|
return s, nil
|
|
}
|
|
|
|
func (s *Store) GetDataDir() string {
|
|
return s.dataDir
|
|
}
|
|
|
|
func (s *Store) Close() {
|
|
if s.primaryDB != nil {
|
|
_ = s.primaryDB.Close()
|
|
}
|
|
if s.backupDB != nil {
|
|
_ = s.backupDB.Close()
|
|
}
|
|
}
|
|
|
|
func (s *Store) nextSeq(name string, prefix string) (string, error) {
|
|
var val int
|
|
err := s.primaryDB.QueryRow(`
|
|
INSERT INTO khira_sequences (name, val) VALUES ($1, 101)
|
|
ON CONFLICT (name) DO UPDATE SET val = khira_sequences.val + 1
|
|
RETURNING val
|
|
`, name).Scan(&val)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return fmt.Sprintf("%s-%03d", prefix, val), nil
|
|
}
|
|
|
|
// ─────────────────────────────────────────────
|
|
// Users & Auth
|
|
// ─────────────────────────────────────────────
|
|
|
|
func (s *Store) RegisterUser(username, name, password, role string) (*User, error) {
|
|
|
|
username = strings.ToLower(strings.TrimSpace(username))
|
|
name = strings.TrimSpace(name)
|
|
if username == "" || name == "" || password == "" {
|
|
return nil, errors.New("username, name and password are required")
|
|
}
|
|
|
|
r := Role(role)
|
|
if !r.IsValid() {
|
|
r = RoleTester
|
|
}
|
|
|
|
avatar := "👤"
|
|
switch r {
|
|
case RoleTester:
|
|
avatar = "🕵️♂️"
|
|
case RoleIOS:
|
|
avatar = "👩💻"
|
|
case RoleAndroid:
|
|
avatar = "🤖"
|
|
case RoleBackend:
|
|
avatar = "👨💻"
|
|
case RoleDesigner:
|
|
avatar = "🎨"
|
|
case RoleLead:
|
|
avatar = "A"
|
|
}
|
|
|
|
var exists bool
|
|
_ = s.primaryDB.QueryRow("SELECT EXISTS(SELECT 1 FROM users WHERE username = $1)", username).Scan(&exists)
|
|
if exists {
|
|
return nil, errors.New("username already taken")
|
|
}
|
|
|
|
id := uuid.New().String()
|
|
now := time.Now()
|
|
hash := hashPassword(password)
|
|
|
|
_, err := s.primaryDB.Exec(`
|
|
INSERT INTO users (id, username, name, password_hash, role, role_display, avatar, avatar_type, profile_image, created_at, updated_at)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, 'emoji', '', $8, $8)
|
|
`, id, username, name, hash, string(r), r.DisplayName(), avatar, now)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to register user: %w", err)
|
|
}
|
|
|
|
return &User{
|
|
ID: id,
|
|
Username: username,
|
|
Name: name,
|
|
PasswordHash: hash,
|
|
Role: string(r),
|
|
RoleDisplay: r.DisplayName(),
|
|
Avatar: avatar,
|
|
AvatarType: "emoji",
|
|
ProfileImage: "",
|
|
CreatedAt: now,
|
|
UpdatedAt: now,
|
|
}, nil
|
|
}
|
|
|
|
func (s *Store) AuthenticateUser(username, password string) (*User, error) {
|
|
|
|
username = strings.ToLower(strings.TrimSpace(username))
|
|
var u User
|
|
err := s.primaryDB.QueryRow(`
|
|
SELECT id, username, name, password_hash, role, role_display, avatar, avatar_type, profile_image, created_at, updated_at
|
|
FROM users WHERE username = $1
|
|
`, username).Scan(&u.ID, &u.Username, &u.Name, &u.PasswordHash, &u.Role, &u.RoleDisplay, &u.Avatar, &u.AvatarType, &u.ProfileImage, &u.CreatedAt, &u.UpdatedAt)
|
|
if err != nil {
|
|
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) {
|
|
|
|
username = strings.ToLower(strings.TrimSpace(username))
|
|
var u User
|
|
err := s.primaryDB.QueryRow(`
|
|
SELECT id, username, name, password_hash, role, role_display, avatar, avatar_type, profile_image, active, created_at, updated_at
|
|
FROM users WHERE username = $1
|
|
`, username).Scan(&u.ID, &u.Username, &u.Name, &u.PasswordHash, &u.Role, &u.RoleDisplay, &u.Avatar, &u.AvatarType, &u.ProfileImage, &u.Active, &u.CreatedAt, &u.UpdatedAt)
|
|
if err != nil {
|
|
return nil, errors.New("user not found")
|
|
}
|
|
return &u, nil
|
|
}
|
|
|
|
func (s *Store) ListUsers() []*User {
|
|
|
|
rows, err := s.primaryDB.Query(`
|
|
SELECT id, username, name, role, role_display, avatar, avatar_type, profile_image, active, created_at, updated_at
|
|
FROM users WHERE active = TRUE ORDER BY name ASC
|
|
`)
|
|
if err != nil {
|
|
return []*User{}
|
|
}
|
|
defer rows.Close()
|
|
|
|
var list []*User
|
|
for rows.Next() {
|
|
var u User
|
|
if err := rows.Scan(&u.ID, &u.Username, &u.Name, &u.Role, &u.RoleDisplay, &u.Avatar, &u.AvatarType, &u.ProfileImage, &u.Active, &u.CreatedAt, &u.UpdatedAt); err == nil {
|
|
list = append(list, &u)
|
|
}
|
|
}
|
|
return list
|
|
}
|
|
|
|
func (s *Store) UpdateUserProfile(username, name, role, avatar, newPassword string) (*User, error) {
|
|
return s.UpdateUserProfileFull(username, name, role, avatar, "", "", newPassword)
|
|
}
|
|
|
|
func (s *Store) UpdateUserProfileFull(username, name, role, avatar, avatarType, profileImage, newPassword string) (*User, error) {
|
|
|
|
username = strings.ToLower(strings.TrimSpace(username))
|
|
u, err := s.GetUser(username)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if strings.TrimSpace(name) != "" {
|
|
u.Name = strings.TrimSpace(name)
|
|
}
|
|
if strings.TrimSpace(role) != "" {
|
|
r := Role(role)
|
|
if r.IsValid() {
|
|
u.Role = string(r)
|
|
u.RoleDisplay = r.DisplayName()
|
|
}
|
|
}
|
|
if strings.TrimSpace(avatar) != "" {
|
|
newAv := strings.TrimSpace(avatar)
|
|
if newAv == "A" {
|
|
isAdmin := strings.EqualFold(u.Username, "admin") || strings.EqualFold(u.Role, "team_lead") || strings.EqualFold(u.Role, "lead")
|
|
if !isAdmin {
|
|
return nil, errors.New("the 'A' avatar is exclusively reserved for administrators")
|
|
}
|
|
}
|
|
u.Avatar = newAv
|
|
}
|
|
if strings.TrimSpace(avatarType) != "" {
|
|
u.AvatarType = strings.TrimSpace(avatarType)
|
|
}
|
|
if profileImage != "" {
|
|
u.ProfileImage = profileImage
|
|
}
|
|
if strings.TrimSpace(newPassword) != "" {
|
|
u.PasswordHash = hashPassword(newPassword)
|
|
}
|
|
u.UpdatedAt = time.Now()
|
|
|
|
_, err = s.primaryDB.Exec(`
|
|
UPDATE users
|
|
SET name = $1, role = $2, role_display = $3, avatar = $4, avatar_type = $5, profile_image = $6, password_hash = $7, updated_at = $8
|
|
WHERE username = $9
|
|
`, u.Name, u.Role, u.RoleDisplay, u.Avatar, u.AvatarType, u.ProfileImage, u.PasswordHash, u.UpdatedAt, u.Username)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to update profile: %w", err)
|
|
}
|
|
|
|
return u, nil
|
|
}
|
|
|
|
// ─────────────────────────────────────────────
|
|
// Tickets
|
|
// ─────────────────────────────────────────────
|
|
|
|
func (s *Store) CreateTicket(t *Ticket, actor *User) (*Ticket, error) {
|
|
|
|
id, err := s.nextSeq("ticket_seq", "KHR")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to generate ticket ID: %w", err)
|
|
}
|
|
t.ID = id
|
|
t.CreatedAt = time.Now()
|
|
t.UpdatedAt = t.CreatedAt
|
|
|
|
if t.Status == "" {
|
|
t.Status = string(StatusOpen)
|
|
}
|
|
if t.Priority == "" {
|
|
t.Priority = string(PriorityMedium)
|
|
}
|
|
if t.TicketType == "" {
|
|
t.TicketType = "application"
|
|
}
|
|
|
|
t.CreatedBy = actor.Username
|
|
t.CreatedByName = actor.Name
|
|
t.CreatedByRole = actor.RoleDisplay
|
|
|
|
if t.AssignedTo != "" {
|
|
var name, role string
|
|
_ = s.primaryDB.QueryRow("SELECT name, role_display FROM users WHERE username = $1", t.AssignedTo).Scan(&name, &role)
|
|
t.AssignedToName = name
|
|
t.AssignedToRole = role
|
|
}
|
|
|
|
if t.SLAHours <= 0 {
|
|
t.SLAHours = calculateDefaultSLA(t.Priority)
|
|
}
|
|
if t.DueDate == nil {
|
|
d := t.CreatedAt.Add(time.Duration(t.SLAHours) * time.Hour)
|
|
t.DueDate = &d
|
|
}
|
|
|
|
tx, err := s.primaryDB.Begin()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer tx.Rollback()
|
|
|
|
_, err = tx.Exec(`
|
|
INSERT INTO tickets (
|
|
id, ticket_type, title, general_category, department, app_name, version, feature_name, api_key, issue_type,
|
|
priority, status, description, assistance_required, additional_info, created_by, created_by_name, created_by_role,
|
|
assigned_to, assigned_to_name, assigned_to_role, linked_error_id, created_at, updated_at, due_date, sla_hours, sla_breached
|
|
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27)
|
|
`, t.ID, t.TicketType, t.Title, t.GeneralCategory, t.Department, t.AppName, t.Version, t.FeatureName, t.APIKey, t.IssueType,
|
|
t.Priority, t.Status, t.Description, t.AssistanceRequired, t.AdditionalInfo, t.CreatedBy, t.CreatedByName, t.CreatedByRole,
|
|
t.AssignedTo, t.AssignedToName, t.AssignedToRole, t.LinkedErrorID, t.CreatedAt, t.UpdatedAt, t.DueDate, t.SLAHours, t.SLABreached)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to insert ticket: %w", err)
|
|
}
|
|
|
|
// Insert tags if present
|
|
for _, tg := range t.Tags {
|
|
tg = strings.ToLower(strings.TrimSpace(tg))
|
|
if tg != "" {
|
|
_, _ = tx.Exec(`INSERT INTO ticket_tags (ticket_id, tag) VALUES ($1, $2) ON CONFLICT DO NOTHING`, t.ID, tg)
|
|
}
|
|
}
|
|
|
|
// Add creation remark
|
|
createRemarkText := fmt.Sprintf("Created ticket with priority %s.", strings.ToUpper(t.Priority))
|
|
if t.AssignedToName != "" {
|
|
createRemarkText = fmt.Sprintf("Created ticket for %s with priority %s.", t.AssignedToName, strings.ToUpper(t.Priority))
|
|
}
|
|
remID := uuid.New().String()
|
|
_, err = tx.Exec(`
|
|
INSERT INTO ticket_remarks (id, ticket_id, author_username, author_name, author_role, type, text, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, 'created', $6, $7)
|
|
`, remID, t.ID, actor.Username, actor.Name, actor.RoleDisplay, createRemarkText, t.CreatedAt)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Add Links if present
|
|
for _, l := range t.Links {
|
|
if strings.TrimSpace(l) != "" {
|
|
_, _ = tx.Exec(`INSERT INTO ticket_links (ticket_id, url, created_at) VALUES ($1, $2, $3)`, t.ID, strings.TrimSpace(l), t.CreatedAt)
|
|
}
|
|
}
|
|
|
|
// Add Attachments if present
|
|
for _, att := range t.Attachments {
|
|
if strings.TrimSpace(att.URL) != "" {
|
|
attID := att.ID
|
|
if attID == "" {
|
|
attID = uuid.New().String()
|
|
}
|
|
attType := att.Type
|
|
if attType == "" {
|
|
attType = "image"
|
|
}
|
|
attName := att.Name
|
|
if attName == "" {
|
|
attName = "uploaded_image"
|
|
}
|
|
_, _ = tx.Exec(`
|
|
INSERT INTO ticket_attachments (id, ticket_id, name, url, size, type, uploaded_by, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
|
`, attID, t.ID, attName, att.URL, att.Size, attType, actor.Username, t.CreatedAt)
|
|
}
|
|
}
|
|
|
|
if err := tx.Commit(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Realtime Broadcast
|
|
if s.Broker != nil {
|
|
s.Broker.Broadcast("ticket_created", t.ID, "", actor.Username, "create", map[string]string{"title": t.Title, "priority": t.Priority})
|
|
}
|
|
|
|
// Notification
|
|
if t.AssignedTo != "" && !strings.EqualFold(t.AssignedTo, actor.Username) {
|
|
s.addNotification(t.AssignedTo, t.ID, "New ticket assigned to you", fmt.Sprintf("%s: %s", t.ID, t.Title), "assignment")
|
|
}
|
|
|
|
return s.GetTicket(t.ID)
|
|
}
|
|
|
|
func (s *Store) GetTicket(id string) (*Ticket, error) {
|
|
|
|
var t Ticket
|
|
err := s.primaryDB.QueryRow(`
|
|
SELECT id, ticket_type, title, general_category, department, app_name, version, feature_name, api_key, issue_type,
|
|
priority, status, description, assistance_required, additional_info, created_by, created_by_name, created_by_role,
|
|
assigned_to, assigned_to_name, assigned_to_role, hold_reason, held_by, held_at, completion_remarks, completed_by,
|
|
completed_at, linked_error_id, archived, created_at, updated_at, due_date, sla_hours, sla_breached
|
|
FROM tickets WHERE id = $1
|
|
`, id).Scan(
|
|
&t.ID, &t.TicketType, &t.Title, &t.GeneralCategory, &t.Department, &t.AppName, &t.Version, &t.FeatureName, &t.APIKey, &t.IssueType,
|
|
&t.Priority, &t.Status, &t.Description, &t.AssistanceRequired, &t.AdditionalInfo, &t.CreatedBy, &t.CreatedByName, &t.CreatedByRole,
|
|
&t.AssignedTo, &t.AssignedToName, &t.AssignedToRole, &t.HoldReason, &t.HeldBy, &t.HeldAt, &t.CompletionRemarks, &t.CompletedBy,
|
|
&t.CompletedAt, &t.LinkedErrorID, &t.Archived, &t.CreatedAt, &t.UpdatedAt, &t.DueDate, &t.SLAHours, &t.SLABreached,
|
|
)
|
|
if err != nil {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
// Remarks
|
|
remRows, err := s.primaryDB.Query(`
|
|
SELECT id, author_username, author_name, author_role, type, text, created_at
|
|
FROM ticket_remarks WHERE ticket_id = $1 ORDER BY created_at ASC
|
|
`, id)
|
|
if err == nil {
|
|
defer remRows.Close()
|
|
for remRows.Next() {
|
|
var r Remark
|
|
if err := remRows.Scan(&r.ID, &r.AuthorUsername, &r.AuthorName, &r.AuthorRole, &r.Type, &r.Text, &r.CreatedAt); err == nil {
|
|
t.Remarks = append(t.Remarks, r)
|
|
}
|
|
}
|
|
}
|
|
if t.Remarks == nil {
|
|
t.Remarks = []Remark{}
|
|
}
|
|
|
|
// Attachments
|
|
attRows, err := s.primaryDB.Query(`
|
|
SELECT id, name, url, size, type, uploaded_by, created_at
|
|
FROM ticket_attachments WHERE ticket_id = $1 ORDER BY created_at ASC
|
|
`, id)
|
|
if err == nil {
|
|
defer attRows.Close()
|
|
for attRows.Next() {
|
|
var a Attachment
|
|
if err := attRows.Scan(&a.ID, &a.Name, &a.URL, &a.Size, &a.Type, &a.UploadedBy, &a.CreatedAt); err == nil {
|
|
t.Attachments = append(t.Attachments, a)
|
|
}
|
|
}
|
|
}
|
|
if t.Attachments == nil {
|
|
t.Attachments = []Attachment{}
|
|
}
|
|
|
|
// Links
|
|
linkRows, err := s.primaryDB.Query(`SELECT url FROM ticket_links WHERE ticket_id = $1 ORDER BY id ASC`, id)
|
|
if err == nil {
|
|
defer linkRows.Close()
|
|
for linkRows.Next() {
|
|
var u string
|
|
if err := linkRows.Scan(&u); err == nil {
|
|
t.Links = append(t.Links, u)
|
|
}
|
|
}
|
|
}
|
|
if t.Links == nil {
|
|
t.Links = []string{}
|
|
}
|
|
|
|
// Tags
|
|
tagRows, err := s.primaryDB.Query(`SELECT tag FROM ticket_tags WHERE ticket_id = $1 ORDER BY tag ASC`, id)
|
|
if err == nil {
|
|
defer tagRows.Close()
|
|
for tagRows.Next() {
|
|
var tg string
|
|
if err := tagRows.Scan(&tg); err == nil {
|
|
t.Tags = append(t.Tags, tg)
|
|
}
|
|
}
|
|
}
|
|
if t.Tags == nil {
|
|
t.Tags = []string{}
|
|
}
|
|
|
|
// Relations
|
|
t.RelatedTicketIDs, _ = s.GetRelatedTickets(id)
|
|
if t.RelatedTicketIDs == nil {
|
|
t.RelatedTicketIDs = []string{}
|
|
}
|
|
|
|
return &t, nil
|
|
}
|
|
|
|
func (s *Store) 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 *Store) DeleteTicket(ticketID string, actor *User) error {
|
|
var createdBy, assignedTo string
|
|
err := s.primaryDB.QueryRow("SELECT created_by, assigned_to FROM tickets WHERE id = $1", ticketID).Scan(&createdBy, &assignedTo)
|
|
if err != nil {
|
|
return errors.New("ticket not found")
|
|
}
|
|
|
|
isAdmin := s.IsAdmin(actor)
|
|
isCreator := actor != nil && strings.EqualFold(actor.Username, createdBy)
|
|
isAssignee := actor != nil && strings.EqualFold(actor.Username, assignedTo)
|
|
|
|
// Corporate Privacy & Permission Rule:
|
|
// No one can delete the ticket assigned to him/her; only the person who assigned/created it can delete that (or admin).
|
|
if isAssignee && !isCreator {
|
|
return errors.New("permission denied: you cannot delete a ticket assigned to you. Only the person who created/assigned this ticket can delete it")
|
|
}
|
|
|
|
if !isAdmin && !isCreator {
|
|
return errors.New("permission denied: only administrators or the person who assigned/created this ticket can delete it")
|
|
}
|
|
|
|
tx, err := s.primaryDB.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
|
|
// 1. Unlink any errors referencing this ticket
|
|
_, _ = tx.Exec("UPDATE errors SET linked_ticket_id = '', status = 'unresolved' WHERE linked_ticket_id = $1", ticketID)
|
|
|
|
// 2. Delete notifications referencing this ticket
|
|
_, _ = tx.Exec("DELETE FROM notifications WHERE ticket_id = $1", ticketID)
|
|
|
|
// 3. Delete ticket (cascade deletes ticket_remarks, ticket_attachments, ticket_links)
|
|
res, err := tx.Exec("DELETE FROM tickets WHERE id = $1", ticketID)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to delete ticket: %w", err)
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 0 {
|
|
return errors.New("ticket not found")
|
|
}
|
|
|
|
if err := tx.Commit(); err != nil {
|
|
return err
|
|
}
|
|
|
|
if s.Broker != nil {
|
|
actorName := "unknown"
|
|
if actor != nil {
|
|
actorName = actor.Username
|
|
}
|
|
s.Broker.Broadcast("ticket_deleted", ticketID, "", actorName, "delete", nil)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
type AppMeta struct {
|
|
Name string `json:"name"`
|
|
Roles []string `json:"roles"`
|
|
TicketCount int `json:"ticket_count"`
|
|
}
|
|
|
|
func (s *Store) ListApps(targetRole, query string) []AppMeta {
|
|
appMap := make(map[string]*AppMeta)
|
|
|
|
// 1. Query distinct app_name from tickets with associated user roles
|
|
rows, err := s.primaryDB.Query(`
|
|
SELECT t.app_name, COALESCE(u.role, ''), COUNT(*)
|
|
FROM tickets t
|
|
LEFT JOIN users u ON LOWER(t.assigned_to) = LOWER(u.username)
|
|
WHERE t.app_name IS NOT NULL AND t.app_name != ''
|
|
GROUP BY t.app_name, COALESCE(u.role, '')
|
|
`)
|
|
if err == nil {
|
|
defer rows.Close()
|
|
for rows.Next() {
|
|
var appName, role string
|
|
var cnt int
|
|
if err := rows.Scan(&appName, &role, &cnt); err == nil {
|
|
appName = strings.TrimSpace(appName)
|
|
if appName == "" {
|
|
continue
|
|
}
|
|
if _, ok := appMap[appName]; !ok {
|
|
appMap[appName] = &AppMeta{
|
|
Name: appName,
|
|
Roles: []string{},
|
|
}
|
|
}
|
|
appMap[appName].TicketCount += cnt
|
|
if role != "" {
|
|
hasRole := false
|
|
for _, r := range appMap[appName].Roles {
|
|
if strings.EqualFold(r, role) {
|
|
hasRole = true
|
|
break
|
|
}
|
|
}
|
|
if !hasRole {
|
|
appMap[appName].Roles = append(appMap[appName].Roles, role)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// 2. Also check errors table for distinct app_name
|
|
errRows, err := s.primaryDB.Query(`
|
|
SELECT DISTINCT app_name FROM errors WHERE app_name IS NOT NULL AND app_name != ''
|
|
`)
|
|
if err == nil {
|
|
defer errRows.Close()
|
|
for errRows.Next() {
|
|
var appName string
|
|
if err := errRows.Scan(&appName); err == nil {
|
|
appName = strings.TrimSpace(appName)
|
|
if appName != "" && appMap[appName] == nil {
|
|
appMap[appName] = &AppMeta{
|
|
Name: appName,
|
|
Roles: []string{},
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// 3. Fallback standard applications if not present in DB
|
|
defaults := []string{
|
|
"Creator Suite Web",
|
|
"Creator Suite iOS",
|
|
"Creator Suite Android",
|
|
"FastAPI Backend",
|
|
"Image Manipulator Pro",
|
|
"Unified Dashboard Client",
|
|
"Unified Dashboard iOS",
|
|
"Unified Dashboard Android",
|
|
"Batch Inpaint Service",
|
|
"Nexus Gateway",
|
|
}
|
|
for _, defApp := range defaults {
|
|
if appMap[defApp] == nil {
|
|
roles := []string{}
|
|
nameLower := strings.ToLower(defApp)
|
|
if strings.Contains(nameLower, "android") {
|
|
roles = append(roles, "android_dev")
|
|
}
|
|
if strings.Contains(nameLower, "ios") {
|
|
roles = append(roles, "ios_dev")
|
|
}
|
|
if strings.Contains(nameLower, "backend") || strings.Contains(nameLower, "service") || strings.Contains(nameLower, "gateway") {
|
|
roles = append(roles, "backend_dev")
|
|
}
|
|
appMap[defApp] = &AppMeta{
|
|
Name: defApp,
|
|
Roles: roles,
|
|
}
|
|
}
|
|
}
|
|
|
|
// 4. Role-based filtering:
|
|
// "suppose the assignee is from iOS developer then no apps which is associated to an android developer should be shown,
|
|
// if assignee is backend developer then every app should be shown as suggestion while typing"
|
|
var result []AppMeta
|
|
qLower := strings.ToLower(strings.TrimSpace(query))
|
|
targetRole = strings.ToLower(strings.TrimSpace(targetRole))
|
|
|
|
for _, meta := range appMap {
|
|
if qLower != "" && !strings.Contains(strings.ToLower(meta.Name), qLower) {
|
|
continue
|
|
}
|
|
|
|
nameLower := strings.ToLower(meta.Name)
|
|
isAndroidApp := strings.Contains(nameLower, "android")
|
|
isIOSApp := strings.Contains(nameLower, "ios")
|
|
for _, r := range meta.Roles {
|
|
if strings.EqualFold(r, "android_dev") {
|
|
isAndroidApp = true
|
|
}
|
|
if strings.EqualFold(r, "ios_dev") {
|
|
isIOSApp = true
|
|
}
|
|
}
|
|
|
|
if targetRole == "ios_dev" {
|
|
// No apps associated to an android developer should be shown
|
|
if isAndroidApp {
|
|
continue
|
|
}
|
|
} else if targetRole == "android_dev" {
|
|
// No apps associated to an iOS developer should be shown
|
|
if isIOSApp {
|
|
continue
|
|
}
|
|
}
|
|
// if backend_dev (or any other), every app is included!
|
|
|
|
result = append(result, *meta)
|
|
}
|
|
|
|
sort.Slice(result, func(i, j int) bool {
|
|
return result[i].Name < result[j].Name
|
|
})
|
|
|
|
return result
|
|
}
|
|
|
|
func (s *Store) ListTickets(status, priority, app, assignee, reporter, query, ticketType string) []*Ticket {
|
|
|
|
var conds []string
|
|
var args []any
|
|
idx := 1
|
|
|
|
if status != "" {
|
|
conds = append(conds, fmt.Sprintf("LOWER(status) = LOWER($%d)", idx))
|
|
args = append(args, status)
|
|
idx++
|
|
}
|
|
if priority != "" {
|
|
conds = append(conds, fmt.Sprintf("LOWER(priority) = LOWER($%d)", idx))
|
|
args = append(args, priority)
|
|
idx++
|
|
}
|
|
if app != "" {
|
|
conds = append(conds, fmt.Sprintf("LOWER(app_name) = LOWER($%d)", idx))
|
|
args = append(args, app)
|
|
idx++
|
|
}
|
|
if assignee != "" {
|
|
conds = append(conds, fmt.Sprintf("LOWER(assigned_to) = LOWER($%d)", idx))
|
|
args = append(args, assignee)
|
|
idx++
|
|
}
|
|
if reporter != "" {
|
|
conds = append(conds, fmt.Sprintf("LOWER(created_by) = LOWER($%d)", idx))
|
|
args = append(args, reporter)
|
|
idx++
|
|
}
|
|
if ticketType != "" {
|
|
conds = append(conds, fmt.Sprintf("LOWER(ticket_type) = LOWER($%d)", idx))
|
|
args = append(args, ticketType)
|
|
idx++
|
|
}
|
|
if query != "" {
|
|
q := "%" + strings.ToLower(query) + "%"
|
|
conds = append(conds, fmt.Sprintf("(LOWER(id) LIKE $%d OR LOWER(title) LIKE $%d OR LOWER(description) LIKE $%d OR LOWER(feature_name) LIKE $%d)", idx, idx, idx, idx))
|
|
args = append(args, q)
|
|
idx++
|
|
}
|
|
|
|
whereClause := ""
|
|
if len(conds) > 0 {
|
|
whereClause = "WHERE " + strings.Join(conds, " AND ")
|
|
}
|
|
|
|
querySQL := fmt.Sprintf(`
|
|
SELECT id, ticket_type, title, general_category, department, app_name, version, feature_name, api_key, issue_type,
|
|
priority, status, description, assistance_required, additional_info, created_by, created_by_name, created_by_role,
|
|
assigned_to, assigned_to_name, assigned_to_role, hold_reason, held_by, held_at, completion_remarks, completed_by,
|
|
completed_at, linked_error_id, archived, created_at, updated_at, due_date, sla_hours, sla_breached
|
|
FROM tickets
|
|
%s
|
|
ORDER BY created_at DESC
|
|
`, whereClause)
|
|
|
|
rows, err := s.primaryDB.Query(querySQL, args...)
|
|
if err != nil {
|
|
return []*Ticket{}
|
|
}
|
|
defer rows.Close()
|
|
|
|
var list []*Ticket
|
|
for rows.Next() {
|
|
var t Ticket
|
|
if err := rows.Scan(
|
|
&t.ID, &t.TicketType, &t.Title, &t.GeneralCategory, &t.Department, &t.AppName, &t.Version, &t.FeatureName, &t.APIKey, &t.IssueType,
|
|
&t.Priority, &t.Status, &t.Description, &t.AssistanceRequired, &t.AdditionalInfo, &t.CreatedBy, &t.CreatedByName, &t.CreatedByRole,
|
|
&t.AssignedTo, &t.AssignedToName, &t.AssignedToRole, &t.HoldReason, &t.HeldBy, &t.HeldAt, &t.CompletionRemarks, &t.CompletedBy,
|
|
&t.CompletedAt, &t.LinkedErrorID, &t.Archived, &t.CreatedAt, &t.UpdatedAt, &t.DueDate, &t.SLAHours, &t.SLABreached,
|
|
); err == nil {
|
|
t.Remarks = []Remark{}
|
|
t.Attachments = []Attachment{}
|
|
t.Links = []string{}
|
|
t.Tags = []string{}
|
|
list = append(list, &t)
|
|
}
|
|
}
|
|
|
|
// Fetch remarks for listed tickets to populate remark badges
|
|
if len(list) > 0 {
|
|
tIDs := make([]string, len(list))
|
|
tIdxMap := make(map[string]*Ticket)
|
|
for i, t := range list {
|
|
tIDs[i] = fmt.Sprintf("'%s'", strings.ReplaceAll(t.ID, "'", "''"))
|
|
tIdxMap[t.ID] = t
|
|
}
|
|
inClause := strings.Join(tIDs, ",")
|
|
remRows, err := s.primaryDB.Query(fmt.Sprintf(`
|
|
SELECT id, ticket_id, author_username, author_name, author_role, type, text, created_at
|
|
FROM ticket_remarks WHERE ticket_id IN (%s) ORDER BY created_at ASC
|
|
`, inClause))
|
|
if err == nil {
|
|
defer remRows.Close()
|
|
for remRows.Next() {
|
|
var r Remark
|
|
var tid string
|
|
if err := remRows.Scan(&r.ID, &tid, &r.AuthorUsername, &r.AuthorName, &r.AuthorRole, &r.Type, &r.Text, &r.CreatedAt); err == nil {
|
|
if t, exists := tIdxMap[tid]; exists {
|
|
t.Remarks = append(t.Remarks, r)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Fetch tags for listed tickets
|
|
tagRows, err := s.primaryDB.Query(fmt.Sprintf(`
|
|
SELECT ticket_id, tag FROM ticket_tags WHERE ticket_id IN (%s)
|
|
`, inClause))
|
|
if err == nil {
|
|
defer tagRows.Close()
|
|
for tagRows.Next() {
|
|
var tid, tg string
|
|
if err := tagRows.Scan(&tid, &tg); err == nil {
|
|
if t, exists := tIdxMap[tid]; exists {
|
|
t.Tags = append(t.Tags, tg)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return list
|
|
}
|
|
|
|
func (s *Store) AddRemark(ticketID string, actor *User, remType, text string) (*Ticket, error) {
|
|
|
|
text = strings.TrimSpace(text)
|
|
if text == "" {
|
|
return nil, errors.New("remark text cannot be empty")
|
|
}
|
|
if remType == "" {
|
|
remType = "comment"
|
|
}
|
|
|
|
var exists bool
|
|
_ = s.primaryDB.QueryRow("SELECT EXISTS(SELECT 1 FROM tickets WHERE id = $1)", ticketID).Scan(&exists)
|
|
if !exists {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
remID := uuid.New().String()
|
|
now := time.Now()
|
|
|
|
_, err := s.primaryDB.Exec(`
|
|
INSERT INTO ticket_remarks (id, ticket_id, author_username, author_name, author_role, type, text, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
|
`, remID, ticketID, actor.Username, actor.Name, actor.RoleDisplay, remType, text, now)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
_, _ = s.primaryDB.Exec(`UPDATE tickets SET updated_at = $1 WHERE id = $2`, now, ticketID)
|
|
|
|
// Notify ticket assignee and creator
|
|
var assignedTo, createdBy string
|
|
_ = s.primaryDB.QueryRow("SELECT assigned_to, created_by FROM tickets WHERE id = $1", ticketID).Scan(&assignedTo, &createdBy)
|
|
if assignedTo != "" && !strings.EqualFold(assignedTo, actor.Username) {
|
|
s.addNotification(assignedTo, ticketID, "New remark on ticket", fmt.Sprintf("%s: %s commented", ticketID, actor.Name), "remark")
|
|
}
|
|
if createdBy != "" && !strings.EqualFold(createdBy, actor.Username) && !strings.EqualFold(createdBy, assignedTo) {
|
|
s.addNotification(createdBy, ticketID, "New remark on ticket", fmt.Sprintf("%s: %s commented", ticketID, actor.Name), "remark")
|
|
}
|
|
|
|
if s.Broker != nil {
|
|
s.Broker.Broadcast("remark_added", ticketID, "", actor.Username, "remark", map[string]string{"text": text, "type": remType})
|
|
}
|
|
|
|
return s.GetTicket(ticketID)
|
|
}
|
|
|
|
func (s *Store) HoldTicket(ticketID string, actor *User, reason string) (*Ticket, error) {
|
|
|
|
now := time.Now()
|
|
res, err := s.primaryDB.Exec(`
|
|
UPDATE tickets
|
|
SET status = 'on_hold', hold_reason = $1, held_by = $2, held_at = $3, updated_at = $3
|
|
WHERE id = $4
|
|
`, reason, actor.Name, now, ticketID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 0 {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
remID := uuid.New().String()
|
|
_, _ = s.primaryDB.Exec(`
|
|
INSERT INTO ticket_remarks (id, ticket_id, author_username, author_name, author_role, type, text, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, 'hold', $6, $7)
|
|
`, remID, ticketID, actor.Username, actor.Name, actor.RoleDisplay, "Placed ticket on hold: "+reason, now)
|
|
|
|
var assignedTo string
|
|
_ = s.primaryDB.QueryRow("SELECT assigned_to FROM tickets WHERE id = $1", ticketID).Scan(&assignedTo)
|
|
if assignedTo != "" && !strings.EqualFold(assignedTo, actor.Username) {
|
|
s.addNotification(assignedTo, ticketID, "Ticket placed on hold", fmt.Sprintf("%s placed on hold by %s", ticketID, actor.Name), "hold")
|
|
}
|
|
|
|
if s.Broker != nil {
|
|
s.Broker.Broadcast("ticket_held", ticketID, "", actor.Username, "hold", map[string]string{"reason": reason})
|
|
}
|
|
|
|
return s.GetTicket(ticketID)
|
|
}
|
|
|
|
func (s *Store) ResumeTicket(ticketID string, actor *User, remarks string) (*Ticket, error) {
|
|
|
|
now := time.Now()
|
|
res, err := s.primaryDB.Exec(`
|
|
UPDATE tickets
|
|
SET status = 'in_progress', hold_reason = '', held_by = '', held_at = NULL, updated_at = $1
|
|
WHERE id = $2
|
|
`, now, ticketID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 0 {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
remText := "Ticket resumed."
|
|
if strings.TrimSpace(remarks) != "" {
|
|
remText = "Ticket resumed: " + remarks
|
|
}
|
|
|
|
remID := uuid.New().String()
|
|
_, _ = s.primaryDB.Exec(`
|
|
INSERT INTO ticket_remarks (id, ticket_id, author_username, author_name, author_role, type, text, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, 'resume', $6, $7)
|
|
`, remID, ticketID, actor.Username, actor.Name, actor.RoleDisplay, remText, now)
|
|
|
|
if s.Broker != nil {
|
|
s.Broker.Broadcast("ticket_resumed", ticketID, "", actor.Username, "resume", nil)
|
|
}
|
|
|
|
return s.GetTicket(ticketID)
|
|
}
|
|
|
|
func (s *Store) CompleteTicket(ticketID string, actor *User, remarks string) (*Ticket, error) {
|
|
|
|
now := time.Now()
|
|
res, err := s.primaryDB.Exec(`
|
|
UPDATE tickets
|
|
SET status = 'completed', completion_remarks = $1, completed_by = $2, completed_at = $3, updated_at = $3
|
|
WHERE id = $4
|
|
`, remarks, actor.Name, now, ticketID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 0 {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
remID := uuid.New().String()
|
|
_, _ = s.primaryDB.Exec(`
|
|
INSERT INTO ticket_remarks (id, ticket_id, author_username, author_name, author_role, type, text, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, 'complete', $6, $7)
|
|
`, remID, ticketID, actor.Username, actor.Name, actor.RoleDisplay, "Ticket resolved and completed: "+remarks, now)
|
|
|
|
var createdBy string
|
|
_ = s.primaryDB.QueryRow("SELECT created_by FROM tickets WHERE id = $1", ticketID).Scan(&createdBy)
|
|
if createdBy != "" && !strings.EqualFold(createdBy, actor.Username) {
|
|
s.addNotification(createdBy, ticketID, "Ticket completed", fmt.Sprintf("%s was marked as completed by %s", ticketID, actor.Name), "complete")
|
|
}
|
|
|
|
if s.Broker != nil {
|
|
s.Broker.Broadcast("ticket_completed", ticketID, "", actor.Username, "complete", map[string]string{"remarks": remarks})
|
|
}
|
|
|
|
return s.GetTicket(ticketID)
|
|
}
|
|
|
|
func (s *Store) ArchiveTicket(ticketID string, actor *User) (*Ticket, error) {
|
|
var status, createdBy, assignedTo, completedBy string
|
|
err := s.primaryDB.QueryRow("SELECT status, created_by, assigned_to, completed_by FROM tickets WHERE id = $1", ticketID).Scan(&status, &createdBy, &assignedTo, &completedBy)
|
|
if err != nil {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
st := strings.ToLower(status)
|
|
if st != "completed" && st != "closed" {
|
|
return nil, errors.New("only completed or resolved tickets can be moved to the archive")
|
|
}
|
|
|
|
isAdmin := s.IsAdmin(actor)
|
|
isCreator := actor != nil && strings.EqualFold(actor.Username, createdBy)
|
|
isResolver := actor != nil && (strings.EqualFold(actor.Username, completedBy) || strings.EqualFold(actor.Name, completedBy))
|
|
|
|
// Corporate Privacy & Permission Rule:
|
|
// Only the person who resolved the ticket (or the assigner/admin) can move it to archive.
|
|
if !isAdmin && !isCreator && !isResolver {
|
|
return nil, errors.New("permission denied: only the person who resolved this ticket (or the assigner/admin) can move it to archive")
|
|
}
|
|
|
|
now := time.Now()
|
|
_, err = s.primaryDB.Exec("UPDATE tickets SET archived = TRUE, updated_at = $1 WHERE id = $2", now, ticketID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
remID := uuid.New().String()
|
|
actorName := "System"
|
|
actorRole := "admin"
|
|
actorUsername := "system"
|
|
if actor != nil {
|
|
actorName = actor.Name
|
|
actorRole = actor.RoleDisplay
|
|
actorUsername = actor.Username
|
|
}
|
|
_, _ = s.primaryDB.Exec(`
|
|
INSERT INTO ticket_remarks (id, ticket_id, author_username, author_name, author_role, type, text, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, 'archive', $6, $7)
|
|
`, remID, ticketID, actorUsername, actorName, actorRole, "Moved ticket to archive.", now)
|
|
|
|
if s.Broker != nil {
|
|
s.Broker.Broadcast("ticket_archived", ticketID, "", actorUsername, "archive", nil)
|
|
}
|
|
|
|
return s.GetTicket(ticketID)
|
|
}
|
|
|
|
func (s *Store) UnarchiveTicket(ticketID string, actor *User) (*Ticket, error) {
|
|
var status, createdBy, assignedTo, completedBy string
|
|
err := s.primaryDB.QueryRow("SELECT status, created_by, assigned_to, completed_by FROM tickets WHERE id = $1", ticketID).Scan(&status, &createdBy, &assignedTo, &completedBy)
|
|
if err != nil {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
isAdmin := s.IsAdmin(actor)
|
|
isCreator := actor != nil && strings.EqualFold(actor.Username, createdBy)
|
|
isResolver := actor != nil && (strings.EqualFold(actor.Username, completedBy) || strings.EqualFold(actor.Name, completedBy))
|
|
|
|
if !isAdmin && !isCreator && !isResolver {
|
|
return nil, errors.New("permission denied: only the person who resolved this ticket (or the assigner/admin) can restore it from archive")
|
|
}
|
|
|
|
now := time.Now()
|
|
res, err := s.primaryDB.Exec("UPDATE tickets SET archived = FALSE, updated_at = $1 WHERE id = $2", now, ticketID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 0 {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
remID := uuid.New().String()
|
|
actorName := "System"
|
|
actorRole := "admin"
|
|
actorUsername := "system"
|
|
if actor != nil {
|
|
actorName = actor.Name
|
|
actorRole = actor.RoleDisplay
|
|
actorUsername = actor.Username
|
|
}
|
|
_, _ = s.primaryDB.Exec(`
|
|
INSERT INTO ticket_remarks (id, ticket_id, author_username, author_name, author_role, type, text, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, 'unarchive', $6, $7)
|
|
`, remID, ticketID, actorUsername, actorName, actorRole, "Restored ticket from archive.", now)
|
|
|
|
if s.Broker != nil {
|
|
s.Broker.Broadcast("ticket_unarchived", ticketID, "", actorUsername, "unarchive", nil)
|
|
}
|
|
|
|
return s.GetTicket(ticketID)
|
|
}
|
|
|
|
func (s *Store) ChangePriority(ticketID string, actor *User, priority, note string) (*Ticket, error) {
|
|
|
|
priority = strings.ToLower(strings.TrimSpace(priority))
|
|
now := time.Now()
|
|
res, err := s.primaryDB.Exec(`
|
|
UPDATE tickets
|
|
SET priority = $1, updated_at = $2
|
|
WHERE id = $3
|
|
`, priority, now, ticketID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 0 {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
remText := fmt.Sprintf("Changed priority to %s.", strings.ToUpper(priority))
|
|
if strings.TrimSpace(note) != "" {
|
|
remText += " Reason: " + note
|
|
}
|
|
|
|
remID := uuid.New().String()
|
|
_, _ = s.primaryDB.Exec(`
|
|
INSERT INTO ticket_remarks (id, ticket_id, author_username, author_name, author_role, type, text, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, 'priority', $6, $7)
|
|
`, remID, ticketID, actor.Username, actor.Name, actor.RoleDisplay, remText, now)
|
|
|
|
if s.Broker != nil {
|
|
s.Broker.Broadcast("ticket_priority", ticketID, "", actor.Username, "priority", map[string]string{"priority": priority})
|
|
}
|
|
|
|
return s.GetTicket(ticketID)
|
|
}
|
|
|
|
func (s *Store) ReassignTicket(ticketID string, actor *User, newAssignee, note string) (*Ticket, error) {
|
|
|
|
newAssignee = strings.ToLower(strings.TrimSpace(newAssignee))
|
|
var name, role string
|
|
err := s.primaryDB.QueryRow("SELECT name, role_display FROM users WHERE username = $1", newAssignee).Scan(&name, &role)
|
|
if err != nil {
|
|
return nil, errors.New("assignee user not found")
|
|
}
|
|
|
|
now := time.Now()
|
|
res, err := s.primaryDB.Exec(`
|
|
UPDATE tickets
|
|
SET assigned_to = $1, assigned_to_name = $2, assigned_to_role = $3, updated_at = $4
|
|
WHERE id = $5
|
|
`, newAssignee, name, role, now, ticketID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 0 {
|
|
return nil, errors.New("ticket not found")
|
|
}
|
|
|
|
remText := fmt.Sprintf("Reassigned ticket to %s (%s).", name, role)
|
|
if strings.TrimSpace(note) != "" {
|
|
remText += " Note: " + note
|
|
}
|
|
|
|
remID := uuid.New().String()
|
|
_, _ = s.primaryDB.Exec(`
|
|
INSERT INTO ticket_remarks (id, ticket_id, author_username, author_name, author_role, type, text, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, 'reassigned', $6, $7)
|
|
`, remID, ticketID, actor.Username, actor.Name, actor.RoleDisplay, remText, now)
|
|
|
|
if !strings.EqualFold(newAssignee, actor.Username) {
|
|
s.addNotification(newAssignee, ticketID, "Ticket reassigned to you", fmt.Sprintf("%s was reassigned to you by %s", ticketID, actor.Name), "assignment")
|
|
}
|
|
|
|
if s.Broker != nil {
|
|
s.Broker.Broadcast("ticket_reassigned", ticketID, "", actor.Username, "reassign", map[string]string{"assigned_to": newAssignee})
|
|
}
|
|
|
|
return s.GetTicket(ticketID)
|
|
}
|
|
|
|
func (s *Store) AddAttachment(ticketID string, actor *User, att Attachment) (*Ticket, error) {
|
|
|
|
att.ID = uuid.New().String()
|
|
att.CreatedAt = time.Now()
|
|
att.UploadedBy = actor.Name
|
|
|
|
_, err := s.primaryDB.Exec(`
|
|
INSERT INTO ticket_attachments (id, ticket_id, name, url, size, type, uploaded_by, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
|
`, att.ID, ticketID, att.Name, att.URL, att.Size, att.Type, att.UploadedBy, att.CreatedAt)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
_, _ = s.primaryDB.Exec(`UPDATE tickets SET updated_at = $1 WHERE id = $2`, att.CreatedAt, ticketID)
|
|
|
|
if s.Broker != nil {
|
|
s.Broker.Broadcast("ticket_updated", ticketID, "", actor.Username, "attachment", nil)
|
|
}
|
|
|
|
return s.GetTicket(ticketID)
|
|
}
|
|
|
|
func (s *Store) AddLink(ticketID string, actor *User, link string) (*Ticket, error) {
|
|
|
|
link = strings.TrimSpace(link)
|
|
if link == "" {
|
|
return nil, errors.New("link cannot be empty")
|
|
}
|
|
|
|
now := time.Now()
|
|
_, err := s.primaryDB.Exec(`INSERT INTO ticket_links (ticket_id, url, created_at) VALUES ($1, $2, $3)`, ticketID, link, now)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
_, _ = s.primaryDB.Exec(`UPDATE tickets SET updated_at = $1 WHERE id = $2`, now, ticketID)
|
|
|
|
if s.Broker != nil {
|
|
s.Broker.Broadcast("ticket_updated", ticketID, "", actor.Username, "link", nil)
|
|
}
|
|
|
|
return s.GetTicket(ticketID)
|
|
}
|
|
|
|
// ─────────────────────────────────────────────
|
|
// Notifications
|
|
// ─────────────────────────────────────────────
|
|
|
|
func (s *Store) addNotification(userID, ticketID, title, msg, notifType string) {
|
|
id := uuid.New().String()
|
|
_, _ = s.primaryDB.Exec(`
|
|
INSERT INTO notifications (id, user_id, ticket_id, title, message, type, read, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, $6, FALSE, $7)
|
|
`, id, strings.ToLower(userID), ticketID, title, msg, notifType, time.Now())
|
|
|
|
if s.Broker != nil {
|
|
s.Broker.Broadcast("notification", ticketID, "", strings.ToLower(userID), notifType, map[string]string{"title": title, "message": msg})
|
|
}
|
|
}
|
|
|
|
func (s *Store) GetNotifications(username string) []Notification {
|
|
|
|
rows, err := s.primaryDB.Query(`
|
|
SELECT id, user_id, ticket_id, title, message, type, read, created_at
|
|
FROM notifications WHERE LOWER(user_id) = LOWER($1)
|
|
ORDER BY created_at DESC LIMIT 30
|
|
`, username)
|
|
if err != nil {
|
|
return []Notification{}
|
|
}
|
|
defer rows.Close()
|
|
|
|
var list []Notification
|
|
for rows.Next() {
|
|
var n Notification
|
|
if err := rows.Scan(&n.ID, &n.UserID, &n.TicketID, &n.Title, &n.Message, &n.Type, &n.Read, &n.CreatedAt); err == nil {
|
|
list = append(list, n)
|
|
}
|
|
}
|
|
return list
|
|
}
|
|
|
|
func (s *Store) MarkNotificationsRead(username string) {
|
|
|
|
_, _ = s.primaryDB.Exec(`UPDATE notifications SET read = TRUE WHERE LOWER(user_id) = LOWER($1)`, username)
|
|
}
|
|
|
|
// ─────────────────────────────────────────────
|
|
// Errors
|
|
// ─────────────────────────────────────────────
|
|
|
|
func (s *Store) IngestError(errItem *AppError, actor *User) (*AppError, error) {
|
|
|
|
if errItem.AppName == "" || errItem.ExceptionType == "" || errItem.Message == "" {
|
|
return nil, errors.New("app_name, exception_type and message are required")
|
|
}
|
|
|
|
// Fingerprint for deduplication
|
|
fpRaw := fmt.Sprintf("%s:%s:%s", errItem.AppName, errItem.ExceptionType, errItem.Message)
|
|
h := sha256.Sum256([]byte(fpRaw))
|
|
fingerprint := fmt.Sprintf("%x", h)[:16]
|
|
|
|
now := time.Now()
|
|
|
|
// Check if already exists with same fingerprint
|
|
var existingID string
|
|
var occurrences int
|
|
err := s.primaryDB.QueryRow(`
|
|
SELECT id, occurrences FROM errors WHERE fingerprint = $1 AND status != 'resolved'
|
|
`, fingerprint).Scan(&existingID, &occurrences)
|
|
|
|
if err == nil && existingID != "" {
|
|
// Update existing error occurrences
|
|
_, _ = s.primaryDB.Exec(`
|
|
UPDATE errors SET occurrences = occurrences + 1, last_seen = $1 WHERE id = $2
|
|
`, now, existingID)
|
|
return s.GetError(existingID)
|
|
}
|
|
|
|
id, err := s.nextSeq("error_seq", "ERR")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
errItem.ID = id
|
|
errItem.Fingerprint = fingerprint
|
|
errItem.Occurrences = 1
|
|
errItem.FirstSeen = now
|
|
errItem.LastSeen = now
|
|
errItem.Status = string(ErrorStatusUnresolved)
|
|
if actor != nil {
|
|
errItem.CreatedBy = actor.Username
|
|
}
|
|
|
|
_, err = s.primaryDB.Exec(`
|
|
INSERT INTO errors (
|
|
id, fingerprint, app_name, version, environment, service, endpoint, exception_type, message,
|
|
stack_trace, severity, status, occurrences, first_seen, last_seen, created_by, request_payload, created_at
|
|
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18)
|
|
`, errItem.ID, errItem.Fingerprint, errItem.AppName, errItem.Version, errItem.Environment, errItem.Service,
|
|
errItem.Endpoint, errItem.ExceptionType, errItem.Message, errItem.StackTrace, errItem.Severity,
|
|
errItem.Status, errItem.Occurrences, errItem.FirstSeen, errItem.LastSeen, errItem.CreatedBy,
|
|
errItem.RequestPayload, now)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to insert error: %w", err)
|
|
}
|
|
|
|
if s.Broker != nil {
|
|
s.Broker.Broadcast("error_logged", "", errItem.ID, "", "log", map[string]string{"app": errItem.AppName, "severity": errItem.Severity})
|
|
}
|
|
|
|
return errItem, nil
|
|
}
|
|
|
|
func (s *Store) GetError(id string) (*AppError, error) {
|
|
|
|
var e AppError
|
|
err := s.primaryDB.QueryRow(`
|
|
SELECT id, fingerprint, app_name, version, environment, service, endpoint, exception_type, message,
|
|
stack_trace, severity, status, occurrences, first_seen, last_seen, resolved_at, resolved_by,
|
|
resolution_notes, linked_ticket_id, created_by, request_payload, archived
|
|
FROM errors WHERE id = $1
|
|
`, id).Scan(
|
|
&e.ID, &e.Fingerprint, &e.AppName, &e.Version, &e.Environment, &e.Service, &e.Endpoint, &e.ExceptionType, &e.Message,
|
|
&e.StackTrace, &e.Severity, &e.Status, &e.Occurrences, &e.FirstSeen, &e.LastSeen, &e.ResolvedAt, &e.ResolvedBy,
|
|
&e.ResolutionNotes, &e.LinkedTicketID, &e.CreatedBy, &e.RequestPayload, &e.Archived,
|
|
)
|
|
if err != nil {
|
|
return nil, errors.New("error not found")
|
|
}
|
|
return &e, nil
|
|
}
|
|
|
|
func (s *Store) ListErrors(status, severity, app, query string) []*AppError {
|
|
|
|
var conds []string
|
|
var args []any
|
|
idx := 1
|
|
|
|
if status != "" {
|
|
conds = append(conds, fmt.Sprintf("LOWER(status) = LOWER($%d)", idx))
|
|
args = append(args, status)
|
|
idx++
|
|
}
|
|
if severity != "" {
|
|
conds = append(conds, fmt.Sprintf("LOWER(severity) = LOWER($%d)", idx))
|
|
args = append(args, severity)
|
|
idx++
|
|
}
|
|
if app != "" {
|
|
conds = append(conds, fmt.Sprintf("LOWER(app_name) = LOWER($%d)", idx))
|
|
args = append(args, app)
|
|
idx++
|
|
}
|
|
if query != "" {
|
|
q := "%" + strings.ToLower(query) + "%"
|
|
conds = append(conds, fmt.Sprintf("(LOWER(id) LIKE $%d OR LOWER(message) LIKE $%d OR LOWER(exception_type) LIKE $%d OR LOWER(endpoint) LIKE $%d)", idx, idx, idx, idx))
|
|
args = append(args, q)
|
|
idx++
|
|
}
|
|
|
|
whereClause := ""
|
|
if len(conds) > 0 {
|
|
whereClause = "WHERE " + strings.Join(conds, " AND ")
|
|
}
|
|
|
|
querySQL := fmt.Sprintf(`
|
|
SELECT id, fingerprint, app_name, version, environment, service, endpoint, exception_type, message,
|
|
stack_trace, severity, status, occurrences, first_seen, last_seen, resolved_at, resolved_by,
|
|
resolution_notes, linked_ticket_id, created_by, request_payload, archived
|
|
FROM errors
|
|
%s
|
|
ORDER BY last_seen DESC LIMIT 100
|
|
`, whereClause)
|
|
|
|
rows, err := s.primaryDB.Query(querySQL, args...)
|
|
if err != nil {
|
|
return []*AppError{}
|
|
}
|
|
defer rows.Close()
|
|
|
|
var list []*AppError
|
|
for rows.Next() {
|
|
var e AppError
|
|
if err := rows.Scan(
|
|
&e.ID, &e.Fingerprint, &e.AppName, &e.Version, &e.Environment, &e.Service, &e.Endpoint, &e.ExceptionType, &e.Message,
|
|
&e.StackTrace, &e.Severity, &e.Status, &e.Occurrences, &e.FirstSeen, &e.LastSeen, &e.ResolvedAt, &e.ResolvedBy,
|
|
&e.ResolutionNotes, &e.LinkedTicketID, &e.CreatedBy, &e.RequestPayload, &e.Archived,
|
|
); err == nil {
|
|
list = append(list, &e)
|
|
}
|
|
}
|
|
return list
|
|
}
|
|
|
|
func (s *Store) GetErrorStats() map[string]int {
|
|
|
|
stats := map[string]int{
|
|
"total": 0,
|
|
"unresolved": 0,
|
|
"investigating": 0,
|
|
"resolved": 0,
|
|
"critical": 0,
|
|
"high": 0,
|
|
"escalated": 0,
|
|
}
|
|
|
|
rows, err := s.primaryDB.Query(`SELECT status, severity, linked_ticket_id FROM errors`)
|
|
if err != nil {
|
|
return stats
|
|
}
|
|
defer rows.Close()
|
|
|
|
for rows.Next() {
|
|
var st, sev, lk string
|
|
if err := rows.Scan(&st, &sev, &lk); err == nil {
|
|
stats["total"]++
|
|
switch strings.ToLower(st) {
|
|
case "unresolved":
|
|
stats["unresolved"]++
|
|
case "investigating":
|
|
stats["investigating"]++
|
|
case "resolved":
|
|
stats["resolved"]++
|
|
}
|
|
switch strings.ToLower(sev) {
|
|
case "critical":
|
|
stats["critical"]++
|
|
case "high":
|
|
stats["high"]++
|
|
}
|
|
if lk != "" {
|
|
stats["escalated"]++
|
|
}
|
|
}
|
|
}
|
|
return stats
|
|
}
|
|
|
|
func (s *Store) UpdateErrorStatus(id string, status ErrorStatus, notes string, actor *User) (*AppError, error) {
|
|
|
|
now := time.Now()
|
|
var res sql.Result
|
|
var err error
|
|
|
|
if status == ErrorStatusResolved {
|
|
res, err = s.primaryDB.Exec(`
|
|
UPDATE errors
|
|
SET status = $1, resolution_notes = $2, resolved_by = $3, resolved_at = $4
|
|
WHERE id = $5
|
|
`, string(status), notes, actor.Name, now, id)
|
|
} else {
|
|
res, err = s.primaryDB.Exec(`
|
|
UPDATE errors
|
|
SET status = $1, resolution_notes = $2
|
|
WHERE id = $3
|
|
`, string(status), notes, id)
|
|
}
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 0 {
|
|
return nil, errors.New("error not found")
|
|
}
|
|
|
|
if s.Broker != nil {
|
|
actorName := "unknown"
|
|
if actor != nil {
|
|
actorName = actor.Username
|
|
}
|
|
s.Broker.Broadcast("error_updated", "", id, actorName, string(status), nil)
|
|
}
|
|
|
|
return s.GetError(id)
|
|
}
|
|
|
|
func (s *Store) ArchiveError(errorID string, actor *User) (*AppError, error) {
|
|
var status string
|
|
err := s.primaryDB.QueryRow("SELECT status FROM errors WHERE id = $1", errorID).Scan(&status)
|
|
if err != nil {
|
|
return nil, errors.New("error not found")
|
|
}
|
|
|
|
if strings.ToLower(status) != string(ErrorStatusResolved) {
|
|
return nil, errors.New("only resolved errors can be sent to the archive")
|
|
}
|
|
|
|
_, err = s.primaryDB.Exec("UPDATE errors SET archived = TRUE WHERE id = $1", errorID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if s.Broker != nil {
|
|
actorName := "unknown"
|
|
if actor != nil {
|
|
actorName = actor.Username
|
|
}
|
|
s.Broker.Broadcast("error_archived", "", errorID, actorName, "archive", nil)
|
|
}
|
|
|
|
return s.GetError(errorID)
|
|
}
|
|
|
|
func (s *Store) UnarchiveError(errorID string, actor *User) (*AppError, error) {
|
|
res, err := s.primaryDB.Exec("UPDATE errors SET archived = FALSE WHERE id = $1", errorID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 0 {
|
|
return nil, errors.New("error not found")
|
|
}
|
|
|
|
if s.Broker != nil {
|
|
actorName := "unknown"
|
|
if actor != nil {
|
|
actorName = actor.Username
|
|
}
|
|
s.Broker.Broadcast("error_unarchived", "", errorID, actorName, "unarchive", nil)
|
|
}
|
|
|
|
return s.GetError(errorID)
|
|
}
|
|
|
|
func (s *Store) RequestPasswordReset(username string) (*Ticket, error) {
|
|
user, err := s.GetUser(username)
|
|
if err != nil || user == nil {
|
|
return nil, errors.New("user not found")
|
|
}
|
|
|
|
tID, err := s.nextSeq("ticket_seq", "KHR")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to generate ticket ID: %w", err)
|
|
}
|
|
|
|
now := time.Now()
|
|
title := fmt.Sprintf("[Password Reset Request] Account: @%s", user.Username)
|
|
desc := fmt.Sprintf("User @%s (%s, Role: %s) has requested a password reset. Please verify their identity and reset their credentials.", user.Username, user.Name, user.RoleDisplay)
|
|
|
|
tx, err := s.primaryDB.Begin()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer tx.Rollback()
|
|
|
|
_, err = tx.Exec(`
|
|
INSERT INTO tickets (
|
|
id, ticket_type, title, general_category, department, app_name, version, feature_name, api_key, issue_type,
|
|
priority, status, description, assistance_required, additional_info, created_by, created_by_name, created_by_role,
|
|
assigned_to, assigned_to_name, assigned_to_role, linked_error_id, created_at, updated_at
|
|
) VALUES ($1,'general',$2,'Access & Permissions','Administration','','','','','credential_reset',
|
|
'P1','open',$3,'Administrator password reset','',
|
|
$4,$5,$6,'admin','Admin','admin','',$7,$7)
|
|
`, tID, title, desc, user.Username, user.Name, user.Role, now)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to create password reset ticket: %w", err)
|
|
}
|
|
|
|
remID := uuid.New().String()
|
|
_, err = tx.Exec(`
|
|
INSERT INTO ticket_remarks (id, ticket_id, author_username, author_name, author_role, type, text, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, 'created', $6, $7)
|
|
`, remID, tID, user.Username, user.Name, user.RoleDisplay, "Automatically generated high-priority password reset ticket for administrator.", now)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if err := tx.Commit(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
s.addNotification("admin", tID, "Password Reset Request", fmt.Sprintf("Password reset requested by @%s (%s)", user.Username, user.Name), "assignment")
|
|
|
|
return s.GetTicket(tID)
|
|
}
|
|
|
|
func (s *Store) EscalateErrorToTicket(errorID, title, assignedTo, priority, notes string, actor *User) (*Ticket, *AppError, error) {
|
|
errItem, err := s.GetError(errorID)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
if title == "" {
|
|
title = fmt.Sprintf("[%s] %s: %s", errItem.AppName, errItem.ExceptionType, errItem.Message)
|
|
if len(title) > 120 {
|
|
title = title[:117] + "..."
|
|
}
|
|
}
|
|
|
|
diagContext := fmt.Sprintf("Exception: %s\nMessage: %s\nEndpoint: %s\nService: %s\nEnvironment: %s\nOccurrences: %d\nLast Seen: %s",
|
|
errItem.ExceptionType, errItem.Message, errItem.Endpoint, errItem.Service, errItem.Environment, errItem.Occurrences, errItem.LastSeen.Format(time.RFC3339))
|
|
if errItem.StackTrace != "" {
|
|
diagContext += "\n\nStack Trace:\n" + errItem.StackTrace
|
|
}
|
|
if errItem.RequestPayload != "" {
|
|
diagContext += "\n\nPayload:\n" + errItem.RequestPayload
|
|
}
|
|
|
|
ticket := &Ticket{
|
|
TicketType: "application",
|
|
Title: title,
|
|
AppName: errItem.AppName,
|
|
Version: errItem.Version,
|
|
FeatureName: errItem.Service,
|
|
APIKey: errItem.Endpoint,
|
|
IssueType: "API Failure / 500 / 400 Error",
|
|
Priority: priority,
|
|
Description: fmt.Sprintf("Escalated from runtime error %s: %s", errItem.ID, errItem.Message),
|
|
AssistanceRequired: "Investigate and resolve runtime exception",
|
|
AdditionalInfo: diagContext,
|
|
AssignedTo: assignedTo,
|
|
LinkedErrorID: errorID,
|
|
}
|
|
|
|
created, err := s.CreateTicket(ticket, actor)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
// Link error
|
|
_, _ = s.primaryDB.Exec(`UPDATE errors SET linked_ticket_id = $1, status = 'investigating' WHERE id = $2`, created.ID, errorID)
|
|
|
|
if s.Broker != nil {
|
|
actorName := "unknown"
|
|
if actor != nil {
|
|
actorName = actor.Username
|
|
}
|
|
s.Broker.Broadcast("error_escalated", created.ID, errorID, actorName, "escalate", nil)
|
|
}
|
|
|
|
updatedErr, _ := s.GetError(errorID)
|
|
return created, updatedErr, nil
|
|
}
|
|
|
|
// ─────────────────────────────────────────────
|
|
// Admin Database Sync & Rollback
|
|
// ─────────────────────────────────────────────
|
|
|
|
func (s *Store) SyncBackupDB() (map[string]any, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
if s.backupDB == nil {
|
|
return nil, errors.New("backup database connection is not available")
|
|
}
|
|
return SyncDatabases(s.primaryDB, s.backupDB)
|
|
}
|
|
|
|
func (s *Store) RollbackFromBackupDB() (map[string]any, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
if s.backupDB == nil {
|
|
return nil, errors.New("backup database connection is not available")
|
|
}
|
|
return RollbackDatabases(s.primaryDB, s.backupDB)
|
|
}
|
|
|
|
func (s *Store) GetDBStatus() map[string]any {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
|
|
primaryCounts := getTableCounts(s.primaryDB)
|
|
backupCounts := make(map[string]int)
|
|
backupAvailable := s.backupDB != nil
|
|
if backupAvailable {
|
|
backupCounts = getTableCounts(s.backupDB)
|
|
}
|
|
|
|
return map[string]any{
|
|
"primary": map[string]any{
|
|
"status": "connected",
|
|
"counts": primaryCounts,
|
|
},
|
|
"backup": map[string]any{
|
|
"status": func() string {
|
|
if backupAvailable {
|
|
return "connected"
|
|
}
|
|
return "disconnected"
|
|
}(),
|
|
"counts": backupCounts,
|
|
},
|
|
"checked_at": time.Now().Format(time.RFC3339),
|
|
}
|
|
}
|