Files
item-code/templates/admin_dashboard.html
2026-10-13 16:00:15 +05:30

1371 lines
49 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Administration</title>
<style>
:root {
--primary: #0284c7;
--primary-hover: #0369a1;
--primary-light: #f0f9ff;
--primary-border: #bae6fd;
--primary-focus-ring: rgba(2, 132, 199, 0.18);
--surface: #ffffff;
--background: #f8fafc;
--border: #e2e8f0;
--border-hover: #cbd5e1;
--text-primary: #0f172a;
--text-secondary: #475569;
--text-muted: #64748b;
--success: #059669;
--success-light: #ecfdf5;
--success-border: #a7f3d0;
--success-text: #065f46;
--warning: #d97706;
--warning-light: #fffbeb;
--warning-border: #fde68a;
--warning-text: #92400e;
--danger: #dc2626;
--danger-light: #fef2f2;
--danger-border: #fecaca;
--danger-text: #991b1b;
--info: #0284c7;
--info-light: #f0f9ff;
--info-border: #bae6fd;
--info-text: #075985;
--radius-sm: 4px;
--radius: 6px;
--radius-lg: 8px;
--shadow-subtle: 0 1px 3px 0 rgba(0, 0, 0, 0.05), 0 1px 2px -1px rgba(0, 0, 0, 0.05);
--shadow-card: 0 1px 3px rgba(0, 0, 0, 0.04), 0 1px 2px rgba(0, 0, 0, 0.02);
--shadow-modal: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background-color: var(--background);
color: var(--text-primary);
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
/* Top Navigation */
.navbar {
background-color: var(--surface);
border-bottom: 1px solid var(--border);
padding: 8px 32px;
display: flex;
justify-content: space-between;
align-items: center;
position: sticky;
top: 0;
z-index: 100;
}
.navbar-brand-area {
display: flex;
align-items: center;
gap: 16px;
}
/* Dedicated Logo Placeholder Area */
.logo-placeholder-slot {
height: 56px;
display: flex;
align-items: center;
user-select: none;
}
.logo-placeholder-slot img {
max-height: 56px;
height: 54px;
width: auto;
object-fit: contain;
display: block;
}
.navbar-right {
display: flex;
gap: 12px;
align-items: center;
}
.nav-link {
padding: 7px 14px;
border: 1px solid var(--border);
border-radius: var(--radius);
text-decoration: none;
font-size: 13px;
font-weight: 500;
color: var(--text-secondary);
transition: all 0.15s ease;
background-color: transparent;
}
.nav-link:hover {
background-color: #f1f5f9;
color: var(--text-primary);
border-color: var(--border-hover);
}
/* Container */
.container {
max-width: 1240px;
margin: 0 auto;
padding: 32px 24px;
}
/* Header */
.header {
margin-bottom: 28px;
}
.header h1 {
font-size: 22px;
font-weight: 600;
color: var(--text-primary);
letter-spacing: -0.01em;
margin-bottom: 4px;
}
.header p {
color: var(--text-secondary);
font-size: 14px;
}
/* Tabs */
.tabs {
display: flex;
gap: 8px;
margin-bottom: 24px;
border-bottom: 1px solid var(--border);
overflow-x: auto;
}
.tab-button {
padding: 10px 16px;
border: none;
background: none;
cursor: pointer;
font-size: 14px;
font-weight: 500;
color: var(--text-muted);
border-bottom: 2px solid transparent;
margin-bottom: -1px;
transition: all 0.15s ease;
white-space: nowrap;
}
.tab-button:hover {
color: var(--primary);
}
.tab-button.active {
color: var(--primary);
font-weight: 600;
border-bottom-color: var(--primary);
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
/* Summary Grid */
.summary-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 16px;
margin-bottom: 28px;
}
.summary-card {
background-color: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 18px 20px;
box-shadow: var(--shadow-card);
}
.summary-label {
font-size: 12px;
color: var(--text-muted);
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.03em;
margin-bottom: 6px;
}
.summary-value {
font-size: 26px;
font-weight: 700;
color: var(--text-primary);
line-height: 1.1;
}
/* Content Blocks */
.day-block,
.user-management-section {
background-color: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 24px;
margin-bottom: 24px;
box-shadow: var(--shadow-card);
}
.day-block h2 {
font-size: 16px;
font-weight: 600;
margin-bottom: 16px;
color: var(--text-primary);
display: flex;
align-items: center;
gap: 10px;
}
.today-badge {
display: inline-block;
padding: 2px 8px;
background-color: var(--primary-light);
color: var(--primary);
border: 1px solid var(--primary-border);
border-radius: 10px;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.03em;
}
.management-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
flex-wrap: wrap;
gap: 12px;
}
.management-header h3 {
font-size: 17px;
font-weight: 600;
color: var(--text-primary);
}
/* Tables */
.table-scroll {
overflow-x: auto;
border: 1px solid var(--border);
border-radius: var(--radius);
}
table.stats-table,
table.users-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
text-align: left;
}
.stats-table th,
.users-table th {
background-color: #f8fafc;
padding: 10px 14px;
border-bottom: 1px solid var(--border);
font-weight: 600;
font-size: 12px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.03em;
white-space: nowrap;
}
.stats-table td,
.users-table td {
padding: 11px 14px;
border-bottom: 1px solid var(--border);
color: var(--text-primary);
vertical-align: middle;
}
.stats-table tbody tr:last-child td,
.users-table tbody tr:last-child td {
border-bottom: none;
}
.stats-table tbody tr:hover,
.users-table tbody tr:hover {
background-color: #f8fafc;
}
.num {
text-align: right;
font-variant-numeric: tabular-nums;
}
/* Tags and Badges */
.tag {
display: inline-block;
padding: 2px 7px;
border-radius: 4px;
font-size: 11px;
font-weight: 600;
line-height: 1.3;
}
.tag.matched {
background-color: var(--success-light);
color: var(--success-text);
border: 1px solid var(--success-border);
}
.tag.manual {
background-color: #f5f3ff;
color: #6d28d9;
border: 1px solid #ddd6fe;
}
.tag.missing {
background-color: var(--danger-light);
color: var(--danger-text);
border: 1px solid var(--danger-border);
}
.admin-badge {
display: inline-block;
padding: 1px 6px;
background-color: #f1f5f9;
color: var(--text-secondary);
border: 1px solid var(--border);
border-radius: 4px;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.04em;
margin-left: 6px;
}
.status-badge {
display: inline-flex;
align-items: center;
font-weight: 500;
font-size: 12px;
}
.status-badge.active {
color: var(--success-text);
}
.status-badge.inactive {
color: var(--danger-text);
}
/* Buttons */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 8px 16px;
border: 1px solid transparent;
border-radius: var(--radius);
font-size: 13px;
font-weight: 600;
cursor: pointer;
transition: all 0.15s ease;
font-family: inherit;
line-height: 1.4;
text-decoration: none;
}
.btn-primary {
background-color: var(--primary);
color: #ffffff;
}
.btn-primary:hover {
background-color: var(--primary-hover);
}
.btn-danger {
background-color: transparent;
color: var(--danger);
border: 1px solid var(--danger-border);
padding: 4px 10px;
font-size: 12px;
}
.btn-danger:hover {
background-color: var(--danger-light);
border-color: var(--danger);
}
.btn-cancel {
background-color: #f1f5f9;
color: var(--text-secondary);
border-color: var(--border);
}
.btn-cancel:hover {
background-color: #e2e8f0;
color: var(--text-primary);
}
/* Catalog Toolbar */
.catalog-toolbar {
display: flex;
gap: 12px;
margin-bottom: 16px;
flex-wrap: wrap;
}
.catalog-search {
flex: 1;
min-width: 240px;
padding: 8px 12px;
border: 1px solid #cbd5e1;
border-radius: var(--radius);
font-size: 13px;
background-color: #ffffff;
color: var(--text-primary);
transition: border-color 0.15s ease;
font-family: inherit;
}
.catalog-search:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 3px var(--primary-focus-ring);
}
.catalog-select {
padding: 8px 12px;
border: 1px solid #cbd5e1;
border-radius: var(--radius);
font-size: 13px;
background-color: #ffffff;
color: var(--text-primary);
font-family: inherit;
}
.catalog-select:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 3px var(--primary-focus-ring);
}
.catalog-footer {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 16px;
padding-top: 12px;
border-top: 1px solid var(--border);
}
.catalog-count {
font-size: 12px;
color: var(--text-muted);
}
/* Empty State */
.empty-state {
text-align: center;
padding: 48px 20px;
color: var(--text-muted);
}
.empty-state-title {
font-size: 15px;
font-weight: 600;
color: var(--text-secondary);
margin-bottom: 4px;
}
.empty-state-desc {
font-size: 13px;
color: var(--text-muted);
}
/* Modals */
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(15, 23, 42, 0.5);
z-index: 1000;
align-items: center;
justify-content: center;
padding: 16px;
}
.modal.active {
display: flex;
}
.modal-content {
background-color: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 28px 24px;
width: 100%;
max-width: 480px;
box-shadow: var(--shadow-modal);
}
.modal-header-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
padding-bottom: 12px;
border-bottom: 1px solid var(--border);
}
.modal-header {
font-size: 16px;
font-weight: 600;
color: var(--text-primary);
}
.modal-close-btn {
background: transparent;
border: none;
font-size: 18px;
cursor: pointer;
color: var(--text-muted);
padding: 4px;
line-height: 1;
}
.modal-close-btn:hover {
color: var(--text-primary);
}
.form-group {
margin-bottom: 16px;
}
.form-group label {
display: block;
margin-bottom: 6px;
font-weight: 500;
color: var(--text-primary);
font-size: 13px;
}
.form-group input {
width: 100%;
padding: 9px 12px;
border: 1px solid #cbd5e1;
border-radius: var(--radius);
font-size: 13px;
color: var(--text-primary);
background-color: #ffffff;
font-family: inherit;
transition: border-color 0.15s ease;
}
.form-group input:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 3px var(--primary-focus-ring);
}
.modal-buttons {
display: flex;
gap: 10px;
justify-content: flex-end;
margin-top: 24px;
padding-top: 14px;
border-top: 1px solid var(--border);
}
/* Message Banners */
.message {
padding: 12px 16px;
border-radius: var(--radius);
margin-bottom: 20px;
font-size: 13px;
line-height: 1.4;
}
.message.error {
background-color: var(--danger-light);
color: var(--danger-text);
border: 1px solid var(--danger-border);
}
.message.success {
background-color: var(--success-light);
color: var(--success-text);
border: 1px solid var(--success-border);
}
@media (max-width: 768px) {
.navbar {
flex-direction: column;
gap: 12px;
padding: 12px 16px;
align-items: flex-start;
}
.navbar-right {
width: 100%;
justify-content: space-between;
}
.container {
padding: 20px 16px;
}
.catalog-toolbar {
flex-direction: column;
}
}
</style>
</head>
<body>
<!-- Top Navigation Bar -->
<nav class="navbar">
<div class="navbar-brand-area">
<div class="logo-placeholder-slot" id="logoPlaceholder">
<img src="{{ url_for('static', filename='logo.png') }}" alt="Logo">
</div>
</div>
<div class="navbar-right">
<a href="{{ url_for('dashboard') }}" class="nav-link">Back to Dashboard</a>
<a href="{{ url_for('logout') }}" class="nav-link">Sign Out</a>
</div>
</nav>
<!-- Main Container -->
<div class="container">
<!-- Page Header -->
<div class="header">
<h1>Administration Portal</h1>
<p>Manage system users, view processing statistics, and update catalog definitions</p>
</div>
<!-- Tab Navigation -->
<div class="tabs">
<button class="tab-button active" onclick="switchTab('statistics')">Statistics</button>
<button class="tab-button" onclick="switchTab('users')">User Management</button>
<button class="tab-button" onclick="switchTab('catalog')">Catalog</button>
<button class="tab-button" onclick="switchTab('quality')">Quality &amp; Review</button>
</div>
<!-- Tab 1: Statistics -->
<div id="statistics" class="tab-content active">
<div class="summary-grid">
<div class="summary-card">
<div class="summary-label">PDFs Today</div>
<div class="summary-value">{{ summary.today_pdfs }}</div>
</div>
<div class="summary-card">
<div class="summary-label">Active Users Today</div>
<div class="summary-value">{{ summary.today_active_users }}</div>
</div>
<div class="summary-card">
<div class="summary-label">Total PDFs Processed</div>
<div class="summary-value">{{ summary.total_pdfs }}</div>
</div>
<div class="summary-card">
<div class="summary-label">Total Items Processed</div>
<div class="summary-value">{{ summary.total_items }}</div>
</div>
<div class="summary-card">
<div class="summary-label">Item Codes Added Manually</div>
<div class="summary-value">{{ summary.total_manual }}</div>
</div>
<div class="summary-card">
<div class="summary-label">Items Missing Code</div>
<div class="summary-value">{{ summary.total_missing }}</div>
</div>
</div>
{% if stats %}
{% for day in stats %}
<div class="day-block">
<h2>
{{ day.date }}
{% if day.date == today %}<span class="today-badge">TODAY</span>{% endif %}
</h2>
<div class="table-scroll">
<table class="stats-table">
<thead>
<tr>
<th>User</th>
<th class="num">PDFs</th>
<th class="num">Items</th>
<th class="num">With Code</th>
<th class="num">Auto-Matched</th>
<th class="num">Manual</th>
<th class="num">Missing</th>
</tr>
</thead>
<tbody>
{% for u in day.users %}
<tr>
<td><strong>{{ u.username }}</strong></td>
<td class="num">{{ u.pdfs_processed }}</td>
<td class="num">{{ u.total_items }}</td>
<td class="num">{{ u.items_with_code }}</td>
<td class="num"><span class="tag matched">{{ u.items_auto_matched }}</span></td>
<td class="num"><span class="tag manual">{{ u.items_manual }}</span></td>
<td class="num">
{% if u.items_missing > 0 %}<span class="tag missing">{{ u.items_missing }}</span>
{% else %}0{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endfor %}
{% else %}
<div class="day-block">
<div class="empty-state">
<div class="empty-state-title">No Activity Recorded</div>
<div class="empty-state-desc">No invoices have been processed in the system yet.</div>
</div>
</div>
{% endif %}
</div>
<!-- Tab 2: User Management -->
<div id="users" class="tab-content">
<div id="messageContainer"></div>
<div class="user-management-section">
<div class="management-header">
<h3>Registered Users</h3>
<button class="btn btn-primary" onclick="openAddUserModal()">Add User</button>
</div>
<div class="table-scroll">
<table class="users-table" id="usersTable" style="{{ 'display:none;' if not all_users else '' }}">
<thead>
<tr>
<th>Username</th>
<th>Email</th>
<th>Registered</th>
<th>Last Login</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="usersTableBody">
{% for user in all_users %}
<tr data-username="{{ user.username }}">
<td>
<strong>{{ user.username }}</strong>
{% if user.is_admin %}<span class="admin-badge">ADMIN</span>{% endif %}
</td>
<td>{{ user.email }}</td>
<td>{{ user.created_at[:10] if user.created_at else 'N/A' }}</td>
<td>{{ user.last_login[:10] if user.last_login else 'Never' }}</td>
<td>
{% if user.is_active %}
<span class="status-badge active">Active</span>
{% else %}
<span class="status-badge inactive">Inactive</span>
{% endif %}
</td>
<td>
{% if user.username != 'admin' %}
<button class="btn btn-danger" onclick="deleteUser('{{ user.username }}')">Delete</button>
{% else %}
<span style="color: var(--text-muted); font-size: 12px;">Protected</span>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="empty-state" id="usersEmptyState" style="{{ '' if not all_users else 'display:none;' }}">
<div class="empty-state-title">No Registered Users</div>
<div class="empty-state-desc">Add a new user to grant access to the system.</div>
</div>
</div>
</div>
<!-- Tab 3: Catalog -->
<div id="catalog" class="tab-content">
<div id="catalogMessageContainer"></div>
<div class="user-management-section">
<div class="management-header">
<h3>Item Code Catalog</h3>
<button class="btn btn-primary" onclick="openAddCodeModal()">Add Item Code</button>
</div>
<div class="catalog-toolbar">
<input type="text" id="catalogSearch" class="catalog-search" placeholder="Search by name or item code...">
<select id="catalogCategoryFilter" class="catalog-select">
<option value="">All Categories</option>
</select>
</div>
<div class="table-scroll">
<table class="users-table">
<thead>
<tr>
<th>Item Code</th>
<th>Name</th>
<th>Category</th>
<th>Updated</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="catalogTableBody"></tbody>
</table>
</div>
<div class="empty-state" id="catalogEmptyState" style="display:none;">
<div class="empty-state-title">No Catalog Entries Found</div>
<div class="empty-state-desc">Try adjusting your search criteria or add a new item code.</div>
</div>
<div class="catalog-footer">
<span id="catalogCount" class="catalog-count"></span>
<button class="btn btn-cancel" id="catalogLoadMoreBtn" onclick="loadCatalog(true)" style="display:none;">Load More</button>
</div>
</div>
</div>
<!-- Tab 4: Quality & Review -->
<div id="quality" class="tab-content">
<div class="summary-grid" id="qualitySummaryGrid"></div>
<div class="day-block">
<h2>Catalog by Category</h2>
<div class="table-scroll">
<table class="stats-table" id="categoryStatsTable">
<thead>
<tr><th>Category</th><th class="num">Item Codes</th></tr>
</thead>
<tbody id="categoryStatsBody"></tbody>
</table>
</div>
</div>
<div class="day-block">
<h2>Items Requiring Review <span style="font-weight:400; color:var(--text-muted); font-size:13px;">(No item code assigned)</span></h2>
<div class="table-scroll">
<table class="stats-table" id="reviewTable">
<thead>
<tr>
<th>Description</th>
<th>User</th>
<th>File</th>
<th>Uploaded</th>
</tr>
</thead>
<tbody id="reviewTableBody"></tbody>
</table>
</div>
<div class="empty-state" id="reviewEmptyState" style="display:none;">
<div class="empty-state-title">All Items Assigned</div>
<div class="empty-state-desc">Every extracted invoice item currently has a designated item code.</div>
</div>
</div>
</div>
</div>
<!-- Add/Edit Item Code Modal -->
<div id="codeModal" class="modal">
<div class="modal-content">
<div class="modal-header-row">
<div class="modal-header" id="codeModalHeader">Add Item Code</div>
<button type="button" class="modal-close-btn" onclick="closeCodeModal()">&times;</button>
</div>
<form onsubmit="submitCodeForm(event)">
<input type="hidden" id="codeModalId" value="">
<div class="form-group">
<label for="codeItemCode">Item Code</label>
<input type="text" id="codeItemCode" required placeholder="e.g. MED-1023" maxlength="50">
</div>
<div class="form-group">
<label for="codeName">Item Name / Description</label>
<input type="text" id="codeName" required placeholder="e.g. Telma Beta 40 Tablet">
</div>
<div class="form-group">
<label for="codeCategory">Category</label>
<input type="text" id="codeCategory" list="categoryOptions" placeholder="e.g. Pharmaceuticals, Supplies, Diagnostics">
<datalist id="categoryOptions"></datalist>
</div>
<div class="modal-buttons">
<button type="button" class="btn btn-cancel" onclick="closeCodeModal()">Cancel</button>
<button type="submit" class="btn btn-primary">Save Code</button>
</div>
</form>
</div>
</div>
<!-- Add User Modal -->
<div id="addUserModal" class="modal">
<div class="modal-content">
<div class="modal-header-row">
<div class="modal-header">Add New User</div>
<button type="button" class="modal-close-btn" onclick="closeAddUserModal()">&times;</button>
</div>
<form id="addUserForm" onsubmit="submitAddUser(event)">
<div class="form-group">
<label for="newUsername">Username</label>
<input type="text" id="newUsername" required placeholder="Choose username" autocomplete="off">
</div>
<div class="form-group">
<label for="newEmail">Email Address</label>
<input type="email" id="newEmail" required placeholder="user@domain.com" autocomplete="off">
</div>
<div class="form-group">
<label for="newPassword">Password</label>
<input type="password" id="newPassword" required placeholder="Minimum 6 characters" autocomplete="new-password">
</div>
<div class="form-group">
<label for="newPasswordConfirm">Confirm Password</label>
<input type="password" id="newPasswordConfirm" required placeholder="Confirm password" autocomplete="new-password">
</div>
<div class="modal-buttons">
<button type="button" class="btn btn-cancel" onclick="closeAddUserModal()">Cancel</button>
<button type="submit" class="btn btn-primary">Create User</button>
</div>
</form>
</div>
</div>
<script>
let catalogLoadedOnce = false;
let qualityLoadedOnce = false;
function switchTab(tabName) {
document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
document.getElementById(tabName).classList.add('active');
if (event && event.target) {
event.target.classList.add('active');
}
if (tabName === 'catalog' && !catalogLoadedOnce) {
catalogLoadedOnce = true;
loadCategoryOptions();
loadCatalog(false);
}
if (tabName === 'quality' && !qualityLoadedOnce) {
qualityLoadedOnce = true;
loadQualityStats();
loadItemsToReview();
}
}
// ============================================================
// CATALOG
// ============================================================
let catalogPage = 1;
let catalogSearchTimer = null;
document.getElementById('catalogSearch').addEventListener('input', () => {
clearTimeout(catalogSearchTimer);
catalogSearchTimer = setTimeout(() => loadCatalog(false), 300);
});
document.getElementById('catalogCategoryFilter').addEventListener('change', () => loadCatalog(false));
async function loadCategoryOptions() {
try {
const res = await fetch('/api/catalog/categories');
const data = await res.json();
if (!data.success) return;
const filterSelect = document.getElementById('catalogCategoryFilter');
const datalist = document.getElementById('categoryOptions');
filterSelect.querySelectorAll('option:not(:first-child)').forEach(o => o.remove());
datalist.replaceChildren();
data.data.forEach(cat => {
const opt1 = document.createElement('option');
opt1.value = cat; opt1.textContent = cat;
filterSelect.appendChild(opt1);
const opt2 = document.createElement('option');
opt2.value = cat;
datalist.appendChild(opt2);
});
} catch (e) { /* silent */ }
}
async function loadCatalog(append) {
const q = document.getElementById('catalogSearch').value.trim();
const category = document.getElementById('catalogCategoryFilter').value;
catalogPage = append ? catalogPage + 1 : 1;
const params = new URLSearchParams({ page: catalogPage, per_page: 50 });
if (q) params.set('q', q);
if (category) params.set('category', category);
try {
const res = await fetch(`/api/catalog?${params}`);
const data = await res.json();
if (!data.success) return;
const tbody = document.getElementById('catalogTableBody');
if (!append) tbody.replaceChildren();
data.data.forEach(row => tbody.appendChild(buildCatalogRow(row)));
document.getElementById('catalogEmptyState').style.display = data.total === 0 ? 'block' : 'none';
document.getElementById('catalogCount').textContent = `${data.total} item code${data.total === 1 ? '' : 's'}`;
document.getElementById('catalogLoadMoreBtn').style.display = data.has_more ? 'inline-block' : 'none';
} catch (e) {
showCatalogMessage('Failed to load catalog data.', 'error');
}
}
function buildCatalogRow(row) {
const tr = document.createElement('tr');
const codeTd = document.createElement('td');
codeTd.innerHTML = '<strong></strong>';
codeTd.querySelector('strong').textContent = row.item_code;
tr.appendChild(codeTd);
const nameTd = document.createElement('td');
nameTd.textContent = row.name;
tr.appendChild(nameTd);
const catTd = document.createElement('td');
catTd.textContent = row.category;
tr.appendChild(catTd);
const updatedTd = document.createElement('td');
updatedTd.textContent = (row.updated_at || row.created_at || '').slice(0, 10);
tr.appendChild(updatedTd);
const actionsTd = document.createElement('td');
const editBtn = document.createElement('button');
editBtn.className = 'btn btn-cancel';
editBtn.style.padding = '4px 10px';
editBtn.style.marginRight = '6px';
editBtn.textContent = 'Edit';
editBtn.onclick = () => openEditCodeModal(row);
const delBtn = document.createElement('button');
delBtn.className = 'btn btn-danger';
delBtn.textContent = 'Delete';
delBtn.onclick = () => deleteCatalogEntry(row.id, row.item_code);
actionsTd.appendChild(editBtn);
actionsTd.appendChild(delBtn);
tr.appendChild(actionsTd);
return tr;
}
function openAddCodeModal() {
document.getElementById('codeModalHeader').textContent = 'Add Item Code';
document.getElementById('codeModalId').value = '';
document.getElementById('codeItemCode').value = '';
document.getElementById('codeName').value = '';
document.getElementById('codeCategory').value = '';
document.getElementById('codeModal').classList.add('active');
}
function openEditCodeModal(row) {
document.getElementById('codeModalHeader').textContent = 'Edit Item Code';
document.getElementById('codeModalId').value = row.id;
document.getElementById('codeItemCode').value = row.item_code;
document.getElementById('codeName').value = row.name;
document.getElementById('codeCategory').value = row.category;
document.getElementById('codeModal').classList.add('active');
}
function closeCodeModal() {
document.getElementById('codeModal').classList.remove('active');
}
async function submitCodeForm(event) {
event.preventDefault();
const id = document.getElementById('codeModalId').value;
const payload = {
item_code: document.getElementById('codeItemCode').value.trim(),
name: document.getElementById('codeName').value.trim(),
category: document.getElementById('codeCategory').value.trim(),
};
try {
const res = await fetch(id ? `/api/catalog/${id}` : '/api/catalog', {
method: id ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const data = await res.json();
if (data.success) {
showCatalogMessage(data.message, 'success');
closeCodeModal();
loadCategoryOptions();
loadCatalog(false);
} else {
showCatalogMessage(data.message || 'Failed to save item code.', 'error');
}
} catch (e) {
showCatalogMessage('Network error saving item code.', 'error');
}
}
async function deleteCatalogEntry(id, code) {
if (!confirm(`Delete item code "${code}"? This action cannot be undone.`)) return;
try {
const res = await fetch(`/api/catalog/${id}`, { method: 'DELETE' });
const data = await res.json();
if (data.success) {
showCatalogMessage(data.message, 'success');
loadCatalog(false);
} else {
showCatalogMessage(data.message || 'Failed to delete item code.', 'error');
}
} catch (e) {
showCatalogMessage('Network error deleting item code.', 'error');
}
}
function showCatalogMessage(message, type) {
const container = document.getElementById('catalogMessageContainer');
container.innerHTML = '';
const div = document.createElement('div');
div.className = `message ${type}`;
div.textContent = message;
container.appendChild(div);
setTimeout(() => container.innerHTML = '', 4000);
}
// ============================================================
// QUALITY & REVIEW
// ============================================================
async function loadQualityStats() {
try {
const res = await fetch('/api/admin/quality-stats');
const result = await res.json();
if (!result.success) return;
const d = result.data;
const grid = document.getElementById('qualitySummaryGrid');
grid.replaceChildren();
[
['Total Catalog Codes', d.catalog_total_codes],
['Distinct Categories', d.catalog_by_category.length],
['Total Items Processed', d.total_items],
['Completion Rate', d.completion_pct + '%'],
['Auto-Matched', d.items_auto_matched],
['Missing Item Code', d.items_missing],
].forEach(([label, value]) => {
const card = document.createElement('div');
card.className = 'summary-card';
card.innerHTML = `<div class="summary-label"></div><div class="summary-value"></div>`;
card.querySelector('.summary-label').textContent = label;
card.querySelector('.summary-value').textContent = value;
grid.appendChild(card);
});
const catBody = document.getElementById('categoryStatsBody');
catBody.replaceChildren();
d.catalog_by_category.forEach(c => {
const tr = document.createElement('tr');
const tdCat = document.createElement('td'); tdCat.textContent = c.category;
const tdCount = document.createElement('td'); tdCount.className = 'num'; tdCount.textContent = c.count;
tr.appendChild(tdCat); tr.appendChild(tdCount);
catBody.appendChild(tr);
});
} catch (e) { /* silent */ }
}
async function loadItemsToReview() {
try {
const res = await fetch('/api/admin/items-to-review?limit=100');
const result = await res.json();
if (!result.success) return;
const tbody = document.getElementById('reviewTableBody');
tbody.replaceChildren();
result.data.forEach(item => {
const tr = document.createElement('tr');
[item.description || '-', item.username, item.filename || '-', (item.created_at || '').slice(0, 10)]
.forEach(val => {
const td = document.createElement('td');
td.textContent = val;
tr.appendChild(td);
});
tbody.appendChild(tr);
});
document.getElementById('reviewEmptyState').style.display = result.data.length === 0 ? 'block' : 'none';
} catch (e) { /* silent */ }
}
function openAddUserModal() {
document.getElementById('addUserModal').classList.add('active');
}
function closeAddUserModal() {
document.getElementById('addUserModal').classList.remove('active');
document.getElementById('addUserForm')?.reset();
}
function submitAddUser(event) {
event.preventDefault();
const username = document.getElementById('newUsername').value;
const email = document.getElementById('newEmail').value;
const password = document.getElementById('newPassword').value;
const passwordConfirm = document.getElementById('newPasswordConfirm').value;
if (password !== passwordConfirm) {
showMessage('Passwords do not match.', 'error');
return;
}
fetch('/api/admin/add-user', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: username,
email: email,
password: password
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
showMessage('User account created successfully.', 'success');
closeAddUserModal();
if (data.user) addUserRow(data.user);
} else {
showMessage(data.message || 'Failed to create user.', 'error');
}
})
.catch(error => {
showMessage('Error: ' + error.message, 'error');
});
}
function addUserRow(user) {
document.getElementById('usersTable').style.display = '';
document.getElementById('usersEmptyState').style.display = 'none';
const tbody = document.getElementById('usersTableBody');
const tr = document.createElement('tr');
tr.dataset.username = user.username;
const nameTd = document.createElement('td');
const strong = document.createElement('strong');
strong.textContent = user.username;
nameTd.appendChild(strong);
if (user.is_admin) {
const badge = document.createElement('span');
badge.className = 'admin-badge';
badge.textContent = 'ADMIN';
nameTd.appendChild(document.createTextNode(' '));
nameTd.appendChild(badge);
}
tr.appendChild(nameTd);
const emailTd = document.createElement('td');
emailTd.textContent = user.email;
tr.appendChild(emailTd);
const regTd = document.createElement('td');
regTd.textContent = user.created_at ? user.created_at.slice(0, 10) : 'N/A';
tr.appendChild(regTd);
const loginTd = document.createElement('td');
loginTd.textContent = user.last_login ? user.last_login.slice(0, 10) : 'Never';
tr.appendChild(loginTd);
const statusTd = document.createElement('td');
const statusSpan = document.createElement('span');
statusSpan.className = user.is_active ? 'status-badge active' : 'status-badge inactive';
statusSpan.textContent = user.is_active ? 'Active' : 'Inactive';
statusTd.appendChild(statusSpan);
tr.appendChild(statusTd);
const actionsTd = document.createElement('td');
if (user.username !== 'admin') {
const delBtn = document.createElement('button');
delBtn.className = 'btn btn-danger';
delBtn.textContent = 'Delete';
delBtn.onclick = () => deleteUser(user.username);
actionsTd.appendChild(delBtn);
} else {
const span = document.createElement('span');
span.style.color = 'var(--text-muted)';
span.style.fontSize = '12px';
span.textContent = 'Protected';
actionsTd.appendChild(span);
}
tr.appendChild(actionsTd);
tbody.appendChild(tr);
}
function deleteUser(username) {
if (confirm(`Delete user "${username}"? All associated extractions will also be removed.`)) {
fetch('/api/admin/delete-user', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: username
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
showMessage('User deleted successfully.', 'success');
const row = document.querySelector(`#usersTableBody tr[data-username="${username}"]`);
if (row) row.remove();
const tbody = document.getElementById('usersTableBody');
if (!tbody.querySelector('tr')) {
document.getElementById('usersTable').style.display = 'none';
document.getElementById('usersEmptyState').style.display = '';
}
} else {
showMessage(data.message || 'Failed to delete user.', 'error');
}
})
.catch(error => {
showMessage('Error: ' + error.message, 'error');
});
}
}
function showMessage(message, type) {
const container = document.getElementById('messageContainer');
container.innerHTML = `<div class="message ${type}">${message}</div>`;
setTimeout(() => container.innerHTML = '', 5000);
}
</script>
</body>
</html>