dealspace/portal/templates/app/project.html

844 lines
42 KiB
HTML

{{define "header-left"}}
<div class="flex items-center gap-3">
<a href="/app/projects" class="text-xl font-bold text-white tracking-tight"><span class="text-[#c9a84c]">Deal</span>space</a>
<span class="text-white/20">/</span>
<a href="/app/projects" class="text-sm text-[#94a3b8] hover:text-white transition">Projects</a>
<span class="text-white/20">/</span>
<span id="projectName" class="text-sm text-white font-medium">Loading...</span>
</div>
{{end}}
{{define "content"}}
<div class="p-8" style="max-width:calc(100vw - 14rem)">
<!-- Header -->
<div class="flex items-start justify-between mb-6">
<div>
<div class="flex items-center gap-3 mb-1">
<h1 id="projectTitle" class="text-2xl font-bold text-white">Loading...</h1>
<span id="projectStatus" class="px-2.5 py-0.5 rounded-full text-xs font-medium"></span>
</div>
<p id="projectDesc" class="text-[#94a3b8] text-sm"></p>
</div>
<div class="flex gap-2">
<button onclick="openImportModal()" class="px-4 py-2 bg-white/[0.05] hover:bg-white/[0.08] text-white rounded-lg text-sm transition flex items-center gap-2">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/></svg>
Import
</button>
</div>
</div>
<!-- Tabs -->
<div class="flex gap-6 border-b border-white/[0.08] mb-6">
<button class="tab active pb-3 text-sm font-medium transition" onclick="switchTab('requests', this)">Requests</button>
<button class="tab pb-3 text-sm font-medium text-[#94a3b8] transition" onclick="switchTab('orgs', this)">Organizations</button>
</div>
<!-- Requests Tab -->
<div id="tab-requests">
<div id="requestEmpty" class="hidden text-center py-16">
<h3 class="text-lg font-semibold text-white mb-1">No requests yet</h3>
<p class="text-[#94a3b8] text-sm mb-4">Import a diligence checklist to get started.</p>
<button onclick="openImportModal()" class="px-4 py-2 bg-[#c9a84c] hover:bg-[#b8973f] text-[#0a1628] font-semibold rounded-lg text-sm transition">Import Checklist</button>
</div>
<div id="treeWrap" class="overflow-x-auto">
<div class="flex items-center gap-2 mb-3">
<button id="detailToggle" onclick="toggleDetailMode()" class="px-3 py-1.5 bg-white/[0.05] hover:bg-white/[0.08] text-[#94a3b8] hover:text-white rounded-lg text-xs font-medium transition">Summary</button>
</div>
<table id="reqTree">
<thead>
<tr>
<th style="width:28px" title="Drag to reorder"></th>
<th style="width:60px">#</th>
<th style="min-width:280px">Request Item</th>
<th style="width:80px">Priority</th>
<th style="width:90px">Status</th>
<th style="width:120px">Assignee</th>
<th style="width:90px">Due Date</th>
<th style="width:90px">Label</th>
<th style="width:50px">Files</th>
<th style="width:160px">Buyer Comment</th>
<th style="width:160px">Seller Comment</th>
<th style="width:90px">Created</th>
<th style="width:40px"></th>
</tr>
</thead>
<tbody id="treeBody">
<tr><td colspan="13" class="text-[#94a3b8] text-sm py-4">Loading requests...</td></tr>
</tbody>
</table>
</div>
</div>
<!-- Orgs Tab -->
<div id="tab-orgs" class="hidden">
<div class="flex justify-between items-center mb-4">
<p class="text-[#94a3b8] text-sm">Organizations and team members in this deal.</p>
<button id="addOrgBtn" class="px-3 py-1.5 bg-white/[0.05] hover:bg-white/[0.08] text-white rounded-lg text-sm transition">+ Add Org</button>
</div>
<div id="orgList" class="space-y-3"><div class="text-[#94a3b8] text-sm">Loading...</div></div>
<div id="teamMembersSection"></div>
</div>
</div>
<!-- Import Modal -->
<div id="importModal" style="display:none" class="fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4">
<div class="bg-[#0d1f3c] border border-white/[0.08] rounded-xl p-8 w-full max-w-md">
<h2 class="text-xl font-semibold text-white mb-6">Import Diligence Checklist</h2>
<div id="importError" class="hidden mb-4 p-3 bg-red-500/10 border border-red-500/20 rounded-lg text-red-400 text-sm"></div>
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-[#94a3b8] mb-1.5">Request List Name</label>
<input type="text" id="importListName" placeholder="e.g. Blackstone DDQ, General Checklist"
class="w-full px-4 py-2.5 bg-[#0a1628] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c] focus:ring-1 focus:ring-[#c9a84c]">
</div>
<div>
<label class="block text-sm font-medium text-[#94a3b8] mb-1.5">File (CSV or XLSX)</label>
<input type="file" id="importFile" accept=".csv,.xlsx,.xls" required
class="w-full px-4 py-2.5 bg-[#0a1628] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c] focus:ring-1 focus:ring-[#c9a84c]">
</div>
<div>
<label class="block text-sm font-medium text-[#94a3b8] mb-1.5">Import Mode</label>
<select id="importMode" class="w-full px-4 py-2.5 bg-[#0a1628] border border-white/[0.08] rounded-lg text-white focus:outline-none focus:border-[#c9a84c]">
<option value="add">Add new request list</option>
<option value="replace">Replace all request lists</option>
</select>
</div>
<div>
<label class="block text-sm font-medium text-[#94a3b8] mb-1.5">Visible to</label>
<select id="importVisibility" class="w-full px-4 py-2.5 bg-[#0a1628] border border-white/[0.08] rounded-lg text-white focus:outline-none focus:border-[#c9a84c]">
<option value="">Everyone (General List)</option>
</select>
</div>
</div>
<div class="flex gap-3 mt-6">
<button onclick="closeImportModal()" class="flex-1 py-2.5 bg-white/[0.05] hover:bg-white/[0.08] text-white rounded-lg text-sm font-medium transition">Cancel</button>
<button id="importBtn" onclick="submitImport()" class="flex-1 py-2.5 bg-[#c9a84c] hover:bg-[#b8973f] text-[#0a1628] font-semibold rounded-lg text-sm transition">Import</button>
</div>
</div>
</div>
<!-- Attach Answer Modal -->
<div id="attachModal" style="display:none" class="fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4">
<div class="bg-[#0d1f3c] border border-white/[0.08] rounded-xl p-8 w-full max-w-lg">
<h2 class="text-xl font-semibold text-white mb-2">Attach Answer Document</h2>
<p id="attachReqTitle" class="text-[#94a3b8] text-sm mb-4"></p>
<div class="mb-4">
<input type="text" id="attachSearch" placeholder="Search existing documents..."
class="w-full px-4 py-2.5 bg-[#0a1628] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c]"
oninput="searchAnswers(this.value)">
</div>
<div id="attachList" class="max-h-64 overflow-y-auto space-y-1 mb-4"></div>
<div class="border-t border-white/[0.08] pt-4">
<label class="block text-sm font-medium text-[#94a3b8] mb-1.5">Or upload new document</label>
<input type="file" id="attachFile" class="w-full px-4 py-2.5 bg-[#0a1628] border border-white/[0.08] rounded-lg text-white text-sm">
</div>
<div class="flex gap-3 mt-4">
<button onclick="closeAttachModal()" class="flex-1 py-2.5 bg-white/[0.05] hover:bg-white/[0.08] text-white rounded-lg text-sm font-medium transition">Cancel</button>
<button onclick="uploadAndLink()" class="flex-1 py-2.5 bg-[#c9a84c] hover:bg-[#b8973f] text-[#0a1628] font-semibold rounded-lg text-sm transition">Upload &amp; Link</button>
</div>
</div>
</div>
{{end}}
{{define "scripts"}}
<script>
const projectID = location.pathname.split('/').pop();
function fmtDate(ms) { if (!ms) return ''; const d = new Date(ms); return d.toLocaleDateString('en-US', {month:'short',day:'numeric'}); }
// Badge helpers
const priStyles = { critical:'background:rgba(239,68,68,.15);color:#f87171', high:'background:rgba(251,146,60,.15);color:#fb923c', medium:'background:rgba(250,204,21,.15);color:#facc15', low:'background:rgba(148,163,184,.15);color:#94a3b8' };
const statStyles = { open:'background:rgba(96,165,250,.15);color:#60a5fa', in_process:'background:rgba(251,191,36,.15);color:#fbbf24', partial:'background:rgba(168,85,247,.15);color:#a855f7', complete:'background:rgba(74,222,128,.15);color:#4ade80' };
const statLabels = { open:'Open', in_process:'In Process', partial:'Partial', complete:'Complete' };
function priorityBadge(p) {
return `<span class="badge" style="${priStyles[p]||priStyles.medium}">${escHtml(p||'medium')}</span>`;
}
function statusBadge(s) {
return `<span class="badge" style="${statStyles[s]||statStyles.open}">${statLabels[s]||escHtml(s||'open')}</span>`;
}
function labelPill(label) {
if (!label) return '';
const colors = [
{bg:'rgba(96,165,250,.15)',fg:'#60a5fa'},{bg:'rgba(244,114,182,.15)',fg:'#f472b6'},
{bg:'rgba(167,139,250,.15)',fg:'#a78bfa'},{bg:'rgba(251,146,60,.15)',fg:'#fb923c'},
{bg:'rgba(74,222,128,.15)',fg:'#4ade80'},{bg:'rgba(250,204,21,.15)',fg:'#facc15'}
];
let hash = 0;
for (let i = 0; i < label.length; i++) hash = ((hash << 5) - hash) + label.charCodeAt(i);
const c = colors[Math.abs(hash) % colors.length];
return `<span style="display:inline-block;padding:1px 8px;border-radius:9999px;font-size:11px;background:${c.bg};color:${c.fg}">${escHtml(label)}</span>`;
}
function fmtDueDate(v) {
if (!v) return '\u2014';
if (typeof v === 'number') return fmtDate(v);
return escHtml(String(v));
}
const statusColors = { active: 'bg-green-500/20 text-green-300', draft: 'bg-gray-500/20 text-gray-300', closed: 'bg-red-500/20 text-red-300' };
const roleColors = { seller: 'bg-blue-500/20 text-blue-300', buyer: 'bg-green-500/20 text-green-300', ib: 'bg-[#c9a84c]/20 text-[#c9a84c]', advisor: 'bg-purple-500/20 text-purple-300' };
// ---- State ----
let treeData = [];
let collapsed = new Set();
let numberMap = {};
let openMenuId = null;
let attachRequestId = null;
let detailMode = false;
// ---- Detail toggle ----
function toggleDetailMode() {
detailMode = !detailMode;
document.getElementById('detailToggle').textContent = detailMode ? 'Full' : 'Summary';
renderTree();
}
// ---- Project loading ----
async function loadProject() {
try {
const res = await fetchAPI('/api/projects/' + projectID);
if (!res.ok) { document.getElementById('projectTitle').textContent = 'Not found'; return; }
const raw = await res.json();
const p = raw.project || raw;
const d = parseData(p.data_text);
const name = d.name || p.summary_text || p.summary || 'Untitled';
document.title = name + ' — Dealspace';
document.getElementById('projectName').textContent = name;
document.getElementById('projectTitle').textContent = name;
document.getElementById('projectDesc').textContent = d.description || '';
const status = d.status || 'active';
const sc = statusColors[status] || 'bg-gray-500/20 text-gray-300';
document.getElementById('projectStatus').className = 'px-2.5 py-0.5 rounded-full text-xs font-medium capitalize ' + sc;
document.getElementById('projectStatus').textContent = status;
} catch(e) {}
}
// ---- Tree loading ----
async function loadRequestTree() {
try {
const res = await fetchAPI('/api/projects/' + projectID + '/requests/tree');
treeData = await res.json();
if (!treeData || treeData.length === 0) {
document.getElementById('requestEmpty').classList.remove('hidden');
document.getElementById('treeWrap').classList.add('hidden');
return;
}
document.getElementById('requestEmpty').classList.add('hidden');
document.getElementById('treeWrap').classList.remove('hidden');
buildNumbering();
renderTree();
} catch(e) {
document.getElementById('treeBody').innerHTML = '<tr><td colspan="13" class="text-red-400 text-sm py-4">Failed to load requests.</td></tr>';
}
}
// Build hierarchical numbering (1, 1.1, 1.1.1, etc.)
function buildNumbering() {
numberMap = {};
const childrenOf = {};
for (const item of treeData) {
if (!childrenOf[item.parent_id]) childrenOf[item.parent_id] = [];
childrenOf[item.parent_id].push(item.entry_id);
}
const counters = {};
for (const item of treeData) {
if (!counters[item.parent_id]) counters[item.parent_id] = 0;
counters[item.parent_id]++;
const parentNum = numberMap[item.parent_id];
if (item.type === 'request_list') {
numberMap[item.entry_id] = '' + counters[item.parent_id];
} else {
numberMap[item.entry_id] = (parentNum ? parentNum + '.' : '') + counters[item.parent_id];
}
}
}
// Check if an item or any ancestor is collapsed
function isHidden(item) {
const parentMap = {};
for (const t of treeData) parentMap[t.entry_id] = t.parent_id;
let pid = item.parent_id;
while (pid && pid !== projectID) {
if (collapsed.has(pid)) return true;
pid = parentMap[pid];
}
return false;
}
function renderTree() {
const tbody = document.getElementById('treeBody');
let html = '';
for (const item of treeData) {
if (isHidden(item)) continue;
const d = item.data || {};
const num = numberMap[item.entry_id] || '';
const indent = Math.max(0, item.depth - 1) * 20;
const isCollapsible = item.type === 'request_list' || item.type === 'section';
const isCollapsed = collapsed.has(item.entry_id);
const chevron = isCollapsible
? `<span class="collapse-btn ${isCollapsed?'collapsed':''}" onclick="toggleCollapse('${item.entry_id}')">\u25BC</span>`
: '';
if (item.type === 'request_list') {
const name = d.name || 'Request List';
const childCount = item.children_count || 0;
const visOrgId = d.visibility_org_id || '';
const visBadge = visOrgId
? `<span style="display:inline-block;padding:1px 8px;border-radius:9999px;font-size:10px;background:rgba(251,146,60,.15);color:#fb923c;margin-left:8px">Restricted</span>`
: `<span style="display:inline-block;padding:1px 8px;border-radius:9999px;font-size:10px;background:rgba(74,222,128,.12);color:#4ade80;margin-left:8px">All</span>`;
html += `<tr class="row-list" data-id="${item.entry_id}" data-type="${item.type}" data-parent="${item.parent_id}" data-depth="${item.depth}">
<td></td>
<td colspan="12" style="padding-left:${indent+10}px">
${chevron}
<strong style="color:var(--ds-tx);margin-left:4px">${escHtml(name)}</strong>
${visBadge}
<span style="color:var(--ds-tx3);margin-left:8px;font-size:11px">${childCount} items</span>
<button onclick="editVisibility('${item.entry_id}')" style="margin-left:6px;background:none;border:none;cursor:pointer;color:var(--ds-tx3);font-size:11px;padding:1px 4px" title="Change visibility">&#9881;</button>
</td>
</tr>`;
} else if (item.type === 'section') {
const name = d.name || d.title || 'Section';
html += `<tr class="row-section" data-id="${item.entry_id}" data-type="${item.type}" data-parent="${item.parent_id}" data-depth="${item.depth}"
draggable="true" ondragstart="onDragStart(event)" ondragover="onDragOver(event)" ondragleave="onDragLeave(event)" ondrop="onDrop(event)">
<td class="drag-handle" style="color:var(--ds-tx3);font-size:11px;cursor:grab">\u2630</td>
<td class="row-num" style="padding-left:${indent}px">${escHtml(num)}</td>
<td colspan="11" style="padding-left:${indent}px">
${chevron}
<span style="color:var(--ds-tx);font-weight:600;margin-left:4px">${escHtml(name)}</span>
<span style="color:var(--ds-tx3);margin-left:8px;font-size:11px">${item.children_count||0} requests</span>
</td>
</tr>`;
} else {
// request row
const title = d.title || d.description || 'Untitled';
const buyerComment = d.buyer_comment || '';
const sellerComment = d.seller_comment || '';
const assignee = d.assignee || d.assigned_to || '';
const dueDate = d.due_date || d.completed_date || '';
const label = d.label || '';
const curPri = d.priority || 'medium';
const curStat = d.status || 'open';
const eid = item.entry_id;
// Title with detail mode
let titleHtml;
if (detailMode) {
titleHtml = `<a href="/app/requests/${eid}" style="color:var(--ds-tx);text-decoration:none" class="hover:underline">${escHtml(title)}</a>`;
if (d.description) {
const descTrunc = d.description.length > 120 ? d.description.substring(0, 120) + '\u2026' : d.description;
titleHtml += `<div style="color:var(--ds-tx3);font-size:12px;margin-top:2px">${escHtml(descTrunc)}</div>`;
}
} else {
const titleTrunc = title.length > 80 ? title.substring(0, 80) + '\u2026' : title;
titleHtml = `<a href="/app/requests/${eid}" style="color:var(--ds-tx);text-decoration:none" class="hover:underline">${escHtml(titleTrunc)}</a>`;
}
// Priority select
const priOpts = ['critical','high','medium','low'].map(o =>
`<option value="${o}" ${o===curPri?'selected':''}>${o}</option>`
).join('');
const prioritySelect = `<select class="badge" style="${priStyles[curPri]||priStyles.medium};border:none;cursor:pointer;font-size:11px;padding:2px 14px 2px 6px;border-radius:9999px;-webkit-appearance:none;appearance:none;outline:none;font-weight:500" onchange="updateField('${eid}','priority',this.value)">${priOpts}</select>`;
// Status select
const statOpts = ['open','in_process','partial','complete'].map(o =>
`<option value="${o}" ${o===curStat?'selected':''}>${statLabels[o]}</option>`
).join('');
const statusSelect = `<select class="badge" style="${statStyles[curStat]||statStyles.open};border:none;cursor:pointer;font-size:11px;padding:2px 14px 2px 6px;border-radius:9999px;-webkit-appearance:none;appearance:none;outline:none;font-weight:500" onchange="updateField('${eid}','status',this.value)">${statOpts}</select>`;
html += `<tr class="row-request" data-id="${eid}" data-type="${item.type}" data-parent="${item.parent_id}" data-depth="${item.depth}"
draggable="true" ondragstart="onDragStart(event)" ondragover="onDragOver(event)" ondragleave="onDragLeave(event)" ondrop="onDrop(event)">
<td class="drag-handle" style="color:var(--ds-tx3);font-size:11px">\u2630</td>
<td class="row-num" style="padding-left:${indent}px">${escHtml(num)}</td>
<td class="req-title-cell" style="white-space:normal;max-width:400px;padding-left:${indent}px">
${titleHtml}
</td>
<td>${prioritySelect}</td>
<td>${statusSelect}</td>
<td style="max-width:120px;overflow:hidden;text-overflow:ellipsis;color:var(--ds-tx2);font-size:12px">${assignee ? escHtml(assignee) : '\u2014'}</td>
<td style="color:var(--ds-tx2);font-size:12px">${dueDate ? fmtDueDate(dueDate) : '\u2014'}</td>
<td>${labelPill(label)}</td>
<td style="text-align:center">
${item.answer_count > 0
? `<span class="badge" style="background:rgba(74,222,128,.15);color:#4ade80;cursor:pointer" onclick="showAttachModal('${eid}','${escHtml(title)}')">${item.answer_count}</span>`
: `<span style="color:var(--ds-tx3);cursor:pointer;font-size:12px" onclick="showAttachModal('${eid}','${escHtml(title)}')">&mdash;</span>`}
</td>
<td style="max-width:140px;overflow:hidden;text-overflow:ellipsis;color:var(--ds-tx2);font-size:12px" title="${escHtml(buyerComment)}">${escHtml(buyerComment)}</td>
<td style="max-width:140px;overflow:hidden;text-overflow:ellipsis;color:var(--ds-tx2);font-size:12px" title="${escHtml(sellerComment)}">${escHtml(sellerComment)}</td>
<td style="color:var(--ds-tx3);font-size:12px">${fmtDate(item.created_at)}</td>
<td style="position:relative">
<button onclick="toggleMenu(event,'${eid}')" style="background:none;border:none;cursor:pointer;color:var(--ds-tx3);font-size:16px;padding:2px 6px">&hellip;</button>
<div id="menu-${eid}" class="actions-menu" style="display:none">
<button onclick="showAttachModal('${eid}','${escHtml(title)}')">Attach Answer</button>
<button onclick="editRequest('${eid}', event)">Edit</button>
<button onclick="deleteEntry('${eid}')">Delete</button>
</div>
</td>
</tr>`;
}
}
if (!html) html = '<tr><td colspan="13" class="text-[#94a3b8] text-sm py-4">No requests found.</td></tr>';
tbody.innerHTML = html;
}
function toggleCollapse(id) {
if (collapsed.has(id)) collapsed.delete(id); else collapsed.add(id);
renderTree();
}
// ---- Inline field update ----
async function updateField(entryId, field, value) {
const item = treeData.find(t => t.entry_id === entryId);
if (!item) return;
const d = { ...(item.data || {}), [field]: value };
item.data = d;
try {
const res = await fetchAPI('/api/projects/' + projectID + '/entries/' + entryId, {
method: 'PUT',
body: JSON.stringify({ data: JSON.stringify(d), version: item.version || 0 })
});
if (res.ok) {
const result = await res.json();
if (result.version) item.version = result.version;
renderTree();
}
} catch(e) {
console.error('Update failed:', e);
loadRequestTree();
}
}
// ---- Inline edit request title ----
function editRequest(id, e) {
if (e) e.stopPropagation();
if (openMenuId) {
const m = document.getElementById('menu-' + openMenuId);
if (m) m.style.display = 'none';
openMenuId = null;
}
const item = treeData.find(t => t.entry_id === id);
if (!item) return;
const d = item.data || {};
const title = d.title || d.description || 'Untitled';
const row = document.querySelector(`tr[data-id="${id}"]`);
if (!row) return;
const titleCell = row.querySelector('.req-title-cell');
if (!titleCell) return;
row.dataset.originalTitleHtml = titleCell.innerHTML;
titleCell.innerHTML = `<div style="display:flex;align-items:center;gap:4px">
<input type="text" style="flex:1;padding:4px 8px;background:#0a1628;border:1px solid rgba(255,255,255,.12);border-radius:6px;color:white;font-size:13px;outline:none" id="edit-title-${id}">
<button onclick="saveEditRequest('${id}')" style="padding:2px 8px;background:#c9a84c;color:#0a1628;border:none;border-radius:4px;font-size:11px;font-weight:600;cursor:pointer">Save</button>
<button onclick="cancelEditRequest('${id}')" style="padding:2px 8px;background:rgba(255,255,255,.08);color:white;border:none;border-radius:4px;font-size:11px;cursor:pointer">Cancel</button>
</div>`;
const input = document.getElementById('edit-title-' + id);
if (input) { input.value = title; input.focus(); input.select(); }
}
function cancelEditRequest(id) {
const row = document.querySelector(`tr[data-id="${id}"]`);
if (!row) return;
const titleCell = row.querySelector('.req-title-cell');
if (titleCell && row.dataset.originalTitleHtml) titleCell.innerHTML = row.dataset.originalTitleHtml;
}
async function saveEditRequest(id) {
const input = document.getElementById('edit-title-' + id);
if (!input) return;
const newTitle = input.value.trim();
if (!newTitle) return;
const item = treeData.find(t => t.entry_id === id);
if (!item) return;
const d = { ...(item.data || {}), title: newTitle };
item.data = d;
try {
const res = await fetchAPI('/api/projects/' + projectID + '/entries/' + id, {
method: 'PUT',
body: JSON.stringify({ data: JSON.stringify(d), version: item.version || 0 })
});
if (res.ok) {
const result = await res.json();
if (result.version) item.version = result.version;
renderTree();
}
} catch(e) {
console.error('Save failed:', e);
cancelEditRequest(id);
}
}
// ---- Actions menu ----
function toggleMenu(e, id) {
e.stopPropagation();
if (openMenuId && openMenuId !== id) {
const prev = document.getElementById('menu-' + openMenuId);
if (prev) prev.style.display = 'none';
}
const menu = document.getElementById('menu-' + id);
if (menu) {
menu.style.display = menu.style.display === 'none' ? 'block' : 'none';
openMenuId = menu.style.display === 'block' ? id : null;
}
}
document.addEventListener('click', () => {
if (openMenuId) {
const m = document.getElementById('menu-' + openMenuId);
if (m) m.style.display = 'none';
openMenuId = null;
}
});
async function deleteEntry(entryID) {
if (!confirm('Delete this entry?')) return;
await fetchAPI('/api/projects/' + projectID + '/entries/' + entryID, { method: 'DELETE' });
loadRequestTree();
}
// ---- Drag & Drop ----
let dragEntryId = null;
function onDragStart(e) {
dragEntryId = e.currentTarget.dataset.id;
e.dataTransfer.effectAllowed = 'move';
e.currentTarget.style.opacity = '0.5';
}
function onDragOver(e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
const tr = e.currentTarget;
tr.classList.remove('drop-above', 'drop-below', 'drop-into');
const rect = tr.getBoundingClientRect();
const y = e.clientY - rect.top;
const pct = y / rect.height;
if (tr.dataset.type === 'section' && pct > 0.25 && pct < 0.75) {
tr.classList.add('drop-into');
} else if (pct < 0.5) {
tr.classList.add('drop-above');
} else {
tr.classList.add('drop-below');
}
}
function onDragLeave(e) {
e.currentTarget.classList.remove('drop-above', 'drop-below', 'drop-into');
}
async function onDrop(e) {
e.preventDefault();
const tr = e.currentTarget;
tr.classList.remove('drop-above', 'drop-below', 'drop-into');
document.querySelectorAll('#reqTree tr').forEach(r => r.style.opacity = '');
if (!dragEntryId || dragEntryId === tr.dataset.id) return;
const targetId = tr.dataset.id;
const targetType = tr.dataset.type;
const rect = tr.getBoundingClientRect();
const y = e.clientY - rect.top;
const pct = y / rect.height;
let newParentId, position;
if (targetType === 'section' && pct > 0.25 && pct < 0.75) {
newParentId = targetId;
const children = treeData.filter(t => t.parent_id === targetId);
position = children.length;
} else {
newParentId = tr.dataset.parent;
const siblings = treeData.filter(t => t.parent_id === newParentId);
const targetIdx = siblings.findIndex(s => s.entry_id === targetId);
position = pct < 0.5 ? targetIdx : targetIdx + 1;
}
try {
await fetchAPI('/api/projects/' + projectID + '/entries/' + dragEntryId + '/move', {
method: 'POST',
body: JSON.stringify({ parent_id: newParentId, position })
});
await loadRequestTree();
} catch(e) {
console.error('Move failed:', e);
}
dragEntryId = null;
}
// ---- Attach answer modal ----
function showAttachModal(reqId, reqTitle) {
attachRequestId = reqId;
document.getElementById('attachReqTitle').textContent = reqTitle;
document.getElementById('attachModal').style.display = 'flex';
document.getElementById('attachSearch').value = '';
document.getElementById('attachFile').value = '';
loadAnswersForPicker('');
loadLinkedAnswers(reqId);
}
function closeAttachModal() { document.getElementById('attachModal').style.display = 'none'; attachRequestId = null; }
let searchTimeout;
function searchAnswers(q) {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => loadAnswersForPicker(q), 200);
}
async function loadAnswersForPicker(q) {
const list = document.getElementById('attachList');
try {
const res = await fetchAPI('/api/projects/' + projectID + '/answers?q=' + encodeURIComponent(q));
const answers = await res.json();
if (!answers || answers.length === 0) {
list.innerHTML = '<div class="text-[#94a3b8] text-sm py-2">No documents found.</div>';
return;
}
list.innerHTML = answers.map(a => {
const d = a.data || {};
const name = d.filename || d.name || d.title || 'Document';
const objectID = d.object_id || '';
const previewUrl = objectID ? '/api/projects/' + projectID + '/objects/' + objectID + '/preview?filename=' + encodeURIComponent(name) : '';
return `<div class="flex items-center justify-between px-3 py-2 rounded-lg hover:bg-white/[0.04] transition">
<span class="text-white text-sm truncate flex-1">${escHtml(name)}</span>
<div class="flex items-center gap-1.5 shrink-0 ml-2">
${previewUrl ? `<a href="${previewUrl}" target="_blank" class="px-2 py-1 bg-white/[0.06] text-[#94a3b8] hover:text-white rounded text-xs font-medium transition">Preview</a>` : ''}
<button onclick="linkAnswer('${a.entry_id}')" class="px-3 py-1 bg-[#c9a84c]/20 text-[#c9a84c] rounded text-xs font-medium hover:bg-[#c9a84c]/30 transition">Link</button>
</div>
</div>`;
}).join('');
} catch(e) {
list.innerHTML = '<div class="text-red-400 text-sm py-2">Failed to load.</div>';
}
}
async function loadLinkedAnswers(reqId) {
try {
const res = await fetchAPI('/api/projects/' + projectID + '/requests/' + reqId + '/links');
const links = await res.json();
if (links && links.length > 0) {
const linkedHtml = links.map(l => {
const d = l.data || {};
const name = d.filename || d.name || 'Document';
return `<div class="flex items-center justify-between px-3 py-2 rounded-lg bg-green-500/5 border border-green-500/10">
<span class="text-green-300 text-sm truncate flex-1">${escHtml(name)}</span>
<button onclick="unlinkAnswer('${l.answer_id}')" class="ml-2 px-3 py-1 bg-red-500/20 text-red-300 rounded text-xs font-medium hover:bg-red-500/30 transition">Unlink</button>
</div>`;
}).join('');
const list = document.getElementById('attachList');
list.innerHTML = '<div class="text-[#94a3b8] text-xs font-medium mb-1 mt-1">LINKED</div>' + linkedHtml + '<div class="border-t border-white/[0.08] my-2"></div><div class="text-[#94a3b8] text-xs font-medium mb-1">AVAILABLE</div>' + list.innerHTML;
}
} catch(e) {}
}
async function linkAnswer(answerId) {
if (!attachRequestId) return;
await fetchAPI('/api/projects/' + projectID + '/requests/' + attachRequestId + '/links', {
method: 'POST', body: JSON.stringify({ answer_id: answerId })
});
closeAttachModal();
loadRequestTree();
}
async function unlinkAnswer(answerId) {
if (!attachRequestId) return;
await fetchAPI('/api/projects/' + projectID + '/requests/' + attachRequestId + '/links/' + answerId, { method: 'DELETE' });
showAttachModal(attachRequestId, document.getElementById('attachReqTitle').textContent);
}
async function uploadAndLink() {
const fileInput = document.getElementById('attachFile');
const file = fileInput.files[0];
if (!file || !attachRequestId) return;
const fd = new FormData();
fd.append('file', file);
const uploadRes = await fetch('/api/projects/' + projectID + '/objects', {
method: 'POST', headers: { 'Authorization': 'Bearer ' + token }, body: fd
});
const uploadData = await uploadRes.json();
if (!uploadRes.ok) { alert('Upload failed'); return; }
const answerData = JSON.stringify({ filename: file.name, object_id: uploadData.object_id, name: file.name });
const entryRes = await fetchAPI('/api/projects/' + projectID + '/entries', {
method: 'POST',
body: JSON.stringify({ project_id: projectID, parent_id: projectID, type: 'answer', depth: 1, data: answerData, stage: 'dataroom' })
});
const entry = await entryRes.json();
if (entry.entry_id) {
await fetchAPI('/api/projects/' + projectID + '/requests/' + attachRequestId + '/links', {
method: 'POST', body: JSON.stringify({ answer_id: entry.entry_id })
});
}
closeAttachModal();
loadRequestTree();
}
// ---- Orgs + Team ----
async function loadOrgs() {
try {
const res = await fetchAPI('/api/projects/' + projectID + '/orgs');
const orgs = await res.json();
const list = document.getElementById('orgList');
if (!orgs || orgs.length === 0) {
list.innerHTML = '<div class="text-[#94a3b8] text-sm">No organizations added yet.</div>';
} else {
list.innerHTML = orgs.map(o => {
const d = parseData(o.data_text);
const rc = roleColors[d.role] || 'bg-gray-500/20 text-gray-300';
return `<div class="flex items-center gap-4 px-5 py-4 rounded-xl bg-[#0d1f3c] border border-white/[0.08]">
<div class="flex-1">
<div class="flex items-center gap-2 mb-1">
<span class="text-white font-medium">${escHtml(d.org_name || d.name || 'Unknown')}</span>
<span class="px-2 py-0.5 rounded-full text-xs font-medium capitalize ${rc}">${d.role || '?'}</span>
</div>
${d.domains ? `<div class="flex gap-1.5 flex-wrap">${(Array.isArray(d.domains)?d.domains:[d.domains]).map(dm=>`<span class="text-xs text-[#94a3b8] font-mono bg-white/[0.05] px-2 py-0.5 rounded">@${dm}</span>`).join('')}</div>` : ''}
</div>
</div>`;
}).join('');
}
loadTeam();
} catch(e) {}
}
async function loadTeam() {
try {
const res = await fetchAPI('/api/projects/' + projectID + '/members');
const members = await res.json();
const section = document.getElementById('teamMembersSection');
if (!section) return;
if (!members || members.length === 0) {
section.innerHTML = `<div class="border-t border-white/[0.08] pt-4 mt-4">
<h3 class="text-sm font-semibold text-[#94a3b8] uppercase tracking-wider mb-3">Team Members</h3>
<div class="text-[#94a3b8] text-sm">No team members yet.</div>
</div>`;
return;
}
section.innerHTML = `<div class="border-t border-white/[0.08] pt-4 mt-4">
<h3 class="text-sm font-semibold text-[#94a3b8] uppercase tracking-wider mb-3">Team Members</h3>
<div class="space-y-2">${members.map(m => `
<div class="flex items-center gap-4 px-5 py-3 rounded-xl bg-[#0d1f3c] border border-white/[0.08]">
<div class="w-8 h-8 rounded-full bg-[#c9a84c]/20 flex items-center justify-center text-[#c9a84c] font-semibold text-sm">${(m.name||m.email||'?')[0].toUpperCase()}</div>
<div class="flex-1">
<div class="text-white text-sm font-medium">${escHtml(m.name || m.email)}</div>
${m.name ? `<div class="text-[#94a3b8] text-xs">${escHtml(m.email)}</div>` : ''}
</div>
<span class="text-xs text-[#94a3b8] capitalize">${m.role || 'member'}</span>
</div>`).join('')}
</div>
</div>`;
} catch(e) {}
}
function switchTab(name, el) {
document.querySelectorAll('.tab').forEach(t => { t.classList.remove('active','text-white'); t.classList.add('text-[#94a3b8]'); });
el.classList.add('active','text-white'); el.classList.remove('text-[#94a3b8]');
document.getElementById('tab-requests').classList.toggle('hidden', name !== 'requests');
document.getElementById('tab-orgs').classList.toggle('hidden', name !== 'orgs');
if (name === 'orgs') loadOrgs();
}
// ---- Import ----
async function openImportModal() {
document.getElementById('importModal').style.display='flex';
document.getElementById('importFile').value='';
document.getElementById('importListName').value='';
document.getElementById('importError').classList.add('hidden');
// Populate visibility org options
try {
const res = await fetchAPI('/api/projects/' + projectID + '/orgs');
const orgs = await res.json();
const sel = document.getElementById('importVisibility');
sel.innerHTML = '<option value="">Everyone (General List)</option>';
if (orgs && orgs.length > 0) {
for (const o of orgs) {
const d = parseData(o.data_text);
const orgName = d.org_name || d.name || 'Unknown';
const orgId = d.org_id || o.entry_id || '';
sel.innerHTML += `<option value="${escHtml(orgId)}">${escHtml(orgName)} only</option>`;
}
}
} catch(e) {}
}
function closeImportModal() { document.getElementById('importModal').style.display='none'; }
async function submitImport() {
const file = document.getElementById('importFile').files[0];
const errEl = document.getElementById('importError');
const btn = document.getElementById('importBtn');
if (!file) { errEl.textContent = 'Please select a file'; errEl.classList.remove('hidden'); return; }
btn.disabled = true; btn.textContent = 'Importing...'; errEl.classList.add('hidden');
const fd = new FormData();
fd.append('file', file);
fd.append('mode', document.getElementById('importMode').value);
fd.append('list_name', document.getElementById('importListName').value);
fd.append('visibility_org_id', document.getElementById('importVisibility').value);
try {
const res = await fetch('/api/projects/' + projectID + '/requests/import', { method: 'POST', headers: { 'Authorization': 'Bearer ' + token }, body: fd });
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Import failed');
closeImportModal();
loadRequestTree();
} catch(e) { errEl.textContent = e.message; errEl.classList.remove('hidden'); }
finally { btn.disabled = false; btn.textContent = 'Import'; }
}
// ---- Visibility edit ----
async function editVisibility(entryId) {
const item = treeData.find(t => t.entry_id === entryId);
if (!item) return;
const d = item.data || {};
const currentVis = d.visibility_org_id || '';
// Fetch orgs for the selector
let orgs = [];
try {
const res = await fetchAPI('/api/projects/' + projectID + '/orgs');
orgs = await res.json() || [];
} catch(e) {}
let opts = '<option value="">Everyone (General List)</option>';
for (const o of orgs) {
const od = parseData(o.data_text);
const orgName = od.org_name || od.name || 'Unknown';
const orgId = od.org_id || o.entry_id || '';
opts += `<option value="${escHtml(orgId)}" ${orgId === currentVis ? 'selected' : ''}>${escHtml(orgName)} only</option>`;
}
const row = document.querySelector(`tr[data-id="${entryId}"]`);
if (!row) return;
const td = row.querySelector('td:nth-child(2)');
if (!td) return;
td.dataset.origHtml = td.innerHTML;
td.innerHTML += `<div style="margin-top:4px;display:flex;align-items:center;gap:4px">
<select id="vis-sel-${entryId}" style="padding:4px 8px;background:#0a1628;border:1px solid rgba(255,255,255,.12);border-radius:6px;color:white;font-size:12px">${opts}</select>
<button onclick="saveVisibility('${entryId}')" style="padding:2px 8px;background:#c9a84c;color:#0a1628;border:none;border-radius:4px;font-size:11px;font-weight:600;cursor:pointer">Save</button>
<button onclick="cancelVisibility('${entryId}')" style="padding:2px 8px;background:rgba(255,255,255,.08);color:white;border:none;border-radius:4px;font-size:11px;cursor:pointer">Cancel</button>
</div>`;
}
function cancelVisibility(entryId) {
const row = document.querySelector(`tr[data-id="${entryId}"]`);
if (!row) return;
const td = row.querySelector('td:nth-child(2)');
if (td && td.dataset.origHtml) td.innerHTML = td.dataset.origHtml;
}
async function saveVisibility(entryId) {
const sel = document.getElementById('vis-sel-' + entryId);
if (!sel) return;
const val = sel.value || null;
try {
await fetchAPI('/api/projects/' + projectID + '/entries/' + entryId + '/visibility', {
method: 'PATCH',
body: JSON.stringify({ visibility_org_id: val })
});
loadRequestTree();
} catch(e) {
console.error('Visibility update failed:', e);
}
}
// ---- Init ----
loadProject();
loadRequestTree();
</script>
{{end}}