Files

2986 lines
130 KiB
JavaScript
Raw Permalink Normal View History

/* Khira Enterprise — Material 3 UI. PostgreSQL Backend, X-Khira-User header, 8s polling. */
'use strict';
const $=s=>document.querySelector(s),$$=s=>[...document.querySelectorAll(s)];
const esc=s=>s==null?'':String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const ls=k=>{try{return localStorage.getItem(k)}catch(e){return null}};
/* ── Inline SVG Icon System (Zero FOUT, Zero Ligature Glitches) ── */
const ICONS = {
bookmark: `<path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"/>`,
filter: `<polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/>`,
ticket: `<path d="M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"/><path d="M13 5v2"/><path d="M13 11v2"/><path d="M13 17v2"/>`,
confirmation_number: `<path d="M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"/><path d="M13 5v2"/><path d="M13 11v2"/><path d="M13 17v2"/>`,
bug: `<path d="m8 2 1.88 1.88"/><path d="M14.12 3.88 16 2"/><path d="M9 7.13v-1a3.003 3.003 0 1 1 6 0v1"/><path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6"/><path d="M12 20v-9"/><path d="M6.53 9C4.6 8.8 3 7.1 3 5"/><path d="M6 13H2"/><path d="M3 21c0-2.1 1.7-3.9 3.8-4"/><path d="M20.97 5c0 2.1-1.6 3.8-3.5 4"/><path d="M22 13h-4"/><path d="M17.2 17c2.1.1 3.8 1.9 3.8 4"/>`,
bug_report: `<path d="m8 2 1.88 1.88"/><path d="M14.12 3.88 16 2"/><path d="M9 7.13v-1a3.003 3.003 0 1 1 6 0v1"/><path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6"/><path d="M12 20v-9"/><path d="M6.53 9C4.6 8.8 3 7.1 3 5"/><path d="M6 13H2"/><path d="M3 21c0-2.1 1.7-3.9 3.8-4"/><path d="M20.97 5c0 2.1-1.6 3.8-3.5 4"/><path d="M22 13h-4"/><path d="M17.2 17c2.1.1 3.8 1.9 3.8 4"/>`,
search: `<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>`,
add: `<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>`,
close: `<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>`,
chat_bubble: `<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>`,
calendar_today: `<rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>`,
archive: `<rect x="2" y="3" width="20" height="5" rx="1"/><path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"/><path d="m10 12 2 2 2-2"/><path d="M12 14v-4"/>`,
unarchive: `<rect x="2" y="3" width="20" height="5" rx="1"/><path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"/><path d="m10 14 2-2 2 2"/><path d="M12 12v4"/>`,
delete: `<polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/>`,
attachment: `<path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/>`,
play_arrow: `<polygon points="5 3 19 12 5 21 5 3"/>`,
pause: `<rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/>`,
warning: `<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>`,
photo_camera: `<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/>`,
sync: `<polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/>`,
upload: `<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/>`,
download: `<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/>`,
check: `<polyline points="20 6 9 17 4 12"/>`,
notifications: `<path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/>`,
view_kanban: `<rect x="3" y="3" width="5" height="18" rx="1"/><rect x="11" y="3" width="5" height="12" rx="1"/><rect x="19" y="3" width="5" height="15" rx="1"/>`,
view_list: `<line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/>`,
biotech: `<path d="M6 18h8"/><path d="M3 22h18"/><path d="m14 22-5-5"/><path d="m17 7 3-3"/><path d="M9 13 4 8a3 3 0 0 1 4.24-4.24l5 5"/><path d="m11 11 4 4"/>`,
link: `<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>`,
tag: `<path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/>`,
moon: `<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>`,
sun: `<circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>`,
send: `<line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>`,
content_copy: `<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>`,
error: `<circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>`,
lock: `<rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>`,
shield: `<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>`,
history: `<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>`,
building: `<rect x="4" y="2" width="16" height="20" rx="2" ry="2"/><line x1="9" y1="22" x2="9" y2="12"/><line x1="15" y1="22" x2="15" y2="12"/><line x1="15" y1="12" x2="9" y2="12"/><line x1="8" y1="6" x2="8.01" y2="6"/><line x1="12" y1="6" x2="12.01" y2="6"/><line x1="16" y1="6" x2="16.01" y2="6"/><line x1="8" y1="10" x2="8.01" y2="10"/><line x1="12" y1="10" x2="12.01" y2="10"/><line x1="16" y1="10" x2="16.01" y2="10"/>`
};
const ic=(name,size=18,cls='')=>{
const inner=ICONS[name]||ICONS.ticket;
return `<svg class="ic ${cls}" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:middle">${inner}</svg>`;
};
const ms=ic; // drop-in replacement for any legacy calls
const S={
u:null, t:[], us:[], e:[], ts:{}, es:{}, n:[], savedFilters:[],
sec:'tickets', scope:'assigned', st:'', pr:'', ty:'', fa:'', view:'board', q:'', ef:'', tid:null,
bulkMode:false, bulkSelected:new Set(),
analyticsData:null, analyticsTargetUser:null
};
const APPS=['Creator Suite Web','FastAPI Backend','Creator Suite Web Unified Dashboard','Batch Inpaint Service','Nexus Gateway','Other App'];
const ISS=['API Failure / 500 / 400 Error','UI Layout / Rendering Bug','Schema Sync / Mismatch','Performance / Latency','Auth / Permission','Other'];
const CATS=['DevOps & Infrastructure','Database & Storage','Access & Permissions','Design & UX','Internal Workflow & Tooling','Hardware & IT Support','Security & Compliance','General Task'];
const ROLES=[['tester','Tester'],['ios_dev','iOS Dev'],['android_dev','Android Dev'],['backend_dev','Backend Dev'],['designer','Designer']];
const EAPPS=['Unified Dashboard Client','Image Manipulator Pro','Image Hoster','FastAPI Backend','Creator Suite Web','Khira Issue Tracker','Batch Inpaint'];
const PRI=[['P0','P0 · Critical'],['P1','P1 · High'],['P2','P2 · Medium'],['P3','P3 · Low']];
const SEV=[['CRITICAL','Critical'],['HIGH','High'],['MEDIUM','Medium'],['LOW','Low']];
const STAT={open:'Open',progress:'In progress',hold:'On hold',completed:'Completed'};
const COLS=[['open','var(--status-open)'],['progress','var(--status-progress)'],['hold','var(--status-hold)'],['completed','var(--status-completed)']];
const EL={draft:'Drafts',unresolved:'Unresolved',escalated:'Escalated',resolved:'Resolved'};
const EMOJIS=['⚡','👩‍💻','👨‍💻','🕵️‍♂️','👤','🚀','🛡️','🎨','🤖','🦊','🦉','🦁','🔥','💡','🎯','⚙️','🌟','💻'];
/* ── API ── */
async function api(p,m='GET',b){
const h={};
const tok=ls('khira_session_token');
if(tok)h['Authorization']='Bearer '+tok;
const un=S.u?.username||ls('khira_active_user');
if(un)h['X-Khira-User']=un;
if(m!=='GET')h['Content-Type']='application/json';
try{
const r=await fetch(p,{method:m,headers:h,credentials:'same-origin',body:b?JSON.stringify(b):undefined});
const j=(r.headers.get('content-type')||'').includes('json')?await r.json():{};
if(!r.ok){j._f=1;if(!j.error)j.error='Request failed ('+r.status+')'}
return j;
}catch(e){return{_f:1,error:'Network error'}}
}
/* ── Helpers ── */
const pri=t=>{
const p=(t.priority||'medium').toLowerCase();
if(p==='critical'||p==='p0')return 'P0';
if(p==='high'||p==='p1')return 'P1';
if(p==='medium'||p==='p2')return 'P2';
if(p==='low'||p==='p3')return 'P3';
return p.toUpperCase();
};
const priFull=t=>{
const p=(t.priority||'medium').toLowerCase();
if(p==='critical'||p==='p0')return 'Critical';
if(p==='high'||p==='p1')return 'High';
if(p==='medium'||p==='p2')return 'Medium';
return 'Low';
};
const st=t=>{const s=(t.status||'open').toLowerCase();return s==='in_progress'?'progress':s==='on_hold'?'hold':s};
const ek=e=>(e.is_draft||e.status==='draft')?'draft':e.status==='resolved'?'resolved':(e.escalated_ticket_id||e.linked_ticket_id)?'escalated':'unresolved';
const isAdmin=u=>u&&(u.username==='admin'||u.role==='team_lead'||u.role==='lead');
const roleClass=u=>{
if(!u)return 'av-tester';
const uname=(u.username||'').toLowerCase();
const role=(u.role||'').toLowerCase();
const av=u.avatar||'';
if(uname==='admin'||role==='team_lead'||role==='lead'||role==='admin'||av==='A')return 'av-admin';
if(role==='tester'||role==='qa'||role==='security')return 'av-tester';
if(role==='ios_dev'||role==='ios'||role==='frontend_dev'||role==='frontend')return 'av-ios_dev';
if(role==='android_dev'||role==='android')return 'av-android_dev';
if(role==='backend_dev'||role==='backend'||role==='engineer')return 'av-backend_dev';
if(role==='designer'||role==='design')return 'av-designer';
return 'av-tester';
};
const adminSvgA=`<svg viewBox="0 0 100 100" class="av-admin-svg">
<defs>
<linearGradient id="adminGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#FF3B30"/>
<stop offset="25%" stop-color="#FF9500"/>
<stop offset="50%" stop-color="#FFCC00"/>
<stop offset="75%" stop-color="#34C759"/>
<stop offset="100%" stop-color="#00C7FF"/>
</linearGradient>
<linearGradient id="adminBg" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#231F32"/>
<stop offset="100%" stop-color="#12101C"/>
</linearGradient>
<filter id="adminGlow" x="-20%" y="-20%" width="140%" height="140%">
<feDropShadow dx="0" dy="1" stdDeviation="2.5" flood-color="#FF9500" flood-opacity="0.6"/>
</filter>
</defs>
<circle cx="50" cy="50" r="48" fill="url(#adminBg)"/>
<path d="M50 17 L21 78 L34 78 L43 58 L57 58 L66 78 L79 78 Z M50 35 L45 49 L55 49 Z" fill="url(#adminGrad)" filter="url(#adminGlow)"/>
</svg>`;
function getInitials(name) {
if (!name) return 'U';
const parts = name.trim().split(/\s+/);
if (parts.length >= 2) return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
return name.slice(0, 2).toUpperCase();
}
function getUserColor(username) {
const colors = [
{ bg: '#3b82f6', text: '#ffffff' },
{ bg: '#6366f1', text: '#ffffff' },
{ bg: '#8b5cf6', text: '#ffffff' },
{ bg: '#ec4899', text: '#ffffff' },
{ bg: '#10b981', text: '#ffffff' },
{ bg: '#f59e0b', text: '#ffffff' },
{ bg: '#06b6d4', text: '#ffffff' },
{ bg: '#f97316', text: '#ffffff' }
];
if (!username) return colors[0];
let hash = 0;
for (let i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + ((hash << 5) - hash);
}
const idx = Math.abs(hash) % colors.length;
return colors[idx];
}
const resolveUser=u=>{
if(!u)return null;
if(typeof u==='string')return S.us?.find(x=>x.username===u)||{username:u,name:u};
const uname=u.username||u.author_username||u.assigned_to||u.created_by;
if(uname){
const found=S.us?.find(x=>x.username===uname);
if(found)return{...found,...u};
}
return u;
};
/* Modern Initials & Profile Photo Avatar (Zero Cartoon Emojis) */
const avHtml=(rawU,size=26)=>{
const u=resolveUser(rawU);
if(!u)return `<span class="av-initials" style="width:${size}px;height:${size}px;font-size:${Math.max(10, Math.round(size*0.42))}px;background:#64748b;color:#ffffff">?</span>`;
if(u.profile_image){
return `<span class="av-wrap" style="width:${size}px;height:${size}px"><img src="${esc(u.profile_image)}" alt="${esc(u.name||u.username||'')}" class="av-img" onerror="this.style.display='none';this.nextElementSibling.style.display='grid'"><span class="av-initials" style="display:none;width:${size}px;height:${size}px;font-size:${Math.max(10, Math.round(size*0.42))}px;background:#3b82f6;color:#ffffff">${getInitials(u.name||u.username)}</span></span>`;
}
const c = getUserColor(u.username || u.name);
const inits = getInitials(u.name || u.username);
return `<span class="av-initials" style="width:${size}px;height:${size}px;font-size:${Math.max(10, Math.round(size*0.42))}px;background:${c.bg};color:${c.text}" title="${esc(u.name || u.username)}">${inits}</span>`;
};
const who=(u,alt)=>{
if(!u)return alt||'—';
const obj=typeof u==='string'?resolveUser(u):u;
return `<span class="r" style="display:inline-flex;align-items:center;gap:8px">${avHtml(obj,22)} <span>${esc(obj?.name||obj?.username||alt||'—')}</span></span>`;
};
function updateMe(u){
const el=$('#me');if(!el)return;
if(!u){ el.innerHTML=''; return; }
const initsAv = avHtml(u, 30);
el.innerHTML = `
${initsAv}
<div class="user-profile-meta">
<span class="user-name">${esc(u.name || u.username)}</span>
<span class="user-role-badge">${esc(u.role_display || u.role)}</span>
</div>
`;
const isAdm=isAdmin(u);
if($('#navAdmin'))$('#navAdmin').hidden=!isAdm;
if($('#navAdminGroup'))$('#navAdminGroup').hidden=!isAdm;
}
const usOpts=b=>[...(b?[['','Choose developer']]:[]),...S.us.map(u=>[u.username,`${u.name} · ${u.role_display}`])];
function ago(iso){if(!iso)return'—';const d=new Date(iso);if(isNaN(d))return iso;const s=Math.floor((Date.now()-d)/1e3);if(s<60)return'just now';const m=Math.floor(s/60);if(m<60)return m+'m ago';const h=Math.floor(m/60);if(h<24)return h+'h ago';const x=Math.floor(h/24);return x<30?x+'d ago':d.toLocaleDateString()}
const greet=()=>{const h=new Date().getHours();return h<5?'Working late':h<12?'Good morning':h<17?'Good afternoon':h<21?'Good evening':'Working late'};
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)':t==='warn'?'#f59e0b':'';
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.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={}){
const r=o.req?' required':'',t=o.t||'text';let c;
if(t==='select')c=`<select name="${n}"${r} ${o.d||''}>${o.opts.map(x=>{const[v,tx]=Array.isArray(x)?x:[x,x];return`<option value="${esc(v)}"${v===o.v?' selected':''}>${esc(tx)}</option>`}).join('')}</select>`;
else if(t==='area')c=`<textarea name="${n}" rows="${o.rows||3}" placeholder=" "${r}>${esc(o.v||'')}</textarea>`;
else c=`<input name="${n}" type="${t}" placeholder=" " value="${esc(o.v||'')}"${r}>`;
return`<label class="fld${t==='select'?' sel':''}${o.mono?' mono':''}">${c}<span>${l}${o.req?' *':''}</span></label>`;
}
const rad=(n,items,cur)=>`<div class="rg">${items.map(([v,l])=>`<label><input type="radio" name="${n}" value="${esc(v)}"${v===cur?' checked':''}><span>${esc(l)}</span></label>`).join('')}</div>`;
function dlg(o){
const d=$('#dlg');
d.className = 'app-modal-dialog' + (o.wide ? ' wide' : '');
d.innerHTML = `<form class="dc" novalidate>
<div class="dh">
<div class="dh-titles">
<h3>${o.title}</h3>
${o.sub ? `<p class="sub">${o.sub}</p>` : ''}
</div>
<button type="button" class="ib" data-x aria-label="Close">${ic('close', 16)}</button>
</div>
<div class="db">${o.body}</div>
<div class="da">
${o.alt ? `<button type="button" class="btn-alt" data-alt>${o.alt[0]}</button>` : ''}
<button type="button" class="tb" data-x>Cancel</button>
<button class="fb">${o.ok || 'Save'}</button>
</div>
</form>`;
const f=d.querySelector('form');
f.querySelectorAll('[data-x]').forEach(btn => {
btn.onclick = () => { if(d.open) d.close(); };
});
if(o.alt)f.querySelector('[data-alt]').onclick=o.alt[1];
if(o.init)o.init(f);
f.onsubmit=async e=>{
e.preventDefault();if(!chk(f))return;
const v=Object.fromEntries([...new FormData(f)].map(([k,x])=>[k,typeof x==='string'?x.trim():x]));
await busy(f.querySelector('.fb'),async()=>{if(await o.go(v)!==false&&d.open)d.close()});
};
if(!d.open)d.showModal();
}
/* ── Data Refresh & State Polling ── */
let pollId;
async function refresh(anim){
if(!S.u)return;
const [tr,ts,er,es,nr,ur,fr]=await Promise.all([
api('/khira/api/tickets?limit=100'),
api('/khira/api/stats'),
api('/khira/api/errors?status=all_with_drafts&limit=100'),
api('/khira/api/errors/stats'),
api('/khira/api/notifications'),
api('/khira/api/users'),
api('/khira/api/filters')
]);
const newT=tr.tickets||[],newTs=ts||{},newE=er.errors||[],newEs=es||{},newN=nr.notifications||[];
if(ur.users)S.us=ur.users;
if(fr&&fr.filters)S.savedFilters=fr.filters;
const changed=anim||newT.length!==S.t.length||newE.length!==S.e.length||JSON.stringify(newTs)!==JSON.stringify(S.ts)||JSON.stringify(newEs)!==JSON.stringify(S.es);
S.t=newT;S.ts=newTs;S.e=newE;S.es=newEs;S.n=newN;
const unreadCount = S.n.filter(x => !x.read).length;
if($('#dot')) $('#dot').hidden = unreadCount === 0;
if($('#navTicketsBadge')) $('#navTicketsBadge').textContent = S.ts.open_assigned || S.ts.open_all || S.t.filter(x => !['completed','closed'].includes(st(x))).length || 0;
if($('#navErrorsBadge')) $('#navErrorsBadge').textContent = S.e.filter(x => x.status === 'unresolved').length || 0;
if(changed)render(anim);
}
const render=a=>{
if(S.sec==='tickets')renderT(a);
else if(S.sec==='errors')renderE(a);
else if(S.sec==='analytics')renderA(a);
else if(S.sec==='admin')renderAdmin(a);
};
const tile=(n,l,k)=>`<div class="tile" data-k="${k}"><small>${l}</small><strong>${n||0}</strong></div>`;
const chipRow=(items,cur,attr)=>items.map(([k,l])=>`<button class="chip${cur===k?' on':''}" ${attr}="${k}">${l}</button>`).join('');
/* ── Tickets Filtering & Rendering ── */
function fT(){
const me=S.u.username;
return S.t.filter(t=>{
if(S.st==='archived'){
if(!t.archived)return false;
}else{
if(t.archived)return false;
if(S.st&&st(t)!==S.st)return false;
}
if(S.scope==='assigned'&&t.assigned_to!==me)return false;
if(S.scope==='created'&&t.created_by!==me)return false;
if(S.pr){
const p=pri(t);
const prReq=S.pr.toUpperCase();
if(p!==prReq&&priFull(t).toUpperCase()!==prReq)return false;
}
if(S.ty&&t.ticket_type!==S.ty)return false;
if(S.fa&&t.assigned_to!==S.fa)return false;
return!S.q||[t.id,t.title,t.description,t.app,t.app_name,t.feature,t.feature_name,t.assignee?.name,t.assigned_to_name].join(' ').toLowerCase().includes(S.q);
});
}
function dateGroup(iso){
if(!iso)return'Older';
const d=new Date(iso);
const now=new Date();
const startOfToday=new Date(now.getFullYear(),now.getMonth(),now.getDate());
const startOfYesterday=new Date(startOfToday.getTime()-86400000);
const startOfWeek=new Date(startOfToday.getTime()-startOfToday.getDay()*86400000);
const startOfMonth=new Date(now.getFullYear(),now.getMonth(),1);
if(d>=startOfToday)return'Today';
if(d>=startOfYesterday)return'Yesterday';
if(d>=startOfWeek)return'This Week';
if(d>=startOfMonth)return'Earlier this Month';
return'Older';
}
const sub=t=>t.ticket_type==='general'?(t.department||'General')
:[t.app||t.app_name,t.version,t.feature||t.feature_name].filter(Boolean).join(' · ')||(t.department||'Application');
function renderT(anim){
put('#hi',`${greet()}, ${esc(S.u.name.split(' ')[0])}`);
put('#sum',`You have ${S.ts.open_assigned||0} active tasks and ${S.ts.hold_assigned||0} on hold.`);
const s=S.ts;
put('#stats',tile(s.total_assigned,'Assigned to me','ta')+tile(s.total_created,'Filed by me','tc')+tile(s.hold_all,'On hold','th')+tile(s.resolved_all,'Completed','tr'));
put('#tabs',`<div class="seg">${[['assigned',`Assigned to me ${s.total_assigned||0}`],['created',`Created by me ${s.total_created||0}`],['all',`All tickets ${s.total_all||0}`]].map(([k,l])=>`<button class="${S.scope===k?'on':''}" data-sc="${k}">${l}</button>`).join('')}</div>`);
const archCount=S.t.filter(t=>t.archived).length;
const chips=[['','All'],...Object.entries(STAT),['archived',`Archived (${archCount})`]];
put('#stChips',chipRow(chips,S.st,'data-st'));
const faEl=$('#fa');
if(faEl){
const curVal=S.fa;
faEl.innerHTML='<option value="">All assignees</option>'+S.us.map(u=>`<option value="${esc(u.username)}"${u.username===curVal?' selected':''}>${esc(u.name)} (${esc(u.role_display)})</option>`).join('');
faEl.value=curVal;
}
$$('#vsw button').forEach(b=>b.classList.toggle('on',b.dataset.v===S.view));
$('#board').hidden=S.view!=='board';$('#list').hidden=S.view!=='list';
$('#board').classList.toggle('anim',!!anim);$('#list').classList.toggle('anim',!!anim);
const f=fT();
if(S.view==='board'){
put('#board',COLS.map(([k,c])=>{
const rows=f.filter(t=>st(t)===k||(!STAT[st(t)]&&k==='open'));
return`<section class="col" data-col="${k}">
<h3>
<i style="--c:${c}"></i>${STAT[k]}
<small>${rows.length}</small>
<button type="button" class="btn-col-add" data-col-add="${k}" title="Add ticket in ${STAT[k]}" style="margin-left:auto;color:var(--text-muted);width:22px;height:22px;display:grid;place-items:center;border-radius:4px;font-size:16px">+</button>
</h3>
<div class="col-cards-container">
${rows.map((t,i)=>{
const p=pri(t),n=(t.remarks||[]).length;
const avElem=avHtml(t.assignee||{role:t.assigned_to_role,username:t.assigned_to,name:t.assigned_to_name},22);
const isSel=S.bulkSelected.has(t.id);
const chkBox=S.bulkMode?`<input type="checkbox" class="card-check" data-tid="${esc(t.id)}" ${isSel?'checked':''}>`:'';
// SLA progress calculation
let slaHtml='';
if(t.due_date){
const now=Date.now(),cre=new Date(t.created_at).getTime(),due=new Date(t.due_date).getTime();
const total=Math.max(1,due-cre);
const elapsed=Math.max(0,now-cre);
const pct=Math.min(100,Math.round((elapsed/total)*100));
const isOverdue=t.sla_breached||now>due;
const cls=isOverdue?'breached':pct>75?'danger':pct>50?'warning':'good';
slaHtml=`<div class="sla-wrap"><div class="sla-meta"><span>${isOverdue?'<b style="color:var(--danger)">OVERDUE</b>':ago(t.due_date)}</span><span>${pct}%</span></div><div class="sla-bar"><div class="sla-fill ${cls}" style="width:${pct}%"></div></div></div>`;
}
const tagsHtml=(t.tags||[]).length?`<div class="tag-list" style="margin-top:4px">${t.tags.map(tg=>`<span class="tag-pill">${esc(tg)}</span>`).join('')}</div>`:'';
return`<article class="card p-${p.toLowerCase()} ${isSel?'selected':''}" draggable="true" tabindex="0" role="button" data-t="${esc(t.id)}" style="--i:${i}">
${chkBox}
<div class="r"><span class="id">${esc(t.id)}</span><span class="tag">${t.ticket_type==='general'?'General':'App'}</span><span class="pb ${p.toLowerCase()}">${p}</span></div>
<h4>${esc(t.title)}</h4>
<div class="r m"><span class="ell">${esc(sub(t))}</span>${n?`<span class="r" style="display:inline-flex;align-items:center;gap:4px">${ic('chat_bubble',12)} ${n}</span>`:''}${avElem}</div>
${tagsHtml}
${slaHtml}
</article>`;
}).join('')||'<div class="empty" style="padding:24px;text-align:center;color:var(--text-muted);font-size:12px">No tickets</div>'}
</div>
</section>`;
}).join(''));
initBoardDragDrop();
}else{
const dateGroups=['Today','Yesterday','This Week','Earlier this Month','Older'];
const grouped={};
dateGroups.forEach(g=>grouped[g]=[]);
f.forEach(t=>{
const g=dateGroup(t.created_at);
if(!grouped[g])grouped[g]=[];
grouped[g].push(t);
});
const sectionsHtml=dateGroups.map(g=>{
const items=grouped[g];
if(!items||!items.length)return'';
const itemsHtml=items.map((t,i)=>{
const p=pri(t),s2=st(t);
const isArch=!!t.archived;
const isSel=S.bulkSelected.has(t.id);
const chkBox=S.bulkMode?`<input type="checkbox" class="card-check" data-tid="${esc(t.id)}" ${isSel?'checked':''} style="margin-right:10px">`:'';
return`<div class="li ${isSel?'selected':''}" tabindex="0" role="button" data-t="${esc(t.id)}" style="--i:${Math.min(i,12)}">${chkBox}<span class="lead pb ${p.toLowerCase()}">${p}</span><div class="ell"><h4 class="ell">${esc(t.title)}</h4><p class="ell">${esc(t.id)} · ${esc(sub(t))} · ${esc(t.assignee?.name||t.assigned_to_name||'Unassigned')}</p></div><div class="tl2">${isArch?'<span class="stt archived">Archived</span>':`<span class="stt ${s2}">${STAT[s2]||esc(s2)}</span>`}<span>${ago(t.created_at||t.updated_at)}</span></div></div>`;
}).join('');
return`<div class="date-section"><div class="date-header">${ic('calendar_today',16)}<span>${g}</span><span class="date-badge">${items.length}</span></div>${itemsHtml}</div>`;
}).filter(Boolean).join('');
put('#list',sectionsHtml||`<div class="big">${ic('confirmation_number',36)}<p>No tickets match these filters.</p></div>`);
}
put('#title','Tickets');
renderSavedFilters();
}
async function loadSavedFilters(){
if(!S.u)return;
try{
const res=await api('/khira/api/filters');
S.savedFilters=res.filters||[];
renderSavedFilters();
}catch(e){}
}
function renderSavedFilters(){
const bar=$('#savedFilterChips');
if(!bar)return;
if(!S.u||S.sec!=='tickets'){
bar.style.display='none';
return;
}
bar.style.display='flex';
const filters=S.savedFilters||[];
let html=`<div class="sf-header"><span class="saved-filter-label">${ic('bookmark',13)} Views:</span></div><div class="sf-items">`;
if(!filters.length){
html+=`<span class="sf-empty">No saved views</span>`;
}else{
html+=filters.map(f=>{
let isActive=false;
try{
const p=JSON.parse(f.filter_json);
isActive=(p.st===undefined||p.st===S.st)&&
(p.pr===undefined||p.pr===S.pr)&&
(p.ty===undefined||p.ty===S.ty)&&
(p.fa===undefined||p.fa===S.fa)&&
(p.scope===undefined||p.scope===S.scope);
}catch(e){}
return`<div class="saved-filter-pill ${isActive?'active':''}" data-fid="${esc(f.id)}" title="Apply ${esc(f.name)}">
<span class="sf-click">${esc(f.name)}</span>
<button class="sf-del" data-delfid="${esc(f.id)}" title="Delete view">&times;</button>
</div>`;
}).join('');
}
html+=`</div><button class="btn-save-filter" id="btnSaveFilter" title="Save current filter set">${ic('add',13)} <span>Save view</span></button>`;
bar.innerHTML=html;
}
function initBoardDragDrop(){
const cards = $$('#board .card');
const cols = $$('#board .col');
cards.forEach(card => {
card.addEventListener('dragstart', e => {
e.dataTransfer.setData('text/plain', card.dataset.t);
e.dataTransfer.effectAllowed = 'move';
card.classList.add('dragging');
});
card.addEventListener('dragend', () => {
card.classList.remove('dragging');
});
});
cols.forEach(col => {
col.addEventListener('dragover', e => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
col.classList.add('drop-hover');
});
col.addEventListener('dragleave', e => {
if (!col.contains(e.relatedTarget)) {
col.classList.remove('drop-hover');
}
});
col.addEventListener('drop', async e => {
e.preventDefault();
col.classList.remove('drop-hover');
const tid = e.dataTransfer.getData('text/plain');
const targetCol = col.dataset.col;
if (!tid || !targetCol) return;
const t = S.t.find(x => x.id === tid);
if (!t) return;
const curSt = st(t);
if (curSt === targetCol) return;
if (targetCol === 'completed') {
S.tid = tid;
doneD();
} else if (targetCol === 'hold') {
S.tid = tid;
holdD();
} else if (targetCol === 'progress') {
await api(`/khira/api/tickets/${encodeURIComponent(tid)}/resume`, 'POST', { remarks: 'Moved to In Progress' });
toast(`Ticket ${tid} moved to In Progress`);
await refresh(false);
} else if (targetCol === 'open') {
await api(`/khira/api/tickets/${encodeURIComponent(tid)}/reopen`, 'POST', { remarks: 'Moved to Open' });
toast(`Ticket ${tid} moved to Open`);
await refresh(false);
}
});
});
}
const verFmt=v=>!v?'':(String(v).toLowerCase().startsWith('v')?' ':' v')+esc(v);
/* ── Errors View ── */
function renderE(anim){
const s=S.es;
const draftCount=S.e.filter(e=>e.is_draft||e.status==='draft').length;
put('#estats',tile(s.total,'Total','et')+tile(s.unresolved,'Unresolved','eu')+tile(draftCount,'Drafts','ed')+tile(s.resolved,'Resolved','er'));
const archErrCount=S.e.filter(e=>e.archived&&!e.is_draft).length;
const eChips=[['','All Published'],['draft',`Drafts (${draftCount})`],['unresolved','Unresolved'],['escalated','Escalated'],['resolved','Resolved'],['archived',`Archived (${archErrCount})`]];
put('#eChips',chipRow(eChips,S.ef,'data-ef'));
const f=S.e.filter(e=>{
const isDr=e.is_draft||e.status==='draft';
if(S.ef==='draft'){
if(!isDr)return false;
}else if(S.ef==='archived'){
if(!e.archived||isDr)return false;
}else if(!S.ef){
if(e.archived||isDr)return false;
}else{
if(e.archived||isDr||ek(e)!==S.ef)return false;
}
return!S.q||[e.id,e.exception_type,e.message,e.description,e.endpoint,e.app,e.app_name,e.feature_name,e.error_screen,e.platform,e.assigned_to].join(' ').toLowerCase().includes(S.q);
});
const draftBannerHtml=(draftCount>0&&S.ef!=='draft')?`
<div class="draft-banner">
<span>📝 You have <b>${draftCount}</b> saved error draft(s) available to edit and send.</span>
<button type="button" class="chip draft-btn" id="btnViewDrafts">View Drafts (${draftCount})</button>
</div>`:'' ;
$('#elist').classList.toggle('anim',!!anim);
put('#elist',draftBannerHtml+(f.length?f.map((e,i)=>{
const sev=(e.severity||'MEDIUM').toUpperCase(),k=ek(e);
const isArch=!!e.archived;
const isDr=e.is_draft||e.status==='draft';
const platChip=`<span class="meta-chip ${e.platform==='Android'?'android':'ios'}">${e.platform==='Android'?'🤖 Android':'🍏 iOS'}</span>`;
const typeChip=`<span class="meta-chip ${e.error_type==='Crash'?'crash':'bug'}">${esc(e.error_type||'Bug')}</span>`;
const phaseChip=e.current_phase?`<span class="meta-chip">${esc(e.current_phase)}</span>`:'';
if(isDr){
return`<div class="li" tabindex="0" role="button" data-e="${esc(e.id)}" style="--i:${Math.min(i,12)}">
<span class="lead sv" style="background:rgba(245,158,11,0.2);color:#fbbf24">${ic('ticket',16)}</span>
<div class="ell">
<div style="display:flex;gap:6px;align-items:center;margin-bottom:3px">
<span class="stt draft">Draft</span>
${platChip}
${typeChip}
${phaseChip}
</div>
<h4 class="ell" style="font-size:14px">${esc(e.app_name||'Draft Application')}${verFmt(e.version)}${e.error_screen?' · '+esc(e.error_screen):''}</h4>
<p class="ell">${esc(e.description||e.message||'(No description provided)')}</p>
<p class="ell" style="font-size:11px;color:var(--on-sv)">${esc(e.id)}${e.assigned_to?' · Sent to @'+esc(e.assigned_to):' · Unassigned'}${e.image_url?' · 📷 Image attached':''}</p>
</div>
<div class="tl2">
<button type="button" class="tn draft-btn" style="height:26px;font-size:11px" onclick="event.stopPropagation();reportErr(S.e.find(x=>x.id==='${esc(e.id)}'))">✏️ Edit & Send</button>
<span>${ago(e.last_seen||e.created_at)}</span>
</div>
</div>`;
}
return`<div class="li" tabindex="0" role="button" data-e="${esc(e.id)}" style="--i:${Math.min(i,12)}">
<span class="lead sv ${sev}">${ic('error',16)}</span>
<div class="ell">
<div style="display:flex;gap:6px;align-items:center;margin-bottom:3px">
${platChip}
${typeChip}
${phaseChip}
</div>
<h4 class="ell" style="font-size:14px">${esc(e.app_name||e.app||'Application')}${verFmt(e.version)}${e.error_screen?' · '+esc(e.error_screen):''}${e.feature_name?' ('+esc(e.feature_name)+')':''}</h4>
<p class="ell">${esc(e.description||e.message)}</p>
<p class="ell" style="font-size:11px;color:var(--on-sv)">${esc(e.id)}${e.assigned_to?' · Assigned to @'+esc(e.assigned_to):''}${e.image_url?' · 📷 Image attached':''}</p>
</div>
<div class="tl2">
<span class="stt ${isArch?'archived':k}">${isArch?'Archived':EL[k]||k}</span>
<span>${e.events||e.occurrences||1} events · ${ago(e.last_seen||e.created_at)}</span>
</div>
</div>`;
}).join(''):`<div class="big">${ic('bug_report',36)}<p>No errors tracked.</p></div>`));
$('#btnViewDrafts')?.addEventListener('click',()=>{
S.ef='draft';
renderE(true);
});
put('#title','Error Tracking');
}
/* ── Analytics View ── */
async function renderA(anim){
put('#title','Analytics');
const url = S.analyticsTargetUser ? `/khira/api/analytics?user=${encodeURIComponent(S.analyticsTargetUser)}` : '/khira/api/analytics';
const res = await api(url);
if(res._f || !res.summary) return;
S.analyticsData = res;
const sum = res.summary;
const isOrg = res.scope === 'organization';
const isAdm = !!res.is_admin;
const targetUser = res.target_user || S.u?.username || '';
const targetName = res.target_name || S.u?.name || targetUser;
// Header and titles
const heroTitle = $('#analyticsHeroTitle');
const heroSub = $('#analyticsHeroSub');
const velTitle = $('#velocityCardTitle');
const priTitle = $('#priorityCardTitle');
const workTitle = $('#workloadCardTitle');
const actTitle = $('#activityCardTitle');
if(isOrg){
if(heroTitle) heroTitle.textContent = 'Organization Productivity & SLA Analytics';
if(heroSub) heroSub.textContent = 'Real-time engineering velocity, resolution benchmarks, and team workload.';
if(velTitle) velTitle.textContent = '8-Week Velocity (Created vs Resolved)';
if(priTitle) priTitle.textContent = 'Priority Distribution';
if(workTitle) workTitle.textContent = 'Team Workload Heatmap';
if(actTitle) actTitle.textContent = 'Live Activity Stream';
put('#astats', tile(sum.total_tickets, 'Total Tickets', 'at') +
tile(sum.open_tickets, 'Open Tasks', 'ao') +
tile(sum.in_progress_tickets, 'In Progress', 'ap') +
tile(sum.sla_breached_tickets, 'SLA Breached', 'as') +
tile(sum.avg_resolution_hours + 'h', 'Avg Resolution', 'ar') +
tile(res.error_summary?.total_errors || 0, 'Total Errors', 'ae'));
}else{
if(heroTitle) heroTitle.textContent = 'Personal Productivity & SLA Analytics';
if(heroSub) heroSub.textContent = `Private & confidential analytics scoped exclusively to @${targetUser}.`;
if(velTitle) velTitle.textContent = `Personal 8-Week Velocity (@${targetUser})`;
if(priTitle) priTitle.textContent = `My Tasks by Priority`;
if(workTitle) workTitle.textContent = `Personal Workload & Scorecard`;
if(actTitle) actTitle.textContent = `Personal Activity Stream`;
put('#astats', tile(sum.total_tickets, 'My Active Tasks', 'at') +
tile(sum.open_tickets, 'Open Tasks', 'ao') +
tile(sum.in_progress_tickets, 'In Progress', 'ap') +
tile(sum.completed_tickets, 'Completed by Me', 'ac') +
tile(sum.avg_resolution_hours + 'h', 'My Avg Turnaround', 'ar') +
tile(sum.sla_breached_tickets, 'SLA Breaches', 'as'));
}
// Scope Controls
const scopeEl = $('#analyticsScopeControls');
if(scopeEl){
if(isAdm){
const opts = (res.available_users || []).map(u =>
`<option value="${esc(u.username)}"${res.target_user === u.username ? ' selected' : ''}>@${esc(u.username)} — ${esc(u.name)} (${esc(u.role_display)})</option>`
).join('');
scopeEl.innerHTML = `
<div class="analytics-scope-bar">
<span class="badge ${isOrg ? 'org-badge' : 'audit-badge'}">
${isOrg ? ic('building', 14) + ' Organization View' : ic('shield', 14) + ' Executive Audit: @' + esc(res.target_user)}
</span>
<select id="selAnalyticsUser" class="analytics-scope-select">
<option value=""${isOrg ? ' selected' : ''}>🏢 All Organization (Executive Overview)</option>
<optgroup label="Team Member Audits">
${opts}
</optgroup>
</select>
</div>
`;
$('#selAnalyticsUser').onchange = e => {
S.analyticsTargetUser = e.target.value || null;
renderA();
};
}else{
scopeEl.innerHTML = `
<div class="analytics-scope-bar">
<span class="badge privacy-badge">
${ic('lock', 14)} Confidential · Personal Scope
</span>
</div>
`;
}
}
drawVelocityChart(res.velocity || []);
drawPriorityDonut(res.by_priority || {});
renderWorkloadTable(res.by_assignee || [], isOrg, res);
renderActivityStream(res.recent_activity || []);
}
function drawVelocityChart(velocity){
const canvas=$('#velocityCanvas');
if(!canvas)return;
const ctx=canvas.getContext('2d');
const dpr=window.devicePixelRatio||1;
const rect=canvas.getBoundingClientRect();
canvas.width=rect.width*dpr;canvas.height=240*dpr;
ctx.scale(dpr,dpr);
const w=rect.width,h=240;
ctx.clearRect(0,0,w,h);
const maxVal=Math.max(1,Math.max(...velocity.map(v=>Math.max(v.created,v.resolved))));
const paddingBottom=30,paddingTop=20,paddingLeft=35,paddingRight=20;
const chartW=w-paddingLeft-paddingRight;
const chartH=h-paddingBottom-paddingTop;
// Grid lines
ctx.strokeStyle='rgba(255,255,255,0.06)';
ctx.lineWidth=1;
for(let i=0;i<=4;i++){
const y=paddingTop+chartH*(i/4);
ctx.beginPath();ctx.moveTo(paddingLeft,y);ctx.lineTo(w-paddingRight,y);ctx.stroke();
ctx.fillStyle='rgba(255,255,255,0.3)';
ctx.font='10px Roboto Mono, monospace';
ctx.textAlign='right';
ctx.fillText(Math.round(maxVal*(1-i/4)),paddingLeft-8,y+4);
}
// Bars
const n=velocity.length;
if(!n)return;
const groupW=chartW/n;
const barW=Math.min(18,groupW*0.35);
velocity.forEach((v,i)=>{
const x=paddingLeft+i*groupW+groupW/2;
// Created bar (blue)
const hCre=(v.created/maxVal)*chartH;
ctx.fillStyle='#38bdf8';
ctx.fillRect(x-barW-2,paddingTop+chartH-hCre,barW,hCre);
// Resolved bar (green)
const hRes=(v.resolved/maxVal)*chartH;
ctx.fillStyle='#10b981';
ctx.fillRect(x+2,paddingTop+chartH-hRes,barW,hRes);
// Date Label
ctx.fillStyle='rgba(255,255,255,0.4)';
ctx.font='10px Roboto Mono, monospace';
ctx.textAlign='center';
ctx.fillText(v.week,x,h-10);
});
}
function drawPriorityDonut(byPri){
const canvas=$('#priorityCanvas');
if(!canvas)return;
const ctx=canvas.getContext('2d');
const dpr=window.devicePixelRatio||1;
const rect=canvas.getBoundingClientRect();
canvas.width=rect.width*dpr;canvas.height=240*dpr;
ctx.scale(dpr,dpr);
const cx=rect.width/2,cy=120,r=75,innerR=48;
const colors={critical:'#ef4444',high:'#f97316',medium:'#eab308',low:'#10b981',p0:'#ef4444',p1:'#f97316',p2:'#eab308',p3:'#10b981'};
const total=Object.values(byPri).reduce((a,b)=>a+b,0)||1;
let startAng=-Math.PI/2;
Object.entries(byPri).forEach(([k,count])=>{
if(!count)return;
const ang=(count/total)*2*Math.PI;
ctx.beginPath();
ctx.arc(cx,cy,r,startAng,startAng+ang);
ctx.arc(cx,cy,innerR,startAng+ang,startAng,true);
ctx.closePath();
ctx.fillStyle=colors[k.toLowerCase()]||'#94a3b8';
ctx.fill();
startAng+=ang;
});
// Center text
ctx.fillStyle='#fff';
ctx.font='bold 20px Roboto Flex, sans-serif';
ctx.textAlign='center';
ctx.fillText(total,cx,cy+6);
ctx.font='10px Roboto Flex, sans-serif';
ctx.fillStyle='rgba(255,255,255,0.4)';
ctx.fillText('Tickets',cx,cy+20);
}
function renderWorkloadTable(users, isOrg, res){
const el=$('#workloadTable');
if(!el)return;
if(!isOrg){
// Personal performance & workload scorecard
const u = users[0] || {
username: res?.target_user || S.u?.username,
name: res?.target_name || S.u?.name,
role_display: S.u?.role_display || 'Engineering',
avatar: S.u?.avatar || '👤',
open: res?.summary?.open_tickets || 0,
in_progress: res?.summary?.in_progress_tickets || 0,
completed: res?.summary?.completed_tickets || 0,
avg_hours: res?.summary?.avg_resolution_hours || 0
};
const breaches = res?.summary?.sla_breached_tickets || 0;
el.innerHTML = `
<div class="personal-scorecard">
<div class="scorecard-user">
${avHtml(u, 44)}
<div>
<h4>${esc(u.name)}</h4>
<p class="sub">@${esc(u.username)} · ${esc(u.role_display || 'Engineering')}</p>
</div>
</div>
<div class="scorecard-metrics">
<div class="scorecard-item"><span class="lbl">Active Workload</span><span class="val">${(u.open || 0) + (u.in_progress || 0)} tasks</span></div>
<div class="scorecard-item"><span class="lbl">Completed Tasks</span><span class="val green">${u.completed || 0} tasks</span></div>
<div class="scorecard-item"><span class="lbl">Avg Turnaround</span><span class="val">${u.avg_hours ? u.avg_hours + 'h' : '—'}</span></div>
<div class="scorecard-item"><span class="lbl">SLA Breaches</span><span class="val ${breaches > 0 ? 'red' : 'green'}">${breaches}</span></div>
</div>
</div>
`;
return;
}
if(!users.length){el.innerHTML='<p class="sub">No workload records found.</p>';return}
el.innerHTML=`<table class="workload-table"><thead><tr><th>Team Member</th><th>Role</th><th>Open</th><th>In Progress</th><th>Completed</th><th>Avg Resolution</th></tr></thead><tbody>${users.map(u=>`<tr>
<td><div class="workload-user">${avHtml(u,28)}<b>${esc(u.name)}</b></div></td>
<td><span class="sub" style="font-size:12px">${esc(u.role_display)}</span></td>
<td><span class="stat-pill open">${u.open||0}</span></td>
<td><span class="stat-pill prog">${u.in_progress||0}</span></td>
<td><span class="stat-pill done">${u.completed||0}</span></td>
<td><span class="mono" style="font-size:12px">${u.avg_hours?u.avg_hours+'h':'—'}</span></td>
</tr>`).join('')}</tbody></table>`;
}
function renderActivityStream(activities){
const el=$('#activityStream');
if(!el)return;
if(!activities.length){el.innerHTML='<p class="sub">No recent activity.</p>';return}
el.innerHTML=activities.map(a=>`<div class="act-item">
${avHtml({username:a.author,avatar:'👤'},28)}
<div class="act-body">
<div class="act-head"><strong>${esc(a.name||a.author)}</strong><span>${ago(a.created_at)}</span></div>
<div class="act-text">${esc(a.text)}</div>
${a.ticket_id?`<div style="font-size:10px;margin-top:2px;color:var(--pri)">${esc(a.ticket_id)} · ${esc(a.title)}</div>`:''}
</div>
</div>`).join('');
}
/* ── Admin Management View ── */
async function renderAdmin(){
put('#title','System Administration');
const activeTab=$('#adminTabs button.on')?.dataset.at||'users';
if(activeTab==='users')loadAdminUsers();
else if(activeTab==='tokens')loadAdminTokens();
else if(activeTab==='database')loadAdminDatabase();
}
async function loadAdminUsers(){
const pane=$('#adminTabUsers');
pane.innerHTML='<div class="skeleton-card"></div>';
const res=await api('/khira/api/admin/users');
if(res._f||!res.users){pane.innerHTML='<p class="err">Failed to load users.</p>';return}
pane.innerHTML=`<table class="admin-users-table">
<thead><tr><th>Avatar</th><th>Name / Username</th><th>Role</th><th>Status</th><th>Actions</th></tr></thead>
<tbody>${res.users.map(u=>`<tr>
<td>${avHtml(u,32)}</td>
<td><strong>${esc(u.name)}</strong><br><span class="sub" style="font-size:11px">@${esc(u.username)}</span></td>
<td>
<select class="admin-role-select" data-user="${esc(u.username)}">
${ROLES.map(([v,l])=>`<option value="${v}"${u.role===v?' selected':''}>${l}</option>`).join('')}
<option value="team_lead"${u.role==='team_lead'?' selected':''}>Team Lead</option>
</select>
</td>
<td><span class="stat-pill ${u.active?'done':'prog'}">${u.active?'Active':'Deactivated'}</span></td>
<td>
<button class="chip" data-admin-act="reset" data-user="${esc(u.username)}">Reset Password</button>
${u.username!=='admin'?`<button class="chip ${u.active?'del':''}" data-admin-act="toggle" data-user="${esc(u.username)}" data-cur="${u.active}">${u.active?'Deactivate':'Activate'}</button>`:''}
</td>
</tr>`).join('')}</tbody>
</table>`;
pane.querySelectorAll('.admin-role-select').forEach(sel=>{
sel.addEventListener('change',async e=>{
const uname=e.target.dataset.user;
const r=await api(`/khira/api/admin/users/${encodeURIComponent(uname)}/role`,'PATCH',{role:e.target.value});
if(r._f)toast(r.error||'Failed to update role','err');
else{toast('Role updated successfully');await refresh();}
});
});
pane.querySelectorAll('[data-admin-act]').forEach(btn=>{
btn.addEventListener('click',async()=>{
const act=btn.dataset.adminAct;
const uname=btn.dataset.user;
if(act==='toggle'){
const cur=btn.dataset.cur==='true';
const r=await api(`/khira/api/admin/users/${encodeURIComponent(uname)}/status`,'PATCH',{active:!cur});
if(r._f)toast(r.error||'Failed','err');
else{toast(cur?'Account deactivated':'Account activated');loadAdminUsers();}
}else if(act==='reset'){
dlg({
title:`Reset password for @${uname}`,
body:fld('pass','New Password',{t:'password',req:1}),
ok:'Reset Password',
go:async v=>{
const r=await api(`/khira/api/admin/users/${encodeURIComponent(uname)}/reset-password`,'POST',{new_password:v.pass});
if(r._f){toast(r.error||'Failed','err');return false}
toast('Password reset successfully');
}
});
}
});
});
}
async function loadAdminTokens(){
const pane=$('#adminTabTokens');
pane.innerHTML='<div class="skeleton-card"></div>';
const res=await api('/khira/api/tokens');
const tokens=res.tokens||[];
pane.innerHTML=`<div style="margin-bottom:16px"><button class="chip on" id="btnCreateToken">${ic('add',14)} Generate API Token</button></div>
<div style="display:flex;flex-direction:column;gap:10px">${tokens.map(t=>`<div class="chart-card" style="display:flex;align-items:center;justify-content:space-between">
<div><strong>${esc(t.name)}</strong><br><span class="sub" style="font-size:11px">Scopes: ${esc(t.scopes)} · Created: ${ago(t.created_at)} · Last used: ${ago(t.last_used_at)}</span></div>
<button class="chip del" data-revoke="${esc(t.id)}">Revoke</button>
</div>`).join('')||'<p class="sub">No active API tokens found.</p>'}</div>`;
$('#btnCreateToken')?.addEventListener('click',()=>{
dlg({
title:'Generate API Token',
sub:'Use for programmatic error reporting and CI/CD integrations.',
body:fld('name','Token Name',{req:1,v:'CI/CD Reporter'})+fld('scopes','Scopes',{v:'errors:write'}),
ok:'Generate',
go:async v=>{
const r=await api('/khira/api/tokens','POST',v);
if(r._f){toast(r.error||'Failed','err');return false}
dlg({
title:'Token Created Successfully',
sub:'Copy this token now. It will not be shown again.',
body:`<pre class="code" id="tokVal">${esc(r.token)}</pre>`,
ok:'Copy Token',
go:()=>{navigator.clipboard.writeText(r.token);toast('Token copied to clipboard');loadAdminTokens();}
});
}
});
});
pane.querySelectorAll('[data-revoke]').forEach(btn=>{
btn.addEventListener('click',async()=>{
const id=btn.dataset.revoke;
const r=await api(`/khira/api/tokens/${encodeURIComponent(id)}`,'DELETE');
if(r._f)toast(r.error||'Failed','err');
else{toast('Token revoked');loadAdminTokens();}
});
});
}
async function loadAdminDatabase(){
const pane=$('#adminTabDatabase');
pane.innerHTML='<div class="skeleton-card"></div>';
const res=await api('/khira/api/admin/db/status');
const pCounts=res.primary?.counts||{};
const bCounts=res.backup?.counts||{};
pane.innerHTML=`<div class="analytics-grid" style="margin-top:0">
<div class="chart-card">
<h3>Primary Database (PostgreSQL)</h3>
<p class="sub">Active transactional records</p>
<div style="margin-top:14px;font-size:13px;display:flex;flex-direction:column;gap:6px">
<div>Tickets: <b>${pCounts.tickets||0}</b></div>
<div>Errors: <b>${pCounts.errors||0}</b></div>
<div>Users: <b>${pCounts.users||0}</b></div>
<div>Remarks: <b>${pCounts.ticket_remarks||0}</b></div>
</div>
</div>
<div class="chart-card">
<h3>Backup Vault Database</h3>
<p class="sub">Disaster recovery standby</p>
<div style="margin-top:14px;font-size:13px;display:flex;flex-direction:column;gap:6px">
<div>Tickets: <b>${bCounts.tickets||0}</b></div>
<div>Errors: <b>${bCounts.errors||0}</b></div>
<div>Users: <b>${bCounts.users||0}</b></div>
<div>Remarks: <b>${bCounts.ticket_remarks||0}</b></div>
</div>
</div>
</div>
<div style="margin-top:20px;display:flex;gap:12px">
<button class="chip db-btn sync" id="btnAdminDBSync">${ic('sync',14)} Sync Primary to Backup</button>
<button class="chip db-btn rollback" id="btnAdminDBRollback">${ic('history',14)} Rollback Primary from Backup</button>
</div>`;
$('#btnAdminDBSync')?.addEventListener('click',adminSyncDB);
$('#btnAdminDBRollback')?.addEventListener('click',adminRollbackDB);
}
/* ── Navigation Handler ── */
function nav(sec){
S.sec=sec;S.q='';$('#q').value='';
$$('.nav button, .sidebar-nav button').forEach(b=>b.classList.toggle('on',b.dataset.s===sec));
$('#vT').hidden=sec!=='tickets';
$('#vE').hidden=sec!=='errors';
$('#vA').hidden=sec!=='analytics';
$('#vAdmin').hidden=sec!=='admin';
$('#q').placeholder=sec==='tickets'?'Search issues, errors, teammates... (press /)':sec==='errors'?'Search runtime errors...':sec==='analytics'?'Filter analytics...':'Search users...';
const titleMap = { tickets: 'Tickets', errors: 'Error Telemetry', analytics: 'Analytics & SLA', admin: 'Administration' };
put('#title', titleMap[sec] || 'Tickets');
render(true);
}
/* ── Ticket Detail Sheet ── */
function renderSheetDOM(t){
const p=pri(t),s=st(t),g=t.ticket_type==='general',rem=t.remarks||[],links=(t.links||[]).map(l=>l.url||l);
const atts=t.attachments||[];
const rels=t.related_ticket_ids||[];
const kv=(k,v,m)=>`<div><dt>${k}</dt><dd${m&&m!=='html'?' class="mono"':''}>${m==='html'?v:esc(v||'—')}</dd></div>`;
const myUser = (S.u?.username || '').toLowerCase();
const myName = (S.u?.name || '').toLowerCase();
const creatorUser = (t.created_by || t.reporter?.username || '').toLowerCase();
const assigneeUser = (t.assigned_to || t.assignee?.username || '').toLowerCase();
const resolverUser = (t.completed_by || '').toLowerCase();
const isAdm = isAdmin(S.u);
const isCreator = myUser && (myUser === creatorUser);
const isAssignee = myUser && (myUser === assigneeUser);
const isResolver = myUser && (myUser === resolverUser || myName === resolverUser);
// Corporate Privacy & Permission Rules
const canDel = (isCreator || (isAdm && !isAssignee)) && (!isAssignee || isCreator);
const isDone = s === 'completed' || s === 'closed';
const canArchive = isDone && (isResolver || isCreator || isAdm);
const archBtn = canArchive ? (t.archived ? `<button class="tn" data-do="unarchive">${ic('unarchive',14)} Restore</button>` : `<button class="tn" data-do="archive">${ic('archive',14)} Archive</button>`) : '';
const tagsList=(t.tags||[]).map(tg=>`<span class="tag-pill">${esc(tg)} <button type="button" class="tag-remove-btn" data-rm-tag="${esc(tg)}">&times;</button></span>`).join('');
const relsList=rels.map(r=>`<span class="tag-pill" style="cursor:pointer" data-view-rel="${esc(r)}">${ic('link',12)} ${esc(r)} <button type="button" class="tag-remove-btn" data-rm-rel="${esc(r)}">&times;</button></span>`).join('');
$('#sheet').innerHTML=`<div class="sbd">
<header class="sh">
<button class="ib" data-x aria-label="Close">${ic('close',16)}</button>
<span class="id mono" style="font-family:var(--font-mono);font-size:12px;color:var(--text-muted);font-weight:600">${esc(t.id)}</span>
<span class="pb ${p.toLowerCase()}">${p}</span>
${t.archived?'<span class="stt archived">Archived</span>':`<span class="stt ${s}">${STAT[s]||esc(s)}</span>`}
<div style="margin-left:auto;display:flex;align-items:center;gap:6px">
<button class="action-chip" id="btnSheetCopyLink" title="Copy issue reference" data-copy-ref="${esc(t.id)}">${ic('link',12)} <span>Copy ID</span></button>
</div>
</header>
<div class="sheet-split-layout">
<!-- Left Main Content Pane -->
<div class="sheet-main-content">
<h2 style="font-size:20px;font-weight:700;line-height:1.3;letter-spacing:-0.01em">${esc(t.title)}</h2>
<div class="sheet-section">
<h5 style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:6px">Description</h5>
<div class="desc-box" style="white-space:pre-wrap;background:var(--bg-canvas);border:1px solid var(--border-subtle);border-radius:6px;padding:12px 14px;font-size:13px;line-height:1.6">${esc(t.description||'No description provided.')}</div>
</div>
<!-- Linked Error Telemetry Card if present -->
${t.linked_error_id ? `
<div class="sheet-section">
<h5 style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--danger);margin-bottom:6px;display:flex;align-items:center;gap:6px">
${ic('bug',14)} Linked Crash Telemetry
</h5>
<div class="linked-error-card" style="background:var(--danger-bg);border:1px solid rgba(239,68,68,0.25);border-radius:6px;padding:10px 14px;display:flex;align-items:center;justify-content:space-between">
<span class="mono" style="font-size:12px;color:var(--danger);font-weight:600">${esc(t.linked_error_id)}</span>
<button type="button" class="action-chip" data-jump-err="${esc(t.linked_error_id)}" style="height:24px;font-size:11px">View Telemetry</button>
</div>
</div>` : ''}
<!-- Attachments Section -->
${atts.length?`
<div class="sheet-section">
<h5 style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:6px">Attachments (${atts.length})</h5>
<div class="att-row" style="display:flex;flex-wrap:wrap;gap:8px">${atts.map(a=>{
const isImg=a.type==='image'||/\.(png|jpe?g|webp|gif)$/i.test(a.url);
return isImg?`<div class="att-card" style="background:var(--bg-canvas);border:1px solid var(--border-subtle);border-radius:6px;padding:6px;max-width:160px"><a href="${esc(a.url)}" target="_blank" rel="noopener"><img src="${esc(a.url)}" alt="${esc(a.name)}" style="width:100%;height:90px;object-fit:cover;border-radius:4px"></a><span class="ell" style="display:block;font-size:11px;margin-top:4px">${esc(a.name)}</span></div>`
:`<div class="att-card" style="background:var(--bg-canvas);border:1px solid var(--border-subtle);border-radius:6px;padding:8px 12px"><a href="${esc(a.url)}" target="_blank" rel="noopener" class="tn" style="height:30px;font-size:12px">${ic('attachment',14)}<span class="ell">${esc(a.name)}</span></a></div>`;
}).join('')}</div>
</div>`:''}
<!-- External Links -->
${links.length?`
<div class="sheet-section">
<h5 style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:6px">External References</h5>
<div style="display:flex;flex-wrap:wrap;gap:6px">${links.map(u=>`<a href="${esc(u)}" target="_blank" rel="noopener" class="action-chip" style="font-size:12px">${ic('link',12)} ${esc(String(u).replace(/^https?:\/\//,''))}</a>`).join('')}</div>
</div>`:''}
<!-- Activity Timeline & Comments -->
<div class="sheet-section" style="margin-top:8px">
<h5 style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:10px">Activity & Remarks (${rem.length})</h5>
<div class="activity-timeline">
${rem.map(r=>{
const sys=r.system||['created','hold','complete','reassigned','priority','resume','reopen','archive','unarchive','sla_breach','reassign','link'].includes(r.type);
return`<div class="tle${sys?' sys':''}">
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:2px">
<span style="font-size:12px;font-weight:600">${sys?'System Automation':who(r.author||{name:r.author_name,username:r.author_username,role:r.author_role},r.author_name)}</span>
<small style="font-family:var(--font-mono);font-size:10px;color:var(--text-muted)">${ago(r.created_at)}</small>
</div>
<p style="font-size:12px;color:var(--text-secondary);line-height:1.4">${esc(r.text||r.body)}</p>
</div>`;
}).join('')}
</div>
<form class="cmp" id="rf" style="margin-top:12px">
<textarea id="rt" rows="2" placeholder="Write a remark or comment..." style="font-size:13px"></textarea>
<button class="action-chip primary" style="height:auto;padding:0 14px" aria-label="Send">${ic('send',14)} <span>Post</span></button>
</form>
</div>
</div>
<!-- Right Metadata Properties Pane -->
<div class="sheet-sidebar-meta">
<div class="meta-group">
<label>Status</label>
<span class="stt ${s}" style="align-self:flex-start">${STAT[s]||esc(s)}</span>
</div>
<div class="meta-group">
<label>Assignee</label>
${fld('a','',{t:'select',opts:usOpts(),v:t.assignee?.username||t.assigned_to||'',d:'data-act="assign"'})}
</div>
<div class="meta-group">
<label>Priority</label>
${fld('p','',{t:'select',opts:PRI,v:p,d:'data-act="prio"'})}
</div>
<div class="meta-group">
<label>Reporter</label>
<div style="font-size:12px;padding:4px 0">${who(t.reporter||{name:t.created_by_name,username:t.created_by,role:t.created_by_role},t.created_by_name)}</div>
</div>
${t.due_date ? `
<div class="meta-group">
<label>SLA Due Date</label>
<div style="font-family:var(--font-mono);font-size:12px;color:${t.sla_breached?'var(--danger)':'var(--text-secondary)'}">
${new Date(t.due_date).toLocaleDateString()} (${ago(t.due_date)})
</div>
</div>` : ''}
${g ? `
${t.general_category ? `<div class="meta-group"><label>Category</label><span style="font-size:12px">${esc(t.general_category)}</span></div>` : ''}
${t.department ? `<div class="meta-group"><label>Department</label><span style="font-size:12px">${esc(t.department)}</span></div>` : ''}
` : `
${t.app||t.app_name ? `<div class="meta-group"><label>Application</label><span style="font-size:12px;font-weight:600">${esc(t.app||t.app_name)}</span></div>` : ''}
${t.feature||t.feature_name ? `<div class="meta-group"><label>Subsystem</label><span style="font-size:12px">${esc(t.feature||t.feature_name)}</span></div>` : ''}
`}
<!-- Tags -->
<div class="meta-group">
<label>Tags</label>
<div class="tag-list" id="sheetTags" style="margin-top:4px">
${tagsList}
<button type="button" class="action-chip" id="btnAddTagBtn" style="height:22px;font-size:10px;padding:0 6px">+ Tag</button>
</div>
</div>
<!-- Relations -->
<div class="meta-group">
<label>Related Issues</label>
<div class="tag-list" id="sheetRels" style="margin-top:4px">
${relsList}
<button type="button" class="action-chip" id="btnLinkTicketBtn" style="height:22px;font-size:10px;padding:0 6px">+ Link</button>
</div>
</div>
</div>
</div>
<footer class="sf">
${canDel?`<button class="del-btn" data-do="del">${ic('delete',14)} Delete</button>`:''}
${archBtn}
${s==='hold'?`<button class="tn" data-do="resume">${ic('play_arrow',14)} Resume</button>`:''}
${s==='completed'?'':(s==='hold'?'':`<button class="tn" data-do="hold">${ic('pause',14)} Hold</button>`)+`<button class="fb" data-do="done">Complete Issue</button>`}
</footer>
</div>`;
// Add Tag button handler
$('#btnAddTagBtn')?.addEventListener('click',()=>{
dlg({
title:'Add Tag',
body:fld('tag','Tag Name',{req:1}),
ok:'Add',
go:async v=>{
const r=await api(`/khira/api/tickets/${encodeURIComponent(t.id)}/tags`,'POST',v);
if(r._f){toast(r.error||'Failed','err');return false}
toast('Tag added');await refresh();sheet(t.id);
}
});
});
// Remove Tag buttons
$$('[data-rm-tag]').forEach(btn=>{
btn.addEventListener('click',async()=>{
const tg=btn.dataset.rmTag;
const r=await api(`/khira/api/tickets/${encodeURIComponent(t.id)}/tags/${encodeURIComponent(tg)}`,'DELETE');
if(r._f)toast(r.error||'Failed','err');
else{toast('Tag removed');await refresh();sheet(t.id);}
});
});
// Link Ticket button handler
$('#btnLinkTicketBtn')?.addEventListener('click',()=>{
dlg({
title:'Link Related Ticket',
sub:'Link with another issue ID (e.g. KHR-102)',
body:fld('target_id','Related Ticket ID',{req:1,placeholder:'KHR-102'})+fld('rel_type','Relationship',{t:'select',opts:[['related','Related to'],['blocks','Blocks'],['blocked_by','Blocked by'],['duplicate','Duplicates']]}),
ok:'Link Ticket',
go:async v=>{
const tid=v.target_id.trim().toUpperCase();
const r=await api(`/khira/api/tickets/${encodeURIComponent(t.id)}/relations`,'POST',{target_ticket_id:tid,relation_type:v.rel_type});
if(r._f||r.error){toast(r.error||'Failed to link ticket','err');return false}
toast('Ticket linked');await refresh();sheet(t.id);
}
});
});
// Unlink / view relation buttons
$$('[data-rm-rel]').forEach(btn=>{
btn.addEventListener('click',async e=>{
e.stopPropagation();
const rel=btn.dataset.rmRel;
const r=await api(`/khira/api/tickets/${encodeURIComponent(t.id)}/relations/${encodeURIComponent(rel)}`,'DELETE');
if(r._f)toast(r.error||'Failed to unlink','err');
else{toast('Ticket unlinked');await refresh();sheet(t.id);}
});
});
$$('[data-view-rel]').forEach(el=>{
el.addEventListener('click',()=>{
const rel=el.dataset.viewRel;
if(rel) sheet(rel);
});
});
}
async function sheet(id, skipFetch){
let t=S.t.find(x=>x.id===id);
if(!t)return;
S.tid=id;
renderSheetDOM(t);
if(!$('#sheet').open)$('#sheet').showModal();
if(!skipFetch){
try {
const res = await api(`/khira/api/tickets/${encodeURIComponent(id)}`);
const full = (res && res.ticket) ? res.ticket : res;
if(full && full.id && S.tid === id && $('#sheet').open){
const idx = S.t.findIndex(x=>x.id===id);
if(idx !== -1) S.t[idx] = full;
renderSheetDOM(full);
}
} catch(e) {}
}
}
async function act(a,b,m){
const r=await api(`/khira/api/tickets/${encodeURIComponent(S.tid)}/${a}`,'POST',b);
if(r._f){toast(r.error,'err');return false}
toast(m);await refresh();sheet(S.tid);
}
async function remark(){
const ta=$('#rt'),b=ta.value.trim();
if(!b){toast('Write a remark first','err');return}
const r=await api(`/khira/api/tickets/${encodeURIComponent(S.tid)}/remarks`,'POST',{text:b,body:b,links:[]});
if(r._f){toast(r.error,'err');return}
ta.value='';
toast('Remark posted');await refresh(false);sheet(S.tid);
}
const holdD=()=>dlg({title:'Put ticket on hold',sub:'Say what is blocking this ticket.',body:fld('reason','Reason',{t:'area',rows:4,req:1}),ok:'Hold ticket',go:v=>act('hold',{reason:v.reason},'Ticket on hold')});
const doneD=()=>dlg({title:'Complete ticket',sub:'Describe how it was resolved.',body:fld('resolution','Resolution',{t:'area',rows:4,req:1}),ok:'Complete ticket',go:v=>act('complete',{remarks:v.resolution,resolution:v.resolution},'Ticket completed')});
function deleteTicketD(id){
dlg({
title:'Delete ticket',
sub:id,
body:`<p style="color:var(--err);font-weight:500">${ic('delete',18)} Are you sure you want to permanently delete this ticket and all its remarks? This action cannot be undone.</p>`,
ok:'Delete ticket',
go:async()=>{
const r=await api(`/khira/api/tickets/${encodeURIComponent(id)}`,'DELETE');
if(r._f||r.error){toast(r.error||'Could not delete ticket','err');return false}
toast(r.message||'Ticket deleted');
$('#sheet').close();
await refresh();
}
});
}
/* ── Create Ticket Modal (General Form FIRST, Application Form SECOND) ── */
function newTicket(){
dlg({wide:1,title:'New ticket',sub:`Reporting as ${esc(S.u.name)}`,ok:'Create ticket',
body:`${rad('type',[['general','General'],['application','Application']],'general')}
<fieldset class="grp" data-g="general">
<div class="g2">
${fld('assignee_username','Choose assignee',{t:'select',opts:usOpts(1),req:1})}
${fld('general_category','General Category',{t:'select',opts:[['Infrastructure','Infrastructure'],['Security','Security'],['Operations','Operations'],['Design','Design'],['DevOps','DevOps'],['General','General']]})}
</div>
${fld('department','Department',{t:'select',opts:[['Engineering','Engineering'],['QA / Testing','QA / Testing'],['Product','Product'],['Operations','Operations'],['IT Support','IT Support']]})}
${fld('title','Write title',{req:1})}
${fld('description','Description',{t:'area',rows:4,req:1})}
</fieldset>
<fieldset class="grp" data-g="application" hidden disabled>
<label class="fld sel">
<select name="assignee_username" id="appDevSelect" required>
${usOpts(1).map(([v,l])=>`<option value="${esc(v)}">${esc(l)}</option>`).join('')}
</select>
<span>Developer account *</span>
</label>
<div class="app-ac-wrap">
<label class="fld">
<input name="app" id="appInput" placeholder=" " autocomplete="off" required>
<span>App name *</span>
</label>
<div class="app-ac-menu" id="appSugMenu" hidden></div>
<div id="appConflictWarn" class="app-ac-conflict" style="display:none"></div>
</div>
${fld('version','Version',{req:1})}
${fld('feature','Feature name')}
${fld('api_key','API key')}
${fld('title','Title',{req:1})}
${fld('description','Description',{t:'area',rows:4,req:1})}
<div class="fld-upload">
<label class="upload-btn" id="lblImgUpload">
${ic('photo_camera',18)}
<span id="imgUploadTxt">Upload image (Optional)</span>
<input type="file" id="appImgInput" accept="image/*" style="display:none">
</label>
<div id="imgPreviewWrap" class="img-preview-wrap" style="display:none">
<img id="imgPreview" src="" alt="Screenshot preview">
<button type="button" class="rm-btn" id="btnRemoveImg" title="Remove image" aria-label="Remove image">${ic('close',14)}</button>
</div>
</div>
</fieldset>`,
init:f=>{
let selectedImageFile=null;
const sw=()=>{
const g=f.querySelector('[name=type]:checked')?.value||'general';
f.querySelectorAll('.grp').forEach(x=>{
const on=x.dataset.g===g;
x.hidden=!on;
x.disabled=!on;
x.querySelectorAll('input, select, textarea').forEach(inp=>{
inp.disabled=!on;
});
});
};
f.querySelectorAll('[name=type]').forEach(r=>r.onchange=sw);
sw();
// App Autocomplete & dynamic role-based app suggestions
const devSel=f.querySelector('#appDevSelect');
const appInp=f.querySelector('#appInput');
const sugMenu=f.querySelector('#appSugMenu');
const conflictWarn=f.querySelector('#appConflictWarn');
let allApps=[];
const loadApps=async()=>{
try{
const res=await api('/khira/api/apps');
if(res.apps&&Array.isArray(res.apps)){
allApps=res.apps;
}
}catch(err){
console.error('Failed to load apps list',err);
}
};
loadApps();
const getSelectedDevRole=()=>{
const username=devSel?.value;
if(!username)return null;
const u=S.us.find(x=>x.username===username);
return u?u.role:null;
};
const getFilteredApps=()=>{
const role=getSelectedDevRole();
if(!role)return allApps;
if(role==='ios_dev'||role==='ios'||role==='frontend'||role==='frontend_dev'){
return allApps.filter(a=>!a.role_hint||a.role_hint==='ios_dev');
}
if(role==='android_dev'||role==='android'){
return allApps.filter(a=>!a.role_hint||a.role_hint==='android_dev');
}
return allApps;
};
const showSuggestions=val=>{
if(!sugMenu)return;
const filtered=getFilteredApps();
const q=val.trim().toLowerCase();
const matches=filtered.filter(a=>!q||a.name.toLowerCase().includes(q));
if(!matches.length){sugMenu.hidden=true;return}
sugMenu.innerHTML=matches.map(a=>`
<div class="app-ac-item" data-app="${esc(a.name)}" data-role="${esc(a.role_hint||'')}">
<span class="app-ac-name">${esc(a.name)}</span>
${a.role_hint?`<span class="app-ac-tag ${a.role_hint}">${a.role_hint==='ios_dev'?'iOS App':'Android App'}</span>`:''}
</div>
`).join('');
sugMenu.hidden=false;
sugMenu.querySelectorAll('.app-ac-item').forEach(item=>{
item.onmousedown=e=>{
e.preventDefault();
appInp.value=item.dataset.app;
sugMenu.hidden=true;
checkRoleConflict();
};
});
};
const checkRoleConflict=()=>{
if(!conflictWarn)return;
const role=getSelectedDevRole();
const val=appInp?.value.trim();
if(!val||!role){conflictWarn.style.display='none';return}
const appObj=allApps.find(a=>a.name.toLowerCase()===val.toLowerCase());
if(!appObj||!appObj.role_hint){conflictWarn.style.display='none';return}
if((role==='ios_dev'||role==='ios')&&appObj.role_hint==='android_dev'){
conflictWarn.style.display='flex';
conflictWarn.innerHTML=`${ic('warning',16)} <span>Selected developer is iOS Dev, but "${esc(val)}" is an Android application.</span>`;
}else if((role==='android_dev'||role==='android')&&appObj.role_hint==='ios_dev'){
conflictWarn.style.display='flex';
conflictWarn.innerHTML=`${ic('warning',16)} <span>Selected developer is Android Dev, but "${esc(val)}" is an iOS application.</span>`;
}else{
conflictWarn.style.display='none';
}
};
if(appInp){
appInp.oninput=()=>showSuggestions(appInp.value);
appInp.onfocus=()=>showSuggestions(appInp.value);
appInp.onblur=()=>{setTimeout(()=>{if(sugMenu)sugMenu.hidden=true},200);checkRoleConflict()};
}
if(devSel){
devSel.onchange=()=>{
checkRoleConflict();
if(appInp&&document.activeElement===appInp){
showSuggestions(appInp.value);
}
};
}
const fileInp=f.querySelector('#appImgInput');
const previewWrap=f.querySelector('#imgPreviewWrap');
const previewImg=f.querySelector('#imgPreview');
const uploadTxt=f.querySelector('#imgUploadTxt');
const btnRemoveImg=f.querySelector('#btnRemoveImg');
if(fileInp){
fileInp.onchange=()=>{
const file=fileInp.files[0];
if(!file)return;
selectedImageFile=file;
const reader=new FileReader();
reader.onload=e=>{
if(previewImg)previewImg.src=e.target.result;
if(previewWrap)previewWrap.style.display='flex';
if(uploadTxt)uploadTxt.textContent='Change image';
};
reader.readAsDataURL(file);
};
}
if(btnRemoveImg){
btnRemoveImg.onclick=e=>{
e.preventDefault();
selectedImageFile=null;
if(fileInp)fileInp.value='';
if(previewImg)previewImg.src='';
if(previewWrap)previewWrap.style.display='none';
if(uploadTxt)uploadTxt.textContent='Upload image (Optional)';
};
}
f._getSelectedFile=()=>selectedImageFile;
},
go:async v=>{
const f=$('#dlg form');
const file=f?._getSelectedFile?.();
let uploadedImageUrl='';
if(file){
const fd=new FormData();
fd.append('file',file);
try{
const un=S.u?.username||ls('khira_active_user');
const tok=ls('khira_session_token');
const upHeaders={'X-Khira-User':un};
if(tok)upHeaders['Authorization']='Bearer '+tok;
const upRes=await fetch('/khira/api/upload',{method:'POST',headers:upHeaders,credentials:'same-origin',body:fd});
const upJson=await upRes.json();
const url=upJson.url||upJson.attachment?.url;
if(url)uploadedImageUrl=url;
}catch(err){
console.error('Failed to upload image attachment',err);
toast('Could not upload image, submitting ticket without it','err');
}
}
const payload={...v};
if(uploadedImageUrl){
payload.image_url=uploadedImageUrl;
payload.attachments=[{name:file.name,url:uploadedImageUrl,type:'image',size:file.size}];
}
const r=await api('/khira/api/tickets','POST',payload);
if(r._f){toast(r.error,'err');return false}
toast('Ticket created');
await refresh();
sheet(r.id);
}});
}
/* ── Error Details & Escalation ── */
function errD(id){
const e=S.e.find(x=>x.id===id);if(!e)return;
if(e.is_draft||e.status==='draft'){
return reportErr(e);
}
const k=ek(e);
const blk=(l,v)=>v?`<div><p class="lbl">${l}</p><pre class="code">${esc(v)}</pre></div>`:'';
const appName=e.app_name||e.app||'';
const isArch=!!e.archived;
const platChip=`<span class="meta-chip ${e.platform==='Android'?'android':'ios'}">${e.platform==='Android'?'🤖 Android':'🍏 iOS'}</span>`;
const typeChip=`<span class="meta-chip ${e.error_type==='Crash'?'crash':'bug'}">${esc(e.error_type||'Bug')}</span>`;
const phaseChip=e.current_phase?`<span class="meta-chip">${esc(e.current_phase)}</span>`:'';
const imgHtml=e.image_url?`<div style="margin:12px 0">
<p class="lbl">Attached Image / Screenshot</p>
<a href="${esc(e.image_url)}" target="_blank" rel="noopener">
<img src="${esc(e.image_url)}" alt="Error attachment" style="max-width:100%;max-height:260px;border-radius:12px;border:1px solid rgba(255,255,255,0.15);box-shadow:0 4px 16px rgba(0,0,0,0.6)">
</a>
</div>`:'';
dlg({wide:1,title:esc(e.exception_type||e.error_type||'Application Error'),sub:esc(`${e.id} · ${appName}${verFmt(e.version)}${e.error_screen?' · Screen: '+e.error_screen:''}`),
body:`<div class="r" style="gap:8px;align-items:center;margin-bottom:8px">
<span class="sv ${(e.severity||'MEDIUM').toUpperCase()}">${esc(e.severity||'Medium')}</span>
<span class="stt ${isArch?'archived':k}">${isArch?'Archived':EL[k]||k}</span>
${platChip}
${typeChip}
${phaseChip}
<span class="id" style="margin-left:auto">${e.events||e.occurrences||1} events · ${ago(e.last_seen||e.created_at)}</span>
</div>
${e.feature_name?`<p style="font-size:12px;color:var(--pri);margin-bottom:6px"><b>Feature:</b> ${esc(e.feature_name)}</p>`:''}
${e.assigned_to?`<p style="font-size:12px;color:#a78bfa;margin-bottom:8px"><b>Assigned to Developer:</b> @${esc(e.assigned_to)}</p>`:''}
<div style="font-size:14px;line-height:1.6;color:var(--on-s);margin:10px 0;white-space:pre-wrap"><b>Description:</b><br>${esc(e.description||e.message)}</div>
${imgHtml}
${blk('Additional Info & Reproduction',e.additional_info)}
${blk('Endpoint / Route',e.endpoint)}
${blk('Stack Trace / Logs',e.stack_trace)}
${e.escalated_ticket_id||e.linked_ticket_id?`<p class="sub">Escalated as ${esc(e.escalated_ticket_id||e.linked_ticket_id)}</p>`:''}
${e.resolution_notes?`<p class="sub">Resolution: ${esc(e.resolution_notes)}</p>`:''}`,
ok:k==='resolved'?'Close':'Escalate to ticket',
alt:k==='unresolved'?['Resolve',()=>resolveD(id)]:(k==='resolved'?[(isArch?'Restore':'Archive'),async()=>{
const actName=isArch?'unarchive':'archive';
const r=await api(`/khira/api/errors/${encodeURIComponent(id)}/${actName}`,'POST');
if(r._f||r.error){toast(r.error||'Failed','err');return false}
toast(isArch?'Error restored from archive':'Error moved to archive');
$('#dlg').close();
await refresh();
}]:undefined),
go:()=>k!=='resolved'&&escD(id)});
}
function escD(id){
const e=S.e.find(x=>x.id===id);
const msg = (e.message || '').slice(0,60);
dlg({title:'Escalate error to ticket',sub:e.id,
body:fld('title','Ticket title',{req:1,v:`[${e.platform||'App'} · ${e.app||e.app_name}] ${e.exception_type||e.error_type}: ${msg}`})+fld('priority','Priority',{t:'select',opts:PRI,v:'P1'})+fld('assignee','Assign to',{t:'select',opts:usOpts(1),req:1,v:e.assigned_to||''}),
ok:'Escalate',go:async v=>{
const r=await api(`/khira/api/errors/${encodeURIComponent(id)}/escalate`,'POST',{title:v.title,priority:v.priority,assigned_to:v.assignee});
if(r._f){toast(r.error,'err');return false}
toast('Escalated to ticket');await refresh();sheet(r.ticket_id);
}});
}
function resolveD(id){
dlg({title:'Resolve error',sub:'Explain the fix applied.',body:fld('notes','Resolution notes',{t:'area',rows:4,req:1}),ok:'Mark resolved',
go:async v=>{
const r=await api(`/khira/api/errors/${encodeURIComponent(id)}/status`,'POST',{status:'resolved',notes:v.notes});
if(r._f){toast(r.error,'err');return false}
toast('Error marked resolved');await refresh();
}});
}
/* ── Application-Oriented Error Reporting Form with Drafts ── */
function reportErr(prefill={}){
const isEdit=!!prefill.id;
const isDraft=!!(prefill.is_draft||prefill.status==='draft');
const d=$('#dlg');
d.className='wide';
const curPlatform=prefill.platform||'iOS';
const curPhase=prefill.current_phase||'development phase';
const curErrorType=prefill.error_type||'Bug';
const curAppName=prefill.app_name||prefill.app||'';
const curVersion=prefill.version||'';
const curScreen=prefill.error_screen||'';
const curFeature=prefill.feature_name||prefill.service||'';
const curDesc=prefill.description||prefill.message||'';
const curAddInfo=prefill.additional_info||prefill.stack_trace||'';
const curImg=prefill.image_url||'';
const curAssignee=prefill.assigned_to||'';
const titleText=isEdit?(isDraft?`Edit Error Draft · ${esc(prefill.id)}`:`Edit Error · ${esc(prefill.id)}`):'Report Application Error';
const subText=isDraft?'Edit draft fields and send to developer or save for later.':'Submit application bugs and crashes, or save as draft before final publishing.';
d.innerHTML=`<form class="dc" id="errReportForm" novalidate>
<h3>${titleText}</h3>
<p class="sub">${subText}</p>
<div class="db" style="padding-top:14px">
<!-- Platform & Current Phase Selection -->
<div class="err-form-grid">
<div class="form-seg-group">
<label class="form-seg-label">Platform *</label>
<div class="seg-pills" id="platformPills">
<button type="button" class="seg-pill ${curPlatform==='iOS'?'on':''}" data-v="iOS">
<svg class="ic" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20.94c1.5 0 2.75 1.06 4 1.06 3 0 6-8 6-12.22A4.91 4.91 0 0 0 17 5c-2.22 0-4 1.44-5 2-1-.56-2.78-2-5-2a4.9 4.9 0 0 0-5 4.78C2 14 5 22 8 22c1.25 0 2.5-1.06 4-1.06Z"/><path d="M10 2c1 .5 2 2 2 5"/></svg>
iOS
</button>
<button type="button" class="seg-pill ${curPlatform==='Android'?'on':''}" data-v="Android">
<svg class="ic" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 18a5 5 0 0 0-10 0"/><line x1="12" y1="2" x2="12" y2="4"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="19.78" y1="4.22" x2="18.36" y2="5.64"/><circle cx="9" cy="9" r="1"/><circle cx="15" cy="9" r="1"/></svg>
Android
</button>
</div>
<input type="hidden" name="platform" id="inputPlatform" value="${esc(curPlatform)}">
</div>
<div class="form-seg-group">
<label class="form-seg-label">Current Phase *</label>
<div class="seg-pills" id="phasePills">
<button type="button" class="seg-pill ${curPhase==='development phase'?'on':''}" data-v="development phase">Development Phase</button>
<button type="button" class="seg-pill ${curPhase==='ready to live'?'on':''}" data-v="ready to live">Ready to Live</button>
</div>
<input type="hidden" name="current_phase" id="inputPhase" value="${esc(curPhase)}">
</div>
</div>
<!-- App Name & Version -->
<div class="err-form-grid">
<label class="fld">
<input name="app_name" id="errAppName" list="appNameSuggestions" placeholder=" " value="${esc(curAppName)}" required>
<span>App name *</span>
<datalist id="appNameSuggestions">
<option value="Creator Suite iOS">
<option value="Creator Suite Android">
<option value="Image Manipulator Pro">
<option value="Unified Dashboard Client">
<option value="Khira Issue Tracker">
<option value="FastAPI Backend">
</datalist>
</label>
<label class="fld">
<input name="version" id="errVersion" placeholder=" " value="${esc(curVersion)}">
<span>Version (e.g. 1.0.0)</span>
</label>
</div>
<!-- Error Screen & Feature Name -->
<div class="err-form-grid">
<label class="fld">
<input name="error_screen" id="errScreen" placeholder=" " value="${esc(curScreen)}">
<span>Error screen (e.g. Login, Canvas, Settings)</span>
</label>
<label class="fld">
<input name="feature_name" id="errFeature" placeholder=" " value="${esc(curFeature)}">
<span>Feature name (e.g. Biometric Auth, Face Swap)</span>
</label>
</div>
<!-- Error Type -->
<div class="form-seg-group">
<label class="form-seg-label">Error Type *</label>
<div class="seg-pills" id="errTypePills">
<button type="button" class="seg-pill bug-pill ${curErrorType==='Bug'?'on':''}" data-v="Bug">
${ic('bug', 15)} Bug
</button>
<button type="button" class="seg-pill crash-pill ${curErrorType==='Crash'?'on':''}" data-v="Crash">
${ic('warning', 15)} Crash
</button>
</div>
<input type="hidden" name="error_type" id="inputErrType" value="${esc(curErrorType)}">
</div>
<!-- Description (Describe error) -->
<label class="fld">
<textarea name="description" id="errDesc" rows="3" placeholder=" " required>${esc(curDesc)}</textarea>
<span>Description (Describe error) *</span>
</label>
<!-- Attach image if you want to -->
<div class="err-attach-group">
<label class="form-seg-label">Attach image (Optional)</label>
<div class="err-upload-box" id="errImgUploadBox">
<input type="file" id="errImgFileInput" accept="image/*" style="display:none">
<input type="hidden" name="image_url" id="errImgUrlInput" value="${esc(curImg)}">
<div id="errImgPlaceholder" class="err-upload-placeholder" ${curImg?'hidden':''}>
<svg class="ic" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
<span>Click to attach screenshot or drag &amp; drop</span>
</div>
<div id="errImgPreviewWrap" class="err-upload-preview" ${curImg?'':'hidden'}>
<img id="errImgThumb" src="${esc(curImg)}" alt="Attached preview">
<div class="err-upload-meta">
<span id="errImgName" class="ell">${curImg?esc(curImg.split('/').pop()):''}</span>
<button type="button" class="tn err-rm-img-btn" id="btnRmErrImg">&times; Remove image</button>
</div>
</div>
</div>
</div>
<!-- Any additional info -->
<label class="fld">
<textarea name="additional_info" id="errAddInfo" rows="2" placeholder=" ">${esc(curAddInfo)}</textarea>
<span>Any additional info (Device model, OS build, reproduction steps)</span>
</label>
<!-- Send to Developer or another person -->
<label class="fld sel">
<select name="assigned_to" id="errAssigneeSelect">
<option value="">None (Unassigned)</option>
${S.us.map(u=>`<option value="${esc(u.username)}"${u.username===curAssignee?' selected':''}>${esc(u.name)} · ${esc(u.role_display)}</option>`).join('')}
</select>
<span>Send / Assign to Developer (Optional)</span>
</label>
</div>
<!-- Actions Bar -->
<div class="da" style="align-items:center;padding:12px 24px 0">
<button type="button" class="tb" data-x>Cancel</button>
${isEdit?`<button type="button" class="tb del-draft-btn" id="btnDeleteErr" style="color:#ef4444">${ic('delete',15)} Delete</button>`:''}
<div style="flex:1"></div>
<button type="button" class="tb draft-btn" id="btnSaveDraft">
<svg class="ic" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:middle;margin-right:4px"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
Save as draft
</button>
<button type="submit" class="fb submit-err-btn" id="btnSubmitErr">
<svg class="ic" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:middle;margin-right:4px"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
${isEdit&&isDraft?'Publish & Send':'Submit'}
</button>
</div>
</form>`;
const form=$('#errReportForm');
// Interactive Pill Switchers
const bindPillGroup=(containerId, hiddenInputId)=>{
const wrap=form.querySelector(containerId);
const inp=form.querySelector(hiddenInputId);
if(!wrap||!inp)return;
wrap.querySelectorAll('.seg-pill').forEach(btn=>{
btn.onclick=()=>{
wrap.querySelectorAll('.seg-pill').forEach(b=>b.classList.remove('on'));
btn.classList.add('on');
inp.value=btn.dataset.v;
};
});
};
bindPillGroup('#platformPills','#inputPlatform');
bindPillGroup('#phasePills','#inputPhase');
bindPillGroup('#errTypePills','#inputErrType');
// Image Upload Binding
const uploadBox=form.querySelector('#errImgUploadBox');
const fileInput=form.querySelector('#errImgFileInput');
const imgUrlInput=form.querySelector('#errImgUrlInput');
const placeholder=form.querySelector('#errImgPlaceholder');
const previewWrap=form.querySelector('#errImgPreviewWrap');
const thumb=form.querySelector('#errImgThumb');
const imgName=form.querySelector('#errImgName');
const rmBtn=form.querySelector('#btnRmErrImg');
uploadBox.onclick=(e)=>{
if(e.target.closest('#btnRmErrImg'))return;
fileInput.click();
};
fileInput.onchange=async()=>{
const file=fileInput.files[0];
if(!file)return;
const fd=new FormData();
fd.append('file',file);
try{
toast('Uploading image...');
const un=S.u?.username||ls('khira_active_user');
const tok=ls('khira_session_token');
const upHeaders={'X-Khira-User':un};
if(tok)upHeaders['Authorization']='Bearer '+tok;
const res=await fetch('/khira/api/upload',{
method:'POST',
headers:upHeaders,
credentials:'same-origin',
body:fd
});
const data=await res.json();
const url=data.url||data.attachment?.url;
if(data.status==='ok'&&url){
imgUrlInput.value=url;
thumb.src=url;
imgName.textContent=file.name;
placeholder.hidden=true;
previewWrap.hidden=false;
toast('Image attached');
}else{
toast(data.error||'Failed to upload image','err');
}
}catch(err){
toast('Upload failed','err');
}
};
rmBtn.onclick=(e)=>{
e.stopPropagation();
imgUrlInput.value='';
fileInput.value='';
thumb.src='';
imgName.textContent='';
placeholder.hidden=false;
previewWrap.hidden=true;
};
// Helper to collect payload
const getPayload=(asDraft)=>{
const app=form.querySelector('#errAppName').value.trim()||(asDraft?'Draft Application':'');
const desc=form.querySelector('#errDesc').value.trim()||(asDraft?'(Draft description)':'');
const errType=form.querySelector('#inputErrType').value||'Bug';
return {
platform:form.querySelector('#inputPlatform').value||'iOS',
current_phase:form.querySelector('#inputPhase').value||'development phase',
app_name:app,
version:form.querySelector('#errVersion').value.trim(),
error_screen:form.querySelector('#errScreen').value.trim(),
feature_name:form.querySelector('#errFeature').value.trim(),
error_type:errType,
exception_type:errType,
description:desc,
message:desc,
image_url:imgUrlInput.value,
additional_info:form.querySelector('#errAddInfo').value.trim(),
assigned_to:form.querySelector('#errAssigneeSelect').value,
is_draft:asDraft
};
};
// Save as draft handler
form.querySelector('#btnSaveDraft')?.addEventListener('click',async()=>{
const payload=getPayload(true);
const saveBtn=form.querySelector('#btnSaveDraft');
await busy(saveBtn,async()=>{
let r;
if(isEdit){
r=await api(`/khira/api/errors/${encodeURIComponent(prefill.id)}`,'PUT',payload);
}else{
r=await api('/khira/api/errors','POST',payload);
}
if(r._f||typeof r.error==='string'){
toast((typeof r.error==='string'?r.error:'')||'Failed to save draft','err');
return;
}
toast('Draft saved successfully');
d.close();
await refresh();
});
});
// Submit handler (Publish)
form.onsubmit=async(e)=>{
e.preventDefault();
const app=form.querySelector('#errAppName').value.trim();
const desc=form.querySelector('#errDesc').value.trim();
if(!app){toast('Please enter an app name','err');return}
if(!desc){toast('Please describe the error','err');return}
const payload=getPayload(false);
const submitBtn=form.querySelector('#btnSubmitErr');
await busy(submitBtn,async()=>{
let r;
if(isEdit){
r=await api(`/khira/api/errors/${encodeURIComponent(prefill.id)}`,'PUT',payload);
}else{
r=await api('/khira/api/errors','POST',payload);
}
if(r._f||typeof r.error==='string'){
toast((typeof r.error==='string'?r.error:'')||'Failed to submit error','err');
return;
}
const sentNotice=payload.assigned_to?` and sent to @${payload.assigned_to}`:'';
toast(isEdit&&isDraft?`Draft published${sentNotice}`:`Error submitted${sentNotice}`);
d.close();
await refresh();
});
};
// Delete draft / error handler
form.querySelector('#btnDeleteErr')?.addEventListener('click',async()=>{
if(!confirm(`Are you sure you want to delete this ${isDraft?'draft':'error'}?`))return;
const r=await api(`/khira/api/errors/${encodeURIComponent(prefill.id)}`,'DELETE');
if(r._f||r.error){
toast(r.error||'Delete failed','err');
return;
}
toast('Error removed');
d.close();
await refresh();
});
if(!d.open)d.showModal();
}
/* ── Bulk Actions Management ── */
function toggleBulkMode(){
S.bulkMode=!S.bulkMode;
if(!S.bulkMode)S.bulkSelected.clear();
$('#btnToggleBulk').classList.toggle('on',S.bulkMode);
updateBulkBar();
render(false);
}
function updateBulkBar(){
const bar=$('#bulkBar');
const count=S.bulkSelected.size;
if(!bar)return;
bar.hidden=!S.bulkMode||count===0;
$('#bulkCount').textContent=count;
}
$('#btnToggleBulk')?.addEventListener('click',toggleBulkMode);
$('#btnBulkCancel')?.addEventListener('click',()=>{
S.bulkSelected.clear();
updateBulkBar();
render(false);
});
$('#btnBulkStatus')?.addEventListener('click',()=>{
if(!S.bulkSelected.size)return;
dlg({
title:`Update Status for ${S.bulkSelected.size} Tickets`,
body:fld('status','Status',{t:'select',opts:[['open','Open'],['in_progress','In Progress'],['completed','Completed']]}),
ok:'Apply',
go:async v=>{
const r=await api('/khira/api/tickets/bulk','POST',{ids:[...S.bulkSelected],action:'status',value:v.status});
if(r._f)toast(r.error||'Bulk action failed','err');
else{toast(`Updated ${r.updated} tickets`);S.bulkSelected.clear();updateBulkBar();await refresh();}
}
});
});
$('#btnBulkPriority')?.addEventListener('click',()=>{
if(!S.bulkSelected.size)return;
dlg({
title:`Update Priority for ${S.bulkSelected.size} Tickets`,
body:fld('priority','Priority',{t:'select',opts:PRI}),
ok:'Apply',
go:async v=>{
const r=await api('/khira/api/tickets/bulk','POST',{ids:[...S.bulkSelected],action:'priority',value:v.priority.toLowerCase()});
if(r._f)toast(r.error||'Bulk action failed','err');
else{toast(`Updated ${r.updated} tickets`);S.bulkSelected.clear();updateBulkBar();await refresh();}
}
});
});
$('#btnBulkAssign')?.addEventListener('click',()=>{
if(!S.bulkSelected.size)return;
dlg({
title:`Reassign ${S.bulkSelected.size} Tickets`,
body:fld('assignee','Assign to',{t:'select',opts:usOpts(1),req:1}),
ok:'Reassign',
go:async v=>{
const r=await api('/khira/api/tickets/bulk','POST',{ids:[...S.bulkSelected],action:'assign',value:v.assignee});
if(r._f)toast(r.error||'Bulk action failed','err');
else{toast(`Reassigned ${r.updated} tickets`);S.bulkSelected.clear();updateBulkBar();await refresh();}
}
});
});
$('#btnBulkArchive')?.addEventListener('click',async()=>{
if(!S.bulkSelected.size)return;
const r=await api('/khira/api/tickets/bulk','POST',{ids:[...S.bulkSelected],action:'archive'});
if(r._f)toast(r.error||'Bulk action failed','err');
else{toast(`Archived ${r.updated} tickets`);S.bulkSelected.clear();updateBulkBar();await refresh();}
});
$('#btnBulkDelete')?.addEventListener('click',()=>{
if(!S.bulkSelected.size)return;
dlg({
title:`Permanently Delete ${S.bulkSelected.size} Tickets?`,
body:`<p style="color:var(--err);font-weight:500">${ic('delete',18)} This will permanently delete all selected tickets and remarks. You must be creator or administrator.</p>`,
ok:'Delete All',
go:async()=>{
const r=await api('/khira/api/tickets/bulk','POST',{ids:[...S.bulkSelected],action:'delete'});
if(r._f)toast(r.error||'Failed','err');
else{toast(`Deleted ${r.updated} tickets`);S.bulkSelected.clear();updateBulkBar();await refresh();}
}
});
});
/* ── Command Palette (Cmd+K) ── */
function openCmdPalette(){
const p=$('#cmdPalette');
if(!p)return;
p.hidden=false;
const inp=$('#cmdInput');
inp.value='';
inp.focus();
renderCmdResults('');
}
function closeCmdPalette(){
const p=$('#cmdPalette');
if(p)p.hidden=true;
}
function renderCmdResults(q){
const list=$('#cmdResults');
if(!list)return;
q=q.trim().toLowerCase();
const actions=[
{id:'act_new',title:'Create New Ticket',sub:'Open ticket form',type:'Action',icon:'add',go:newTicket},
{id:'act_analytics',title:'Go to Analytics',sub:'View team velocity and charts',type:'Action',icon:'ticket',go:()=>nav('analytics')},
{id:'act_board',title:'Switch to Kanban Board',sub:'View board columns',type:'Action',icon:'view_kanban',go:()=>{S.view='board';nav('tickets')}},
{id:'act_list',title:'Switch to List View',sub:'View date-grouped list',type:'Action',icon:'view_list',go:()=>{S.view='list';nav('tickets')}},
{id:'act_theme',title:'Toggle Dark/Light Theme',sub:'Switch UI color theme',type:'Action',icon:'sun',go:()=>{theme(document.documentElement.dataset.theme==='dark'?'light':'dark')}}
];
let items=[];
if(!q){
items=actions.slice(0,4).concat(S.t.slice(0,4).map(t=>({
id:t.id,title:`${t.id}: ${t.title}`,sub:sub(t),type:'Ticket',icon:'ticket',go:()=>sheet(t.id)
})));
}else{
const matchedActions=actions.filter(a=>a.title.toLowerCase().includes(q)||a.sub.toLowerCase().includes(q));
const matchedTickets=S.t.filter(t=>t.id.toLowerCase().includes(q)||t.title.toLowerCase().includes(q)||sub(t).toLowerCase().includes(q)).slice(0,6).map(t=>({
id:t.id,title:`${t.id}: ${t.title}`,sub:sub(t),type:'Ticket',icon:'ticket',go:()=>sheet(t.id)
}));
const matchedErrors=S.e.filter(e=>e.id.toLowerCase().includes(q)||e.exception_type.toLowerCase().includes(q)||e.message.toLowerCase().includes(q)).slice(0,4).map(e=>({
id:e.id,title:`${e.id}: ${e.exception_type}`,sub:e.message,type:'Error',icon:'bug',go:()=>errD(e.id)
}));
const matchedUsers=S.us.filter(u=>u.name.toLowerCase().includes(q)||u.username.toLowerCase().includes(q)).slice(0,3).map(u=>({
id:u.username,title:`${u.name} (@${u.username})`,sub:u.role_display,type:'User',icon:'search',go:()=>{S.fa=u.username;nav('tickets');}
}));
items=matchedActions.concat(matchedTickets).concat(matchedErrors).concat(matchedUsers);
}
cmdSelectedIndex=0;
if(!items.length){
list.innerHTML='<div style="padding:20px;text-align:center;color:var(--sub)">No results found.</div>';
return;
}
list.innerHTML=items.map((it,i)=>`<div class="cmd-item ${i===0?'active':''}" data-ci="${i}">
<div class="cmd-item-left">
${ic(it.icon,16)}
<div><div>${esc(it.title)}</div><div class="sub" style="font-size:11px">${esc(it.sub)}</div></div>
</div>
<span class="cmd-item-type">${esc(it.type)}</span>
</div>`).join('');
list.querySelectorAll('.cmd-item').forEach((el,i)=>{
el.onclick=()=>{
closeCmdPalette();
items[i]?.go();
};
});
}
let cmdSelectedIndex = 0;
$('#btnCmdK')?.addEventListener('click',openCmdPalette);
$('#cmdInput')?.addEventListener('input',e=>renderCmdResults(e.target.value));
$('#cmdInput')?.addEventListener('keydown',e=>{
const items=$$('#cmdResults .cmd-item');
if(!items.length)return;
if(e.key==='ArrowDown'){
e.preventDefault();
cmdSelectedIndex=(cmdSelectedIndex+1)%items.length;
items.forEach((el,idx)=>el.classList.toggle('active',idx===cmdSelectedIndex));
items[cmdSelectedIndex]?.scrollIntoView({block:'nearest'});
}else if(e.key==='ArrowUp'){
e.preventDefault();
cmdSelectedIndex=(cmdSelectedIndex-1+items.length)%items.length;
items.forEach((el,idx)=>el.classList.toggle('active',idx===cmdSelectedIndex));
items[cmdSelectedIndex]?.scrollIntoView({block:'nearest'});
}else if(e.key==='Enter'){
e.preventDefault();
if(items[cmdSelectedIndex]){
items[cmdSelectedIndex].click();
}
}
});
$('#cmdPalette')?.addEventListener('click',e=>{if(e.target.id==='cmdPalette')closeCmdPalette()});
/* ── Keyboard Shortcuts ── */
window.addEventListener('keydown', e => {
// If app workspace is not active (e.g. login screen), do not trigger shortcuts
if ($('#app')?.hidden) return;
// Global Cmd+K / Ctrl+K
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
e.preventDefault();
if ($('#cmdPalette').hidden) openCmdPalette();
else closeCmdPalette();
return;
}
// Escape key handler: close any active overlay, sheet, dialog, or modal
if (e.key === 'Escape') {
if (!$('#shortcutsModal')?.hidden) {
$('#shortcutsModal').hidden = true;
return;
}
if (!$('#cmdPalette')?.hidden) {
closeCmdPalette();
return;
}
if ($('#dlg')?.open) {
$('#dlg').close();
return;
}
if ($('#sheet')?.open) {
$('#sheet').close();
return;
}
return;
}
// Do not intercept keystrokes when typing in inputs or textareas
const tag = document.activeElement?.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || document.activeElement?.isContentEditable) return;
// Do not fire navigation/creation shortcuts if any modal, sheet, or overlay is active
if (!$('#shortcutsModal')?.hidden || !$('#cmdPalette')?.hidden || $('#dlg')?.open || $('#sheet')?.open) return;
if (e.key === '?' || (e.key === '/' && e.shiftKey)) {
e.preventDefault();
$('#shortcutsModal').hidden = !$('#shortcutsModal').hidden;
} else if (e.key === 'n' || e.key === 'N' || e.key === 'c' || e.key === 'C') {
e.preventDefault();
newTicket();
} else if (e.key === 't' || e.key === 'T') {
nav('tickets');
} else if (e.key === 'e' || e.key === 'E') {
nav('errors');
} else if (e.key === 'a' || e.key === 'A') {
nav('analytics');
} else if (e.key === 'b' || e.key === 'B') {
S.view = 'board';
nav('tickets');
} else if (e.key === 'l' || e.key === 'L') {
S.view = 'list';
nav('tickets');
} else if (e.key === '/') {
e.preventDefault();
$('#q')?.focus();
}
});
$('#btnShortcutsHelp')?.addEventListener('click', () => {
$('#shortcutsModal').hidden = false;
});
$('#btnCloseShortcuts')?.addEventListener('click', () => {
$('#shortcutsModal').hidden = true;
});
$('#shortcutsModal')?.addEventListener('click', e => {
if (e.target.id === 'shortcutsModal' || e.target.closest('#btnCloseShortcuts')) {
$('#shortcutsModal').hidden = true;
}
});
/* ── Export CSV Triggers ── */
$('#btnExportTickets')?.addEventListener('click',()=>{
const url=`/khira/api/tickets/export?status=${encodeURIComponent(S.st)}&priority=${encodeURIComponent(S.pr)}&assignee=${encodeURIComponent(S.fa)}&q=${encodeURIComponent(S.q)}`;
window.open(url,'_blank');
toast('Exporting tickets to CSV');
});
$('#btnExportErrors')?.addEventListener('click',()=>{
const url=`/khira/api/errors/export?status=${encodeURIComponent(S.ef)}&q=${encodeURIComponent(S.q)}`;
window.open(url,'_blank');
toast('Exporting errors to CSV');
});
/* ── Admin Database Sync & Rollback ── */
function adminSyncDB(){
dlg({
title:'Backup Primary Database',
sub:'Synchronizes all primary PostgreSQL records into the disaster backup vault.',
body:'<p>Are you sure you want to perform a manual backup synchronization now?</p>',
ok:'Sync Backup',
go:async()=>{
const r=await api('/khira/api/admin/db/sync','POST');
if(r._f||r.error){toast(r.error||'Backup sync failed','err');return false}
toast(r.message||'Primary DB successfully synced to Backup DB');
await refresh();
}
});
}
function adminRollbackDB(){
dlg({
title:'Rollback Primary Database',
sub:'Overwrites primary database records from the backup vault state.',
body:`<p style="color:var(--err);font-weight:500;margin-bottom:8px">${ic('warning',16)} WARNING: This will restore records from the backup state. Enter administrator password to confirm.</p>`+fld('password','Admin password',{t:'password',req:1}),
ok:'Execute Rollback',
go:async v=>{
const r=await api('/khira/api/admin/db/rollback','POST',v);
if(r._f||r.error){toast(r.error||'Rollback failed','err');return false}
toast(r.message||'Primary DB rolled back');
await refresh();
}
});
}
/* ── Profile & Avatar Selector ── */
function profile(){
const cur = S.u;
let curImgUrl = cur.profile_image || '';
let curType = curImgUrl ? 'image' : (cur.avatar_type || 'initials');
let curColor = cur.avatar_color || getUserColor(cur.username);
const getPreviewHtml = (imgUrl, color, name) => {
if (imgUrl) {
return `<div class="profile-avatar-wrap">
<img src="${esc(imgUrl)}" alt="${esc(name || cur.name || '')}" class="profile-avatar-img">
</div>`;
}
const inits = getInitials(name || cur.name || cur.username);
return `<div class="profile-avatar-wrap" style="background:${color};color:#ffffff">
<span class="profile-avatar-initials">${inits}</span>
</div>`;
};
const colors = [
{ name: 'Blue', hex: '#3b82f6' },
{ name: 'Emerald', hex: '#10b981' },
{ name: 'Indigo', hex: '#6366f1' },
{ name: 'Amber', hex: '#f59e0b' },
{ name: 'Rose', hex: '#f43f5e' },
{ name: 'Purple', hex: '#8b5cf6' },
{ name: 'Cyan', hex: '#06b6d4' },
{ name: 'Slate', hex: '#475569' }
];
dlg({
title: 'Account & Profile Settings',
sub: `@${cur.username} · ${cur.role_display}`,
wide: 1,
body: `
<div class="profile-card-hero">
<div id="profileAvatarPreview">${getPreviewHtml(curImgUrl, curColor, cur.name)}</div>
<div class="profile-hero-info">
<h4>${esc(cur.name || cur.username)}</h4>
<div class="profile-tags-row">
<span class="chip-role">${esc(cur.role_display)}</span>
<span class="mono" style="font-size:12px;color:var(--text-muted)">@${esc(cur.username)}</span>
</div>
<div class="profile-avatar-actions">
<input type="file" id="profileFileInput" accept="image/png,image/jpeg,image/webp" style="display:none">
<button type="button" class="action-chip primary" id="btnUploadPhoto">
${ic('upload', 14)} <span>Upload Photo</span>
</button>
<button type="button" class="action-chip" id="btnUseInitials">
${ic('refresh', 14)} <span>Use Initials</span>
</button>
</div>
</div>
</div>
<div class="profile-palette-section" id="initialsColorSection" ${curImgUrl ? 'hidden' : ''}>
<label class="section-micro-label">Initials Avatar Accent Color</label>
<div class="color-swatches-grid">
${colors.map(c => `
<button type="button" class="color-swatch-btn ${curColor === c.hex ? 'active' : ''}" data-color="${c.hex}" style="--swatch:${c.hex}" title="${c.name}"></button>
`).join('')}
</div>
</div>
<div class="profile-fields-grid">
<div class="profile-form-group">
<label>Full Name</label>
<input type="text" name="name" id="profNameInp" value="${esc(cur.name || '')}" placeholder="Your full name" required>
</div>
<div class="profile-form-group">
<label>Username</label>
<div class="input-with-lock">
<input type="text" value="@${esc(cur.username)}" readonly disabled>
<span class="lock-icon" title="Username cannot be altered">${ic('lock', 14)}</span>
</div>
</div>
<div class="profile-form-group">
<label>Role & Access Level</label>
<input type="text" value="${esc(cur.role_display)}" readonly disabled>
</div>
<div class="profile-form-group">
<label>Organization</label>
<input type="text" value="Khira Engineering & Telemetry" readonly disabled>
</div>
</div>
<div class="profile-security-accordion">
<div class="security-accordion-header" id="btnToggleSecurity">
<div style="display:flex;align-items:center;gap:8px">
${ic('lock', 16)}
<strong>Change Password</strong>
</div>
<span style="font-size:12px;color:var(--text-muted)">Optional</span>
</div>
<div class="security-accordion-body" id="securityBody" hidden>
<div class="profile-fields-grid" style="margin-top:12px">
<div class="profile-form-group" style="grid-column:1/-1">
<label>Current Password</label>
<input type="password" name="current_password" placeholder="Required to set a new password" autocomplete="current-password">
</div>
<div class="profile-form-group">
<label>New Password</label>
<input type="password" name="new_password" placeholder="Minimum 6 characters" autocomplete="new-password">
</div>
<div class="profile-form-group">
<label>Confirm New Password</label>
<input type="password" name="confirm_password" placeholder="Repeat new password" autocomplete="new-password">
</div>
</div>
</div>
</div>
<input type="hidden" name="profile_image" id="hidProfImg" value="${esc(curImgUrl)}">
<input type="hidden" name="avatar_color" id="hidProfColor" value="${esc(curColor)}">
<input type="hidden" name="avatar_type" id="hidProfType" value="${esc(curType)}">
`,
ok: 'Save Changes',
alt: ['Sign out', async () => {
await api('/khira/api/auth/logout', 'POST');
localStorage.removeItem('khira_session_token');
localStorage.removeItem('khira_active_user');
location.reload();
}],
init: f => {
const prev = f.querySelector('#profileAvatarPreview');
const fileInp = f.querySelector('#profileFileInput');
const btnUp = f.querySelector('#btnUploadPhoto');
const btnInits = f.querySelector('#btnUseInitials');
const hidImg = f.querySelector('#hidProfImg');
const hidColor = f.querySelector('#hidProfColor');
const hidType = f.querySelector('#hidProfType');
const nameInp = f.querySelector('#profNameInp');
const colorSec = f.querySelector('#initialsColorSection');
const refreshPreview = () => {
prev.innerHTML = getPreviewHtml(curImgUrl, curColor, nameInp.value);
colorSec.hidden = !!curImgUrl;
};
nameInp.addEventListener('input', refreshPreview);
btnUp.onclick = () => fileInp.click();
btnInits.onclick = () => {
curImgUrl = '';
curType = 'initials';
hidImg.value = '';
hidType.value = 'initials';
refreshPreview();
toast('Switched to initials avatar');
};
f.querySelectorAll('.color-swatch-btn').forEach(b => {
b.onclick = () => {
f.querySelectorAll('.color-swatch-btn').forEach(btn => btn.classList.remove('active'));
b.classList.add('active');
curColor = b.dataset.color;
hidColor.value = curColor;
refreshPreview();
};
});
fileInp.onchange = async () => {
const file = fileInp.files[0];
if (!file) return;
const fd = new FormData();
fd.append('file', file);
try {
toast('Uploading avatar photo...');
const un = S.u?.username || ls('khira_active_user');
const tok = ls('khira_session_token');
const upHeaders = { 'X-Khira-User': un };
if (tok) upHeaders['Authorization'] = 'Bearer ' + tok;
const upRes = await fetch('/khira/api/upload', {
method: 'POST',
headers: upHeaders,
credentials: 'same-origin',
body: fd
});
const upJson = await upRes.json();
const url = upJson.url || upJson.attachment?.url;
if (url) {
curImgUrl = url;
curType = 'image';
hidImg.value = url;
hidType.value = 'image';
refreshPreview();
toast('Avatar uploaded successfully');
} else {
toast(upJson.error || 'Failed to upload image', 'err');
}
} catch (err) {
toast('Failed to upload image', 'err');
}
};
// Toggle Security accordion
const toggleBtn = f.querySelector('#btnToggleSecurity');
const secBody = f.querySelector('#securityBody');
toggleBtn.onclick = () => {
secBody.hidden = !secBody.hidden;
};
},
go: async v => {
// Validate password if supplied
if (v.new_password) {
if (!v.current_password) {
toast('Please enter your current password to set a new password', 'err');
return false;
}
if (v.new_password.length < 6) {
toast('New password must be at least 6 characters', 'err');
return false;
}
if (v.new_password !== v.confirm_password) {
toast('New passwords do not match', 'err');
return false;
}
}
const payload = {
name: v.name,
avatar_type: v.avatar_type || curType,
avatar: cur.avatar || '👤',
profile_image: v.profile_image
};
if (v.new_password) {
payload.current_password = v.current_password;
payload.new_password = v.new_password;
}
const r = await api('/khira/api/auth/profile', 'PUT', payload);
if (r._f) {
toast(r.error || 'Failed to update profile', 'err');
return false;
}
S.u = r.user || { ...S.u, ...payload };
updateMe(S.u);
toast('Profile updated successfully');
await refresh();
}
});
}
function pop(){
const p=$('#pop');
if(!p.hidden){p.hidden=true;return}
const unread=S.n.filter(x=>!x.read);
p.innerHTML=`<div class="pop-h"><h4>Notifications</h4><button class="tb" data-d="readall">Mark all read</button></div>${S.n.length?S.n.map(x=>`<div class="ni${x.read?'':' un'}" data-n="${esc(x.ticket_id)}" data-nid="${esc(x.id)}"><p><b>${esc(x.title)}</b> · <small>${ago(x.created_at)}</small></p><p class="sub">${esc(x.message)}</p></div>`).join(''):'<div class="emp">No notifications</div>'}`;
p.hidden=false;
}
function theme(t){
document.documentElement.dataset.theme=t;
try{localStorage.khira_theme=t}catch(e){}
const tc=t==='dark'?'#06080c':'#f5f5f7';
$('#tc').content=tc;
if($('#themeIcon'))$('#themeIcon').innerHTML=t==='dark'?ICONS.moon:ICONS.sun;
}
/* ── Global Event Delegation ── */
document.addEventListener('click',async e=>{
let x;const c=s=>e.target.closest(s);
// Card click (open sheet or toggle checkbox in bulk mode)
if(x=c('.card-check')){
e.stopPropagation();
const tid=x.dataset.tid;
if(x.checked)S.bulkSelected.add(tid);
else S.bulkSelected.delete(tid);
updateBulkBar();
return;
}
if(x=c('[data-t]')){
if(S.bulkMode){
const tid=x.dataset.t;
if(S.bulkSelected.has(tid))S.bulkSelected.delete(tid);
else S.bulkSelected.add(tid);
updateBulkBar();
render(false);
return;
}
return sheet(x.dataset.t);
}
if(x=c('[data-e]'))return errD(x.dataset.e);
// Nav buttons
if(x=c('.nav button'))return nav(x.dataset.s);
// Admin tabs
if(x=c('#adminTabs button')){
$$('#adminTabs button').forEach(b=>b.classList.remove('on'));
x.classList.add('on');
$$('.admin-tab-pane').forEach(p=>p.hidden=true);
const at=x.dataset.at;
if(at==='users'){ $('#adminTabUsers').hidden=false; loadAdminUsers(); }
else if(at==='tokens'){ $('#adminTabTokens').hidden=false; loadAdminTokens(); }
else if(at==='database'){ $('#adminTabDatabase').hidden=false; loadAdminDatabase(); }
return;
}
// View switchers & filters
if(x=c('#vsw button')){S.view=x.dataset.v;return renderT(true)}
if(x=c('[data-sc]')){S.scope=x.dataset.sc;return renderT(true)}
if(x=c('[data-st]')){S.st=x.dataset.st;return renderT(true)}
if(x=c('[data-ef]')){S.ef=x.dataset.ef;return renderE(true)}
// Saved filters
if(x=c('[data-delfid]')){
const fid=x.dataset.delfid;
if(confirm('Delete this saved view?')){
api(`/khira/api/filters/${encodeURIComponent(fid)}`,'DELETE').then(r=>{
if(r._f)toast(r.error||'Failed to delete view','err');
else{toast('Saved view deleted');loadSavedFilters();}
});
}
return;
}
if(x=c('[data-fid]')){
const fid=x.dataset.fid;
const sf=(S.savedFilters||[]).find(it=>it.id===fid);
if(sf){
try{
const cfg=JSON.parse(sf.filter_json);
if(cfg.scope!==undefined)S.scope=cfg.scope;
if(cfg.st!==undefined)S.st=cfg.st;
if(cfg.pr!==undefined)S.pr=cfg.pr;
if(cfg.ty!==undefined)S.ty=cfg.ty;
if(cfg.fa!==undefined)S.fa=cfg.fa;
if(cfg.q!==undefined){S.q=cfg.q;const qEl=$('#q');if(qEl)qEl.value=cfg.q;}
const fpEl=$('#fp');if(fpEl)fpEl.value=S.pr;
const ftEl=$('#ft');if(ftEl)ftEl.value=S.ty;
const faEl=$('#fa');if(faEl)faEl.value=S.fa;
toast(`Applied view: ${sf.name}`);
renderT(true);
}catch(err){toast('Corrupt filter configuration','err');}
}
return;
}
if(c('#btnSaveFilter')){
const defName=(S.pr?S.pr+' ':'')+(S.ty?S.ty+' ':'')+'View';
const name=prompt('Enter a name for this saved view:',defName);
if(name&&name.trim()){
const filterJSON=JSON.stringify({scope:S.scope,st:S.st,pr:S.pr,ty:S.ty,fa:S.fa,q:S.q});
api('/khira/api/filters','POST',{name:name.trim(),filter_json:filterJSON}).then(r=>{
if(r._f)toast(r.error||'Failed to save view','err');
else{toast('View saved successfully');loadSavedFilters();}
});
}
return;
}
// Database tools
if(c('#btnSyncBackup'))return adminSyncDB();
if(c('#btnRollbackBackup'))return adminRollbackDB();
// Close modals & sheets
if(x=c('[data-x]')){
const dlgEl=x.closest('dialog');
if(dlgEl)dlgEl.close();
return;
}
// Ticket actions inside sheet
if(x=c('[data-do]')){
const a=x.dataset.do;
if(a==='del')return deleteTicketD(S.tid);
if(a==='hold')return holdD();
if(a==='resume')return act('resume',{},'Ticket resumed');
if(a==='done')return doneD();
if(a==='archive')return act('archive',{},'Ticket archived');
if(a==='unarchive')return act('unarchive',{},'Ticket restored');
}
// Notifications popup
if(x=c('#pop [data-d]')){
const d=x.dataset.d;
if(d==='readall'){await api('/khira/api/notifications/read','POST');await refresh();toast('All marked read');$('#pop').hidden=true}
return;
}
if(x=c('[data-n]')){
$('#pop').hidden=true;
if(x.dataset.nid){
api(`/khira/api/notifications/${encodeURIComponent(x.dataset.nid)}/read`,'POST').then(()=>refresh(false));
}
if(x.dataset.n)sheet(x.dataset.n);
return;
}
if(c('[data-copy]'))return navigator.clipboard.writeText($('#ctx').textContent).then(()=>toast('Copied'));
if(c('#btnSidebarCreate'))return S.sec==='tickets'?newTicket():reportErr();
if(c('#btnLogout')){
await api('/khira/api/auth/logout','POST');
ls('khira_session_token','');
ls('khira_active_user','');
boot();
toast('Signed out');
return;
}
if(c('#btnMobileNav')){
$('#sidebar')?.classList.toggle('mobile-open');
return;
}
if(x=c('[data-col-add]')){
newTicket();
return;
}
if(x=c('#btnSheetCopyLink')||(x=c('[data-copy-ref]'))){
const ref = x.dataset.copyRef || S.tid || '';
if(ref)navigator.clipboard.writeText(ref).then(()=>toast(`Reference ${ref} copied`));
return;
}
if(x=c('[data-jump-err]')){
const errId = x.dataset.jumpErr;
nav('errors');
S.q = errId.toLowerCase();
const qEl = $('#q');
if (qEl) qEl.value = errId;
renderE(true);
return;
}
if(c('#btnLogAppErr'))return reportErr({continue_app:true});
if(c('#fab'))return S.sec==='tickets'?newTicket():reportErr();
if(c('#bell'))return pop();
if(c('#me'))return profile();
if(c('#theme'))return theme(document.documentElement.dataset.theme==='dark'?'light':'dark');
});
document.addEventListener('change',e=>{
const t=e.target;
if(t.id==='fp'){S.pr=t.value;renderT(true)}
if(t.id==='ft'){S.ty=t.value;renderT(true)}
if(t.id==='fa'){S.fa=t.value;renderT(true)}
if(t.dataset.act==='assign')act('reassign',{assignee:t.value},'Reassigned');
if(t.dataset.act==='prio')act('priority',{priority:t.value},'Priority updated');
});
let searchDebounceTimer = null;
document.addEventListener('input',e=>{
if(e.target.id==='q'){
clearTimeout(searchDebounceTimer);
searchDebounceTimer = setTimeout(() => {
S.q = e.target.value.trim().toLowerCase();
render(false);
}, 200);
}
});
document.addEventListener('submit',e=>{
if(e.target.id==='rf'){e.preventDefault();remark()}
});
/* ── Cloudflare Turnstile Integration ── */
let turnstileSiteKey = '';
let turnstileInWidgetId = null;
let turnstileUpWidgetId = null;
let turnstileInToken = '';
let turnstileUpToken = '';
async function setupTurnstile() {
try {
const res = await api('/khira/api/auth/turnstile-config');
if (res && res.site_key) {
turnstileSiteKey = res.site_key;
renderTurnstileWidgets();
}
} catch(e) {}
}
function renderTurnstileWidgets() {
if (!window.turnstile || !turnstileSiteKey) {
setTimeout(renderTurnstileWidgets, 300);
return;
}
const elIn = document.getElementById('turnstileWidgetIn');
if (elIn && turnstileInWidgetId === null) {
try {
turnstileInWidgetId = window.turnstile.render(elIn, {
sitekey: turnstileSiteKey,
theme: 'dark',
callback: tok => { turnstileInToken = tok; },
'expired-callback': () => { turnstileInToken = ''; }
});
} catch(e) {}
}
const elUp = document.getElementById('turnstileWidgetUp');
if (elUp && turnstileUpWidgetId === null) {
try {
turnstileUpWidgetId = window.turnstile.render(elUp, {
sitekey: turnstileSiteKey,
theme: 'dark',
callback: tok => { turnstileUpToken = tok; },
'expired-callback': () => { turnstileUpToken = ''; }
});
} catch(e) {}
}
}
/* ── Auth System ── */
$('#atabs')?.addEventListener('click',e=>{
const b=e.target.closest('button');if(!b)return;
$$('#atabs button').forEach(x=>x.classList.remove('on'));b.classList.add('on');
$('#fIn').hidden=b.dataset.a!=='in';$('#fUp').hidden=b.dataset.a!=='up';
});
$('#fIn')?.addEventListener('submit',async e=>{
e.preventDefault();if(!chk($('#fIn')))return;
const u=$('#lu').value.trim(),p=$('#lp').value;
const r=await api('/khira/api/auth/login','POST',{
username:u,
password:p,
turnstile_token:turnstileInToken
});
if(r._f){
toast(r.error||'Sign in failed','err');
if(window.turnstile && turnstileInWidgetId !== null){
try{window.turnstile.reset(turnstileInWidgetId);turnstileInToken='';}catch(e){}
}
return;
}
if(r.token){try{localStorage.khira_session_token=r.token}catch(e){}}
try{localStorage.khira_active_user=r.user.username}catch(e){}
boot(r.user);
});
$('#fUp')?.addEventListener('submit',async e=>{
e.preventDefault();if(!chk($('#fUp')))return;
const r=await api('/khira/api/auth/register','POST',{
name:$('#rn').value.trim(),
username:$('#ru').value.trim(),
password:$('#rp').value,
role:$('#rr').value,
turnstile_token:turnstileUpToken
});
if(r._f){
toast(r.error||'Registration failed','err');
if(window.turnstile && turnstileUpWidgetId !== null){
try{window.turnstile.reset(turnstileUpWidgetId);turnstileUpToken='';}catch(e){}
}
return;
}
if(r.token){try{localStorage.khira_session_token=r.token}catch(e){}}
try{localStorage.khira_active_user=r.user.username}catch(e){}
boot(r.user);
});
$$('.demo button, .demo-chips button').forEach(b=>{
b.onclick=async()=>{
const uname = b.dataset.d;
const pass = uname + '123';
$('#lu').value = uname;
$('#lp').value = pass;
const r = await api('/khira/api/auth/login','POST',{username:uname, password:pass});
if(r._f){toast(r.error||'Demo sign in failed','err');return}
if(r.token){try{localStorage.khira_session_token=r.token}catch(e){}}
try{localStorage.khira_active_user=r.user.username}catch(e){}
boot(r.user);
};
});
$('#btnForgot')?.addEventListener('click',()=>{
dlg({
title:'Reset Password',
sub:'Creates an urgent ticket for administrator to reset your credentials.',
body:fld('username','Your username',{req:1})+fld('reason','Reason / details',{t:'area',rows:3,v:'Forgot my password, please reset.'}),
ok:'Raise Ticket to Admin',
go:async v=>{
const r=await api('/khira/api/auth/forgot-password','POST',v);
if(r._f||r.error){toast(r.error||'Could not raise ticket','err');return false}
toast(r.message||'Password reset ticket raised to administrator');
}
});
});
/* ── Realtime SSE Engine ── */
let sseSource = null;
let sseReconnectTimer = null;
function updateLiveStatus(online) {
const pill = $('#livePill');
if (!pill) return;
pill.classList.toggle('online', !!online);
pill.classList.toggle('offline', !online);
const lbl = pill.querySelector('.live-lbl');
if (lbl) lbl.textContent = online ? 'Live' : 'Reconnecting...';
}
function initRealtime() {
if (sseSource) {
try { sseSource.close(); } catch(e) {}
sseSource = null;
}
const un = S.u?.username || ls('khira_active_user');
const url = un ? `/khira/api/events?u=${encodeURIComponent(un)}` : '/khira/api/events';
sseSource = new EventSource(url);
sseSource.addEventListener('connected', () => {
updateLiveStatus(true);
});
sseSource.addEventListener('message', async (e) => {
try {
const evt = JSON.parse(e.data);
handleRealtimeEvent(evt);
} catch(err) {
console.warn('Realtime event parse error', err);
}
});
sseSource.onerror = () => {
updateLiveStatus(false);
if (sseSource && sseSource.readyState === EventSource.CLOSED) {
clearTimeout(sseReconnectTimer);
sseReconnectTimer = setTimeout(initRealtime, 3000);
}
};
}
async function handleRealtimeEvent(evt) {
const tId = evt.ticket_id;
// 1. Refresh background datasets silently without layout flicker
await refresh(false);
// 2. If the user currently has the affected ticket sheet open:
if (S.tid && tId && S.tid === tId && $('#sheet')?.open) {
sheet(S.tid);
}
// 3. Subtle visual highlight on affected card
if (tId) {
const card = document.querySelector(`.card[data-t="${tId}"]`);
if (card) {
card.classList.add('live-flash');
setTimeout(() => card.classList.remove('live-flash'), 1200);
}
}
}
/* ── App Initialization ── */
async function boot(u){
if (!u) {
S.u = null;
$('#app').hidden = true;
$('#auth').hidden = false;
setupTurnstile();
clearInterval(pollId);
return;
}
S.u=u;
$('#auth').hidden=true;
$('#app').hidden=false;
updateMe(u);
initRealtime();
await refresh(true);
clearInterval(pollId);
pollId=setInterval(()=>refresh(false),30000);
}
(async function init(){
const me=await api('/khira/api/auth/me');
if(!me._f&&me.user){
boot(me.user);
}else{
$('#auth').hidden=false;
$('#app').hidden=true;
setupTurnstile();
}
})();
/* ── Khira v12 visual enhancer (UI only — no API or state access) ── */
(function(){
'use strict';
const fine=matchMedia('(pointer:fine)').matches,calm=matchMedia('(prefers-reduced-motion:reduce)').matches;
if(fine&&!calm){
let raf=0;
document.addEventListener('pointermove',e=>{
if(raf)return;
raf=requestAnimationFrame(()=>{
raf=0;
const el=e.target.closest&&e.target.closest('.tile,.card,.analytics-card');
if(!el)return;
const r=el.getBoundingClientRect();
el.style.setProperty('--mx',(e.clientX-r.left)+'px');
el.style.setProperty('--my',(e.clientY-r.top)+'px');
});
},{passive:true});
}
/* Count-up on stat tiles when their numbers change */
const last=new WeakMap();
function countUp(root){
root.querySelectorAll('.tile strong').forEach(el=>{
const to=parseInt(el.textContent,10);
if(isNaN(to))return;
const key=el.closest('.tile')?.dataset.k||'';
const from=last.get(root)?.[key]??0;
const map=last.get(root)||{};map[key]=to;last.set(root,map);
if(calm||from===to){el.textContent=to;return}
const t0=performance.now(),d=650;
const step=n=>{
const p=Math.min(1,(n-t0)/d),k=1-Math.pow(1-p,4);
el.textContent=Math.round(from+(to-from)*k);
if(p<1)requestAnimationFrame(step);
};
requestAnimationFrame(step);
});
}
['stats','estats','astats'].forEach(id=>{
const el=document.getElementById(id);
if(!el)return;
new MutationObserver(()=>countUp(el)).observe(el,{childList:true});
});
})();
/* ── Sidebar collapse toggle (UI only; remembers choice) ── */
(function(){
'use strict';
const app=document.getElementById('app'),aside=document.getElementById('sidebar');
if(!app||!aside)return;
let min=false;try{min=localStorage.getItem('khira_dock')==='min'}catch(e){}
const btn=document.createElement('button');
btn.type='button';btn.className='dock-toggle';
btn.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>';
const sync=()=>{app.classList.toggle('dock-min',min);btn.setAttribute('aria-label',min?'Expand sidebar':'Collapse sidebar');btn.title=min?'Expand sidebar':'Collapse sidebar'};
btn.onclick=()=>{min=!min;try{localStorage.setItem('khira_dock',min?'min':'full')}catch(e){}sync()};
aside.appendChild(btn);sync();
})();