diff --git a/internal/khira/handlers.go b/internal/khira/handlers.go index f318dab..5aaabb6 100644 --- a/internal/khira/handlers.go +++ b/internal/khira/handlers.go @@ -101,8 +101,9 @@ func (s *Server) RegisterRoutes(r chi.Router) { api.Put("/auth/profile", s.handleUpdateProfile) api.Post("/auth/profile", s.handleUpdateProfile) - // Users + // Users & Apps api.Get("/users", s.handleListUsers) + api.Get("/apps", s.handleListApps) // Tickets api.Get("/tickets", s.handleListTickets) @@ -315,6 +316,25 @@ func (s *Server) handleListUsers(w http.ResponseWriter, r *http.Request) { }) } +func (s *Server) handleListApps(w http.ResponseWriter, r *http.Request) { + assignee := r.URL.Query().Get("assignee") + role := r.URL.Query().Get("role") + q := r.URL.Query().Get("q") + + if role == "" && assignee != "" { + if u, err := s.Store.GetUser(assignee); err == nil && u != nil { + role = u.Role + } + } + + apps := s.Store.ListApps(role, q) + s.writeJSON(w, http.StatusOK, map[string]any{ + "status": "ok", + "apps": apps, + "count": len(apps), + }) +} + func (s *Server) handleListTickets(w http.ResponseWriter, r *http.Request) { status := r.URL.Query().Get("status") priority := r.URL.Query().Get("priority") diff --git a/internal/khira/store.go b/internal/khira/store.go index 187dc51..884522f 100644 --- a/internal/khira/store.go +++ b/internal/khira/store.go @@ -8,6 +8,7 @@ import ( "log/slog" "os" "path/filepath" + "sort" "strings" "sync" "time" @@ -500,6 +501,156 @@ func (s *Store) DeleteTicket(ticketID string, actor *User) error { return tx.Commit() } +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 diff --git a/web/khira/app.js b/web/khira/app.js index 6fcd49b..e290624 100644 --- a/web/khira/app.js +++ b/web/khira/app.js @@ -116,7 +116,7 @@ const greet=()=>{const h=new Date().getHours();return h<5?'Working late':h<12?'G const put=(sel,html)=>{const el=typeof sel==='string'?$(sel):sel;if(el&&el._h!==html){el.innerHTML=html;el._h=html}return el}; let tt;function toast(m,t){const s=$('#snack');s.textContent=m;s.style.background=t==='err'?'var(--err)':'';s.classList.add('on');clearTimeout(tt);tt=setTimeout(()=>s.classList.remove('on'),3500)} const busy=async(b,fn)=>{b.disabled=true;try{return await fn()}finally{b.disabled=false}}; -const chk=f=>{f.querySelectorAll('.bad').forEach(x=>x.classList.remove('bad'));const bad=[...f.querySelectorAll('[required]:not(:disabled)')].filter(x=>!x.value.trim());bad.forEach(x=>x.closest('.fld').classList.add('bad'));if(bad.length){bad[0].focus();toast('Fill in the required fields','err')}return!bad.length}; +const chk=f=>{f.querySelectorAll('.bad').forEach(x=>x.classList.remove('bad'));const bad=[...f.querySelectorAll('[required]:not(:disabled)')].filter(x=>!x.disabled&&!x.closest('[hidden]')&&!x.closest('fieldset:disabled')&&!x.value.trim());bad.forEach(x=>x.closest('.fld').classList.add('bad'));if(bad.length){bad[0].focus();toast('Fill in the required fields','err')}return!bad.length}; /* ── form builders ── */ function fld(n,l,o={}){ @@ -378,8 +378,6 @@ function deleteTicketD(id){ /* ── create ticket ── */ function newTicket(){ - const appOpts=[['','Select application'],...Array.from(new Set([...APPS,...(S.t||[]).map(t=>t.app||t.app_name),...(S.e||[]).map(e=>e.app||e.app_name)].filter(Boolean)))]; - dlg({wide:1,title:'New ticket',sub:`Reporting as ${esc(S.u.name)}`,ok:'Create ticket', body:`${rad('type',[['general','General'],['application','Application']],'general')}
@@ -388,8 +386,20 @@ function newTicket(){ ${fld('description','Description',{t:'area',rows:5,req:1})}