feat: implement core backend API structure and frontend service layer for case management and authentication
This commit is contained in:
@@ -1,39 +1,101 @@
|
||||
// frontend/js/api.js
|
||||
// Base URL for backend API (adjust if using different host/port)
|
||||
const API_BASE = "http://localhost:5000/api";
|
||||
|
||||
function getHeaders() {
|
||||
const token = localStorage.getItem('token');
|
||||
const headers = { "Content-Type": "application/json" };
|
||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||
return headers;
|
||||
}
|
||||
|
||||
async function handleResponse(res) {
|
||||
if (res.status === 401) {
|
||||
localStorage.removeItem('token');
|
||||
window.location.reload();
|
||||
}
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || data.message || 'API Error');
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function login(username, password) {
|
||||
const res = await fetch(`${API_BASE}/auth/login`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
return await handleResponse(res);
|
||||
}
|
||||
|
||||
export async function register(username, password) {
|
||||
const res = await fetch(`${API_BASE}/auth/register`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
return await handleResponse(res);
|
||||
}
|
||||
|
||||
export async function getMe() {
|
||||
const res = await fetch(`${API_BASE}/auth/me`, { headers: getHeaders() });
|
||||
return await handleResponse(res);
|
||||
}
|
||||
|
||||
export async function upgradePlan() {
|
||||
const res = await fetch(`${API_BASE}/auth/upgrade`, {
|
||||
method: "POST",
|
||||
headers: getHeaders()
|
||||
});
|
||||
return await handleResponse(res);
|
||||
}
|
||||
|
||||
export async function getDashboardStats() {
|
||||
const res = await fetch(`${API_BASE}/dashboard/stats`, { headers: getHeaders() });
|
||||
return await handleResponse(res);
|
||||
}
|
||||
|
||||
export function getCaseReportPdfUrl(caseId) {
|
||||
const token = localStorage.getItem('token');
|
||||
return `${API_BASE}/reports/case/${caseId}/pdf?token=${token}`;
|
||||
}
|
||||
|
||||
export function getExportCsvUrl() {
|
||||
const token = localStorage.getItem('token');
|
||||
return `${API_BASE}/reports/cases/csv?token=${token}`;
|
||||
}
|
||||
|
||||
export async function fetchCases(params = {}) {
|
||||
const query = new URLSearchParams(params).toString();
|
||||
const res = await fetch(`${API_BASE}/cases${query ? `?${query}` : ''}`);
|
||||
return await res.json();
|
||||
const res = await fetch(`${API_BASE}/cases${query ? `?${query}` : ''}`, { headers: getHeaders() });
|
||||
return await handleResponse(res);
|
||||
}
|
||||
|
||||
export async function createCase(data) {
|
||||
const res = await fetch(`${API_BASE}/cases`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: getHeaders(),
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
return await res.json();
|
||||
return await handleResponse(res);
|
||||
}
|
||||
|
||||
export async function getCase(id) {
|
||||
const res = await fetch(`${API_BASE}/cases/${id}`);
|
||||
return await res.json();
|
||||
const res = await fetch(`${API_BASE}/cases/${id}`, { headers: getHeaders() });
|
||||
return await handleResponse(res);
|
||||
}
|
||||
|
||||
export async function updateCase(id, data) {
|
||||
const res = await fetch(`${API_BASE}/cases/${id}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: getHeaders(),
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
return await res.json();
|
||||
return await handleResponse(res);
|
||||
}
|
||||
|
||||
export async function deleteCase(id) {
|
||||
const res = await fetch(`${API_BASE}/cases/${id}`, { method: "DELETE" });
|
||||
return await res.json();
|
||||
const res = await fetch(`${API_BASE}/cases/${id}`, { method: "DELETE", headers: getHeaders() });
|
||||
return await handleResponse(res);
|
||||
}
|
||||
|
||||
export async function uploadFiles(caseId, fileList) {
|
||||
@@ -41,29 +103,32 @@ export async function uploadFiles(caseId, fileList) {
|
||||
for (const f of fileList) {
|
||||
form.append("files", f);
|
||||
}
|
||||
const headers = getHeaders();
|
||||
delete headers["Content-Type"]; // let browser set boundary
|
||||
const res = await fetch(`${API_BASE}/cases/${caseId}/files`, {
|
||||
method: "POST",
|
||||
headers: headers,
|
||||
body: form,
|
||||
});
|
||||
return await res.json();
|
||||
return await handleResponse(res);
|
||||
}
|
||||
|
||||
export async function listFiles(caseId) {
|
||||
const res = await fetch(`${API_BASE}/cases/${caseId}/files`);
|
||||
return await res.json();
|
||||
const res = await fetch(`${API_BASE}/cases/${caseId}/files`, { headers: getHeaders() });
|
||||
return await handleResponse(res);
|
||||
}
|
||||
|
||||
export async function getConfiguredPlatforms() {
|
||||
const res = await fetch(`${API_BASE}/credentials`);
|
||||
const data = await res.json();
|
||||
const res = await fetch(`${API_BASE}/credentials`, { headers: getHeaders() });
|
||||
const data = await handleResponse(res);
|
||||
return data.configured_platforms || [];
|
||||
}
|
||||
|
||||
export async function saveCredentials(platform, data) {
|
||||
const res = await fetch(`${API_BASE}/credentials/${platform}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: getHeaders(),
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
return await res.json();
|
||||
return await handleResponse(res);
|
||||
}
|
||||
|
||||
@@ -14,15 +14,156 @@ const PLATFORMS = [
|
||||
{ id: 'flowwow', name: 'Flowwow' }
|
||||
];
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
let currentUser = null;
|
||||
|
||||
document.addEventListener("DOMContentLoaded", async () => {
|
||||
initAuth();
|
||||
initReports();
|
||||
|
||||
// Check if logged in
|
||||
const token = localStorage.getItem('token');
|
||||
if (token) {
|
||||
try {
|
||||
currentUser = await api.getMe();
|
||||
const planBadge = currentUser.plan === 'pro' ? '<span style="color: gold;">[PRO]</span>' : '<span style="color: gray;">[FREE]</span>';
|
||||
document.getElementById('username-display').innerHTML = `Привет, ${currentUser.username} ${planBadge}`;
|
||||
showApp();
|
||||
} catch (e) {
|
||||
showAuth();
|
||||
}
|
||||
} else {
|
||||
showAuth();
|
||||
}
|
||||
});
|
||||
|
||||
let isLoginMode = true;
|
||||
function initAuth() {
|
||||
const authForm = document.getElementById('auth-form');
|
||||
const toggleBtn = document.getElementById('auth-toggle');
|
||||
const title = document.getElementById('auth-title');
|
||||
const logoutBtn = document.getElementById('logout-btn');
|
||||
|
||||
toggleBtn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
isLoginMode = !isLoginMode;
|
||||
title.textContent = isLoginMode ? 'Вход в систему' : 'Регистрация';
|
||||
toggleBtn.textContent = isLoginMode ? 'Нет аккаунта? Зарегистрироваться' : 'Уже есть аккаунт? Войти';
|
||||
});
|
||||
|
||||
authForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const username = document.getElementById('auth-username').value;
|
||||
const password = document.getElementById('auth-password').value;
|
||||
try {
|
||||
if (isLoginMode) {
|
||||
const res = await api.login(username, password);
|
||||
localStorage.setItem('token', res.token);
|
||||
} else {
|
||||
await api.register(username, password);
|
||||
alert('Регистрация успешна! Теперь вы можете войти.');
|
||||
isLoginMode = true;
|
||||
title.textContent = 'Вход в систему';
|
||||
toggleBtn.textContent = 'Нет аккаунта? Зарегистрироваться';
|
||||
return;
|
||||
}
|
||||
window.location.reload();
|
||||
} catch (err) {
|
||||
alert(err.message);
|
||||
}
|
||||
});
|
||||
|
||||
logoutBtn.addEventListener('click', () => {
|
||||
localStorage.removeItem('token');
|
||||
window.location.reload();
|
||||
});
|
||||
}
|
||||
|
||||
function showAuth() {
|
||||
document.getElementById('auth-section').classList.remove('hidden');
|
||||
document.getElementById('main-app').classList.add('hidden');
|
||||
document.getElementById('user-info').classList.add('hidden');
|
||||
}
|
||||
|
||||
function showApp() {
|
||||
document.getElementById('auth-section').classList.add('hidden');
|
||||
document.getElementById('main-app').classList.remove('hidden');
|
||||
document.getElementById('user-info').classList.remove('hidden');
|
||||
initTabs();
|
||||
initCases();
|
||||
initIntegrations();
|
||||
});
|
||||
initBilling();
|
||||
initDashboard();
|
||||
}
|
||||
|
||||
function initDashboard() {
|
||||
loadDashboard();
|
||||
}
|
||||
|
||||
async function loadDashboard() {
|
||||
try {
|
||||
const stats = await api.getDashboardStats();
|
||||
const grid = document.getElementById('stats-grid');
|
||||
grid.innerHTML = `
|
||||
<div class="platform-card">
|
||||
<h3>Всего кейсов</h3>
|
||||
<p style="font-size: 2rem; font-weight: bold;">${stats.total_cases}</p>
|
||||
</div>
|
||||
<div class="platform-card">
|
||||
<h3>Активных интеграций</h3>
|
||||
<p style="font-size: 2rem; font-weight: bold;">${stats.total_integrations}</p>
|
||||
<p style="font-size: 0.8rem;">${stats.platforms.join(', ').toUpperCase()}</p>
|
||||
</div>
|
||||
<div class="platform-card">
|
||||
<h3>В работе (Prepared/Sent)</h3>
|
||||
<p style="font-size: 2rem; font-weight: bold;">
|
||||
${(stats.cases_by_status.prepared || 0) + (stats.cases_by_status.sent || 0)}
|
||||
</p>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const tbody = document.querySelector('#recent-activity-table tbody');
|
||||
tbody.innerHTML = '';
|
||||
stats.recent_activity.forEach(a => {
|
||||
const tr = document.createElement('tr');
|
||||
const pName = PLATFORMS.find(p => p.id === a.platform)?.name || a.platform;
|
||||
tr.innerHTML = `
|
||||
<td>${a.id}</td>
|
||||
<td>${pName}</td>
|
||||
<td>${a.article}</td>
|
||||
<td>${a.status}</td>
|
||||
<td>${new Date(a.date).toLocaleDateString()}</td>
|
||||
`;
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
function initBilling() {
|
||||
document.getElementById('current-plan-display').textContent = currentUser.plan.toUpperCase();
|
||||
|
||||
document.getElementById('upgrade-btn').addEventListener('click', async () => {
|
||||
if(currentUser.plan === 'pro') {
|
||||
alert('У вас уже тариф PRO!');
|
||||
return;
|
||||
}
|
||||
|
||||
if(confirm('Перейти на PRO тариф (симуляция оплаты)?')) {
|
||||
try {
|
||||
await api.upgradePlan();
|
||||
alert('Оплата прошла успешно! Вы теперь PRO.');
|
||||
window.location.reload();
|
||||
} catch (err) {
|
||||
alert(err.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function initTabs() {
|
||||
const btns = document.querySelectorAll('.tab-btn');
|
||||
const sections = ['cases-section', 'integrations-section'];
|
||||
const sections = ['dashboard-section', 'cases-section', 'integrations-section', 'billing-section'];
|
||||
|
||||
btns.forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
@@ -31,12 +172,14 @@ function initTabs() {
|
||||
|
||||
const target = btn.dataset.target;
|
||||
sections.forEach(s => {
|
||||
document.getElementById(s).classList.add('hidden');
|
||||
const el = document.getElementById(s);
|
||||
if (el) el.classList.add('hidden');
|
||||
});
|
||||
document.getElementById(target).classList.remove('hidden');
|
||||
document.getElementById('case-form-section').classList.add('hidden');
|
||||
document.getElementById('case-detail-section').classList.add('hidden');
|
||||
|
||||
if(target === 'dashboard-section') loadDashboard();
|
||||
if(target === 'cases-section') loadCases();
|
||||
if(target === 'integrations-section') loadIntegrations();
|
||||
});
|
||||
@@ -71,9 +214,13 @@ async function loadIntegrations() {
|
||||
e.preventDefault();
|
||||
const formData = new FormData(e.target);
|
||||
const data = Object.fromEntries(formData);
|
||||
await api.saveCredentials(p.id, data);
|
||||
alert(`Настройки для ${p.name} сохранены!`);
|
||||
loadIntegrations();
|
||||
try {
|
||||
await api.saveCredentials(p.id, data);
|
||||
alert(`Настройки для ${p.name} сохранены!`);
|
||||
loadIntegrations();
|
||||
} catch(err) {
|
||||
alert(err.message);
|
||||
}
|
||||
});
|
||||
|
||||
grid.appendChild(card);
|
||||
@@ -130,9 +277,22 @@ async function initCases() {
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('export-csv-btn').addEventListener('click', () => {
|
||||
window.location.href = api.getExportCsvUrl();
|
||||
});
|
||||
|
||||
loadCases();
|
||||
}
|
||||
|
||||
let currentViewCaseId = null;
|
||||
async function initReports() {
|
||||
document.getElementById('download-pdf-btn').addEventListener('click', () => {
|
||||
if (currentViewCaseId) {
|
||||
window.location.href = api.getCaseReportPdfUrl(currentViewCaseId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function loadCases() {
|
||||
const article = document.getElementById('search-input').value;
|
||||
const status = document.getElementById('status-filter').value;
|
||||
@@ -171,6 +331,7 @@ async function loadCases() {
|
||||
}
|
||||
|
||||
window.viewCase = async function(id) {
|
||||
currentViewCaseId = id;
|
||||
document.getElementById('cases-section').classList.add('hidden');
|
||||
const detailSection = document.getElementById('case-detail-section');
|
||||
detailSection.classList.remove('hidden');
|
||||
|
||||
Reference in New Issue
Block a user