Files
MiauInv/frontend/assets/js/api.js

729 lines
28 KiB
JavaScript

// api.js
document.addEventListener("DOMContentLoaded", () => {
const profileBtn = document.getElementById('profile-btn');
const dropdownMenu = document.getElementById('dropdown-menu');
const menuBtn = document.getElementById('menu-btn');
const mainNav = document.getElementById('main-nav');
const logoutBtn = document.getElementById('logout-btn');
if (profileBtn && dropdownMenu) {
profileBtn.addEventListener('click', (e) => {
e.stopPropagation();
dropdownMenu.classList.toggle('show');
if (mainNav) mainNav.classList.remove('show');
});
}
if (menuBtn && mainNav) {
menuBtn.addEventListener('click', (e) => {
e.stopPropagation();
e.preventDefault();
mainNav.classList.toggle('show');
if (dropdownMenu) dropdownMenu.classList.remove('show');
});
}
logoutBtn.addEventListener('click', () => {
console.log("Logout")
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
document.cookie = "access_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;";
document.cookie = "refresh_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;";
});
document.addEventListener('click', () => {
if (dropdownMenu) dropdownMenu.classList.remove('show');
if (mainNav) mainNav.classList.remove('show');
});
if (document.getElementById('items-table-body')) loadItems();
if (document.getElementById('locations-table-body')) loadLocations();
if (document.getElementById('projects-table-body')) loadProjects();
if (document.getElementById('account-settings-content')) loadAccountSettings();
loadProfile();
});
function closeModal(id) {
document.getElementById(id).classList.remove('show');
}
async function apiRequest(endpoint, method = 'GET', body = null) {
const options = {
method,
headers: { 'Content-Type': 'application/json' }
};
if (body) options.body = JSON.stringify(body);
try {
const response = await fetch(endpoint, options);
if (!response.ok && response.status !== 204) {
const errText = await response.text();
throw new Error(errText || `HTTP Error ${response.status}`);
}
if (response.status === 204) return null;
return await response.json();
} catch (err) {
alert("Action failed: " + err.message);
throw err;
}
}
// ---- ITEMS ----
async function loadItems() {
const data = await apiRequest('/api/item');
const tbody = document.getElementById('items-table-body');
tbody.innerHTML = '';
if (!data.items || data.items.length === 0) {
tbody.innerHTML = '<tr><td colspan="4" style="text-align: center;">No items found.</td></tr>';
return;
}
data.items.forEach(item => {
tbody.innerHTML += `
<tr>
<td style="font-weight: 600;">${item.name}</td>
<td><span class="badge">${item.category}</span></td>
<td style="font-family: monospace; font-size: 1.05rem;">${item.total_quantity || 0}</td>
<td style="text-align: right;">
<button class="btn btn-secondary" style="width: auto; padding: 0.4rem 0.8rem; font-size: 0.85rem; border-color: var(--success); color: var(--success);" onclick='openStockModal(${JSON.stringify(item).replace(/'/g, "&#39;")})'>Stock</button>
<button class="btn btn-secondary" style="width: auto; padding: 0.4rem 0.8rem; font-size: 0.85rem;" onclick='editItem(${JSON.stringify(item).replace(/'/g, "&#39;")})'>Edit</button>
<button class="btn btn-secondary danger-btn" style="width: auto; padding: 0.4rem 0.8rem; font-size: 0.85rem;" onclick="deleteItem(${item.id})">Del</button>
</td>
</tr>
`;
});
}
function openItemModal() {
document.getElementById('item-form').reset();
document.getElementById('item-id').value = '';
document.getElementById('item-modal-title').innerText = 'New Item';
document.getElementById('item-modal').classList.add('show');
}
function editItem(item) {
document.getElementById('item-id').value = item.id;
document.getElementById('item-name').value = item.name;
document.getElementById('item-category').value = item.category;
document.getElementById('item-desc').value = item.description;
//document.getElementById('item-qty').value = item.total_quantity;
document.getElementById('item-modal-title').innerText = 'Edit Item';
document.getElementById('item-modal').classList.add('show');
}
async function saveItem(event) {
event.preventDefault();
const id = document.getElementById('item-id').value;
const payload = {
name: document.getElementById('item-name').value,
category: document.getElementById('item-category').value,
description: document.getElementById('item-desc').value,
//total_quantity: parseInt(document.getElementById('item-qty').value, 10)
};
const method = id ? 'PUT' : 'POST';
const endpoint = id ? `/api/item?id=${id}` : '/api/item';
await apiRequest(endpoint, method, payload);
closeModal('item-modal');
loadItems();
}
async function deleteItem(id) {
if (confirm("Are you sure you want to delete this item?")) {
await apiRequest(`/api/item?id=${id}`, 'DELETE');
loadItems();
}
}
// ---- LOCATIONS ----
async function loadLocations() {
const data = await apiRequest('/api/location');
const tbody = document.getElementById('locations-table-body');
tbody.innerHTML = '';
if (!data.locations || data.locations.length === 0) {
tbody.innerHTML = '<tr><td colspan="2" style="text-align: center;">No locations found.</td></tr>';
return;
}
data.locations.forEach(loc => {
tbody.innerHTML += `
<tr>
<td style="font-weight: 600;">${loc.name}</td>
<td style="text-align: right;">
<button class="btn btn-secondary" style="width: auto; padding: 0.4rem 0.8rem; font-size: 0.85rem;" onclick="editLocation(${loc.id}, '${loc.name}')">Edit</button>
<button class="btn btn-secondary danger-btn" style="width: auto; padding: 0.4rem 0.8rem; font-size: 0.85rem;" onclick="deleteLocation(${loc.id})">Delete</button>
</td>
</tr>
`;
});
}
function openLocationModal() {
document.getElementById('location-form').reset();
document.getElementById('location-id').value = '';
document.getElementById('location-modal-title').innerText = 'New Location';
document.getElementById('location-modal').classList.add('show');
}
function editLocation(id, name) {
document.getElementById('location-id').value = id;
document.getElementById('location-name').value = name;
document.getElementById('location-modal-title').innerText = 'Edit Location';
document.getElementById('location-modal').classList.add('show');
}
async function saveLocation(event) {
event.preventDefault();
const id = document.getElementById('location-id').value;
const payload = { name: document.getElementById('location-name').value };
const method = id ? 'PUT' : 'POST';
const endpoint = id ? `/api/location?id=${id}` : '/api/location';
await apiRequest(endpoint, method, payload);
closeModal('location-modal');
loadLocations();
}
async function deleteLocation(id) {
if (confirm("Are you sure you want to delete this location?")) {
await apiRequest(`/api/location?id=${id}`, 'DELETE');
loadLocations();
}
}
// ---- PROJECTS ----
async function loadProjects() {
const data = await apiRequest('/api/project');
const tbody = document.getElementById('projects-table-body');
tbody.innerHTML = '';
if (!data.projects || data.projects.length === 0) {
tbody.innerHTML = '<tr><td colspan="3" style="text-align: center;">No projects found.</td></tr>';
return;
}
data.projects.forEach(proj => {
tbody.innerHTML += `
<tr>
<td style="font-weight: 600;">${proj.name}</td>
<td style="color: var(--text-muted);">${proj.description}</td>
<td style="text-align: right;">
<button class="btn btn-secondary" style="width: auto; padding: 0.4rem 0.8rem; font-size: 0.85rem; border-color: var(--accent); color: var(--accent);" onclick='openAssociationModal(${JSON.stringify(proj).replace(/'/g, "&#39;")})'>Items</button>
<button class="btn btn-secondary" style="width: auto; padding: 0.4rem 0.8rem; font-size: 0.85rem;" onclick='editProject(${JSON.stringify(proj).replace(/'/g, "&#39;")})'>Edit</button>
<button class="btn btn-secondary danger-btn" style="width: auto; padding: 0.4rem 0.8rem; font-size: 0.85rem;" onclick="deleteProject(${proj.id})">Del</button>
</td>
</tr>
`;
});
}
function openProjectModal() {
document.getElementById('project-form').reset();
document.getElementById('project-id').value = '';
document.getElementById('project-modal-title').innerText = 'New Project';
document.getElementById('project-modal').classList.add('show');
}
function editProject(proj) {
document.getElementById('project-id').value = proj.id;
document.getElementById('project-name').value = proj.name;
document.getElementById('project-desc').value = proj.description;
document.getElementById('project-modal-title').innerText = 'Edit Project';
document.getElementById('project-modal').classList.add('show');
}
async function saveProject(event) {
event.preventDefault();
const id = document.getElementById('project-id').value;
const payload = {
name: document.getElementById('project-name').value,
description: document.getElementById('project-desc').value
};
const method = id ? 'PUT' : 'POST';
const endpoint = id ? `/api/project?id=${id}` : '/api/project';
await apiRequest(endpoint, method, payload);
closeModal('project-modal');
loadProjects();
}
async function deleteProject(id) {
if (confirm("Are you sure you want to delete this project?")) {
await apiRequest(`/api/project?id=${id}`, 'DELETE');
loadProjects();
}
}
// ---- STOCK ----
async function openStockModal(item) {
document.getElementById('stock-modal-title').innerText = `Stock: ${item.name}`;
document.getElementById('stock-item-id').value = item.id;
document.getElementById('stock-qty').value = '';
document.getElementById('stock-modal').classList.add('show');
await reloadStockTable(item.id);
const locData = await apiRequest('/api/location');
const locSelect = document.getElementById('stock-location');
locSelect.innerHTML = '<option value="">Select Location...</option>';
if (locData.locations) {
locData.locations.forEach(loc => {
locSelect.innerHTML += `<option value="${loc.id}">${loc.name}</option>`;
});
}
}
async function reloadStockTable(itemId) {
const tbody = document.getElementById('stock-table-body');
tbody.innerHTML = '<tr><td colspan="3" style="text-align:center;">Loading...</td></tr>';
try {
const data = await apiRequest(`/api/stock?item_id=${itemId}`);
tbody.innerHTML = '';
if (!data.stock || data.stock.length === 0) {
tbody.innerHTML = '<tr><td colspan="3" style="text-align: center;">No stock entries.</td></tr>';
return;
}
for (const st of data.stock) {
const locData = await apiRequest(`/api/location?id=${st.location_id}`);
tbody.innerHTML += `
<tr>
<td>${locData.name || `Location #${st.location_id}`}</td>
<td><span class="badge success">${st.quantity}</span></td>
<td style="text-align: right;">
<button class="btn btn-secondary danger-btn" style="padding: 0.2rem 0.5rem; font-size: 0.75rem;" onclick="deleteStock(${st.id}, ${itemId})">Del</button>
</td>
</tr>
`;
}
} catch (e) {
tbody.innerHTML = '<tr><td colspan="3" style="text-align: center;">Failed to load.</td></tr>';
}
}
async function saveStock(event) {
event.preventDefault();
const itemId = document.getElementById('stock-item-id').value;
const payload = {
item_id: parseInt(itemId, 10),
location_id: parseInt(document.getElementById('stock-location').value, 10),
quantity: parseInt(document.getElementById('stock-qty').value, 10)
};
await apiRequest('/api/stock', 'POST', payload);
document.getElementById('stock-qty').value = '';
await reloadStockTable(itemId);
loadItems();
}
async function deleteStock(stockId, itemId) {
if (confirm("Remove this stock entry?")) {
await apiRequest(`/api/stock?id=${stockId}`, 'DELETE');
await reloadStockTable(itemId);
loadItems();
}
}
// ---- ASSOCIATIONS ----
async function openAssociationModal(project) {
document.getElementById('association-modal-title').innerText = `Items for: ${project.name}`;
document.getElementById('assoc-project-id').value = project.id;
document.getElementById('assoc-qty').value = '';
document.getElementById('association-modal').classList.add('show');
await reloadAssociationTable(project.id);
const itemData = await apiRequest('/api/item');
const itemSelect = document.getElementById('assoc-item');
itemSelect.innerHTML = '<option value="">Select Item...</option>';
if (itemData.items) {
itemData.items.forEach(it => {
itemSelect.innerHTML += `<option value="${it.id}">${it.name} (Avail: ${it.total_quantity})</option>`;
});
}
}
async function reloadAssociationTable(projectId) {
const tbody = document.getElementById('association-table-body');
tbody.innerHTML = '<tr><td colspan="3" style="text-align:center;">Loading...</td></tr>';
try {
const data = await apiRequest(`/api/association?project_id=${projectId}`);
tbody.innerHTML = '';
if (!data.associations || data.associations.length === 0) {
tbody.innerHTML = '<tr><td colspan="3" style="text-align: center;">No allocated items.</td></tr>';
return;
}
for (const asc of data.associations) {
const itemData = await apiRequest(`/api/item?id=${asc.item_id}`);
console.log(itemData)
tbody.innerHTML += `
<tr>
<td>${itemData.name || `Item #${asc.item_id}`}</td>
<td><span class="badge success">${asc.quantity}</span></td>
<td style="text-align: right;">
<button class="btn btn-secondary danger-btn" style="padding: 0.2rem 0.5rem; font-size: 0.75rem;" onclick="deleteAssociation(${asc.id}, ${projectId})">Del</button>
</td>
</tr>
`;
}
} catch (e) {
tbody.innerHTML = '<tr><td colspan="3" style="text-align: center;">Failed to load.</td></tr>';
}
}
async function saveAssociation(event) {
event.preventDefault();
const projectId = document.getElementById('assoc-project-id').value;
const payload = {
project_id: parseInt(projectId, 10),
item_id: parseInt(document.getElementById('assoc-item').value, 10),
quantity: parseInt(document.getElementById('assoc-qty').value, 10)
};
await apiRequest('/api/association', 'POST', payload);
document.getElementById('assoc-qty').value = '';
await reloadAssociationTable(projectId);
}
async function deleteAssociation(assocId, projectId) {
if (confirm("Remove this item from the project?")) {
await apiRequest(`/api/association?id=${assocId}`, 'DELETE');
await reloadAssociationTable(projectId);
}
}
async function handleDashboardView() {
const locTbody = document.getElementById('dash-locations-body');
const projTbody = document.getElementById('dash-projects-body');
if (!locTbody && !projTbody) return;
try {
const locData = await apiRequest('/api/location');
if (locTbody && locData && locData.locations) {
locTbody.innerHTML = '';
if (locData.locations.length === 0) {
locTbody.innerHTML = '<tr><td style="color: var(--text-muted); padding: 1rem;">No locations found.</td></tr>';
} else {
locData.locations.forEach(loc => {
const tr = document.createElement('tr');
tr.innerHTML = `<td style="cursor: pointer; color: var(--accent); font-weight: 500; padding: 0.75rem 1rem;">${loc.name}</td>`;
tr.onclick = () => openDashboardModal(`/api/location?id=${loc.id}&content=true`, `Items in ${loc.name}`, 'contents');
locTbody.appendChild(tr);
});
}
}
const projData = await apiRequest('/api/project');
if (projTbody && projData && projData.projects) {
projTbody.innerHTML = '';
if (projData.projects.length === 0) {
projTbody.innerHTML = '<tr><td style="color: var(--text-muted); padding: 1rem;">No projects found.</td></tr>';
} else {
projData.projects.forEach(p => {
const tr = document.createElement('tr');
tr.innerHTML = `<td style="cursor: pointer; color: var(--accent); font-weight: 500; padding: 0.75rem 1rem;">${p.name}</td>`;
tr.onclick = () => openDashboardModal(`/api/project?id=${p.id}&details=true`, `Items assigned to ${p.name}`, 'items');
projTbody.appendChild(tr);
});
}
}
} catch (err) {
console.error(err);
}
}
async function openDashboardModal(url, title, dataKey) {
document.getElementById('dash-modal-title').innerText = title;
const tbody = document.getElementById('dash-modal-body');
if (!tbody) return;
tbody.innerHTML = '<tr><td colspan="2" style="text-align:center; padding:1.5rem; color:var(--text-muted);">Loading...</td></tr>';
document.getElementById('dash-details-modal').classList.add('show');
try {
const data = await apiRequest(url);
tbody.innerHTML = '';
const list = data[dataKey] || [];
if (list.length === 0) {
tbody.innerHTML = '<tr><td colspan="2" style="color:var(--text-muted); text-align:center; padding:1.5rem;">No active items found.</td></tr>';
return;
}
list.forEach(i => {
tbody.innerHTML += `
<tr>
<td style="color:var(--text); padding:0.75rem 1rem;">${i.item_name}</td>
<td style="text-align:right; padding:0.75rem 1rem;"><span class="badge success">${i.quantity}</span></td>
</tr>
`;
});
} catch (e) {
tbody.innerHTML = '<tr><td colspan="2" style="color:var(--error); text-align:center; padding:1.5rem;">Failed to load data.</td></tr>';
}
}
// ---- PROFILE ----
async function loadProfile() {
const avatar = document.getElementById("avatar");
const username = document.getElementById('username');
try {
const data = await apiRequest('/api/profile');
avatar.innerText = data.username[0].toLocaleUpperCase();
username.innerText = data.username;
} catch (e) {
username.innerHTML = '<tr><td colspan="2" style="color:var(--error); text-align:center; padding:1.5rem;">Failed to load data.</td></tr>';
}
}
// ---- ACCOUNT SETTINGS ----
let latestRecoveryCodes = [];
function showAccountSettingsMessage(message, type = 'success') {
const box = document.getElementById('account-settings-message');
if (!box) return;
box.textContent = message;
box.className = `message ${type}`;
box.style.display = 'block';
}
function setTwoFactorPanels(enabled) {
const badge = document.getElementById('two-factor-badge');
const status = document.getElementById('two-factor-status');
const disabledPanel = document.getElementById('two-factor-disabled-panel');
const enabledPanel = document.getElementById('two-factor-enabled-panel');
if (!badge || !status || !disabledPanel || !enabledPanel) return;
if (enabled) {
badge.textContent = 'Enabled';
badge.classList.add('success');
status.textContent = '2FA is enabled for your account.';
disabledPanel.style.display = 'none';
enabledPanel.style.display = 'block';
} else {
badge.textContent = 'Disabled';
badge.classList.remove('success');
status.textContent = '2FA is disabled. Enable it to protect your account with an authenticator app.';
disabledPanel.style.display = 'block';
enabledPanel.style.display = 'none';
}
}
function renderRecoveryCodes(codes) {
latestRecoveryCodes = codes || [];
const panel = document.getElementById('recovery-codes-panel');
const list = document.getElementById('recovery-codes-list');
if (!panel || !list) return;
if (latestRecoveryCodes.length === 0) {
panel.style.display = 'none';
list.textContent = '';
return;
}
list.textContent = latestRecoveryCodes.join('\n');
panel.style.display = 'block';
}
async function loadAccountSettings() {
try {
const data = await apiRequest('/api/profile');
const usernameInput = document.getElementById('settings-username');
const avatarPreview = document.getElementById('settings-avatar-preview');
const remaining = document.getElementById('recovery-codes-remaining');
if (usernameInput) usernameInput.value = data.username || '';
if (avatarPreview && data.username) avatarPreview.innerText = data.username[0].toLocaleUpperCase();
if (remaining) remaining.innerText = data.recovery_codes_remaining || 0;
setTwoFactorPanels(!!data.two_factor_enabled);
renderRecoveryCodes([]);
} catch (err) {
showAccountSettingsMessage(err.message || 'Failed to load account settings.', 'error');
}
}
async function saveAccountUsername(event) {
event.preventDefault();
try {
const data = await apiRequest('/api/account/username', 'POST', {
username: document.getElementById('settings-username').value.trim(),
password: document.getElementById('settings-username-password').value
});
document.getElementById('settings-username-password').value = '';
showAccountSettingsMessage('Username updated.');
const username = document.getElementById('username');
const avatar = document.getElementById('avatar');
const avatarPreview = document.getElementById('settings-avatar-preview');
if (username) username.innerText = data.username;
if (avatar && data.username) avatar.innerText = data.username[0].toLocaleUpperCase();
if (avatarPreview && data.username) avatarPreview.innerText = data.username[0].toLocaleUpperCase();
} catch (err) {
showAccountSettingsMessage(err.message || 'Could not update username.', 'error');
}
}
async function saveAccountPassword(event) {
event.preventDefault();
const currentPassword = document.getElementById('settings-current-password').value;
const newPassword = document.getElementById('settings-new-password').value;
const confirmPassword = document.getElementById('settings-confirm-password').value;
if (newPassword !== confirmPassword) {
showAccountSettingsMessage('New passwords do not match.', 'error');
return;
}
try {
const data = await apiRequest('/api/account/password', 'POST', {
current_password: currentPassword,
new_password: newPassword
});
if (data && data.access_token && data.refresh_token) {
localStorage.setItem('access_token', data.access_token);
localStorage.setItem('refresh_token', data.refresh_token);
}
document.getElementById('password-form').reset();
showAccountSettingsMessage('Password updated. Your session was refreshed.');
} catch (err) {
showAccountSettingsMessage(err.message || 'Could not update password.', 'error');
}
}
async function startTwoFactorSetup() {
try {
const data = await apiRequest('/api/2fa/setup', 'POST');
const panel = document.getElementById('two-factor-setup-panel');
const qr = document.getElementById('two-factor-qr');
const secret = document.getElementById('two-factor-secret');
const otpauth = document.getElementById('two-factor-otpauth');
if (panel) panel.style.display = 'block';
if (qr) {
qr.src = data.qr_code;
qr.style.display = data.qr_code ? 'block' : 'none';
}
if (secret) secret.textContent = data.secret || '';
if (otpauth) {
otpauth.href = data.otpauth_url || '#';
otpauth.textContent = data.otpauth_url || 'No otpauth URL available';
}
showAccountSettingsMessage('Scan the QR code or enter the setup key manually, then confirm the 6-digit code.');
} catch (err) {
showAccountSettingsMessage(err.message || 'Could not start 2FA setup.', 'error');
}
}
async function enableTwoFactor(event) {
event.preventDefault();
try {
const data = await apiRequest('/api/2fa/enable', 'POST', {
code: document.getElementById('two-factor-enable-code').value.trim()
});
document.getElementById('two-factor-enable-form').reset();
document.getElementById('two-factor-setup-panel').style.display = 'none';
setTwoFactorPanels(true);
renderRecoveryCodes(data.recovery_codes || []);
const remaining = document.getElementById('recovery-codes-remaining');
if (remaining) remaining.innerText = (data.recovery_codes || []).length;
showAccountSettingsMessage('2FA enabled. Download your recovery codes now.');
loadProfile();
} catch (err) {
showAccountSettingsMessage(err.message || 'Could not enable 2FA.', 'error');
}
}
async function disableTwoFactor(event) {
event.preventDefault();
if (!confirm('Disable 2FA for your account?')) return;
try {
await apiRequest('/api/2fa/disable', 'POST', {
password: document.getElementById('two-factor-disable-password').value,
code: document.getElementById('two-factor-disable-code').value.trim()
});
document.getElementById('two-factor-disable-form').reset();
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
setTwoFactorPanels(false);
renderRecoveryCodes([]);
showAccountSettingsMessage('2FA disabled. Redirecting to login because sessions were revoked.');
setTimeout(() => {
window.location.href = '/login';
}, 1200);
} catch (err) {
showAccountSettingsMessage(err.message || 'Could not disable 2FA.', 'error');
}
}
async function regenerateRecoveryCodes(event) {
event.preventDefault();
if (!confirm('Generate new recovery codes? Existing unused codes will stop working.')) return;
try {
const data = await apiRequest('/api/2fa/recovery-codes/regenerate', 'POST', {
password: document.getElementById('recovery-password').value,
code: document.getElementById('recovery-code').value.trim()
});
document.getElementById('recovery-regenerate-form').reset();
renderRecoveryCodes(data.recovery_codes || []);
const remaining = document.getElementById('recovery-codes-remaining');
if (remaining) remaining.innerText = (data.recovery_codes || []).length;
showAccountSettingsMessage('New recovery codes generated. Download them now.');
} catch (err) {
showAccountSettingsMessage(err.message || 'Could not regenerate recovery codes.', 'error');
}
}
function downloadRecoveryCodes() {
if (!latestRecoveryCodes || latestRecoveryCodes.length === 0) {
showAccountSettingsMessage('No recovery codes available to download.', 'error');
return;
}
const text = [
'MiauInv recovery codes',
'Save these somewhere safe. Each code can be used once.',
'',
...latestRecoveryCodes,
''
].join('\n');
const blob = new Blob([text], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'miauinv-recovery-codes.txt';
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
}