Add multi-tenant support with per-company data isolation
Implement full multi-company architecture:
- Per-company directory structure (data/companies/{id}/)
- Automatic migration from single-tenant to multi-tenant
- Company management admin tab (create, edit, delete companies)
- Per-company IMAP mailbox configuration (multiple mailboxes per company)
- User access control per company (companies array on users)
- Company switcher in header (shown when user has access to >1 company)
- Session-based company context with check_auth fallback for old sessions
- Ticket list shows mailbox name instead of sender
- IMAP settings moved from global config to company-specific config
- All data endpoints protected with requireCompany() guard
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
297
script.js
297
script.js
@@ -4,6 +4,8 @@ let sortField = 'yritys';
|
||||
let sortAsc = true;
|
||||
let currentDetailId = null;
|
||||
let currentUser = { username: '', nimi: '', role: '' };
|
||||
let currentCompany = null; // {id, nimi}
|
||||
let availableCompanies = []; // [{id, nimi}, ...]
|
||||
|
||||
// Elements
|
||||
const loginScreen = document.getElementById('login-screen');
|
||||
@@ -129,6 +131,8 @@ async function checkAuth() {
|
||||
const data = await apiCall('check_auth');
|
||||
if (data.authenticated) {
|
||||
currentUser = { username: data.username, nimi: data.nimi, role: data.role };
|
||||
availableCompanies = data.companies || [];
|
||||
currentCompany = availableCompanies.find(c => c.id === data.company_id) || availableCompanies[0] || null;
|
||||
showDashboard();
|
||||
}
|
||||
} catch (e) { /* not logged in */ }
|
||||
@@ -143,6 +147,8 @@ loginForm.addEventListener('submit', async (e) => {
|
||||
const data = await apiCall('login', 'POST', { username, password, captcha: parseInt(captcha) });
|
||||
loginError.style.display = 'none';
|
||||
currentUser = { username: data.username, nimi: data.nimi, role: data.role };
|
||||
availableCompanies = data.companies || [];
|
||||
currentCompany = availableCompanies.find(c => c.id === data.company_id) || availableCompanies[0] || null;
|
||||
showDashboard();
|
||||
} catch (err) {
|
||||
loginError.textContent = err.message;
|
||||
@@ -170,13 +176,38 @@ async function showDashboard() {
|
||||
// Näytä admin-toiminnot vain adminille
|
||||
document.getElementById('btn-users').style.display = currentUser.role === 'admin' ? '' : 'none';
|
||||
document.getElementById('tab-settings').style.display = currentUser.role === 'admin' ? '' : 'none';
|
||||
document.getElementById('tab-companies').style.display = currentUser.role === 'admin' ? '' : 'none';
|
||||
// Yritysvalitsin
|
||||
populateCompanySelector();
|
||||
// Avaa oikea tabi URL-hashin perusteella (tai customers oletuks)
|
||||
const hash = window.location.hash.replace('#', '');
|
||||
const validTabs = ['customers', 'leads', 'archive', 'changelog', 'support', 'users', 'settings'];
|
||||
const validTabs = ['customers', 'leads', 'archive', 'changelog', 'support', 'users', 'settings', 'companies'];
|
||||
const startTab = validTabs.includes(hash) ? hash : 'customers';
|
||||
switchToTab(startTab);
|
||||
}
|
||||
|
||||
function populateCompanySelector() {
|
||||
const sel = document.getElementById('company-selector');
|
||||
if (availableCompanies.length <= 1) {
|
||||
sel.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
sel.style.display = '';
|
||||
sel.innerHTML = availableCompanies.map(c =>
|
||||
`<option value="${c.id}" ${currentCompany && c.id === currentCompany.id ? 'selected' : ''}>${esc(c.nimi)}</option>`
|
||||
).join('');
|
||||
}
|
||||
|
||||
async function switchCompany(companyId) {
|
||||
try {
|
||||
await apiCall('company_switch', 'POST', { company_id: companyId });
|
||||
currentCompany = availableCompanies.find(c => c.id === companyId) || null;
|
||||
// Lataa uudelleen aktiivinen tab
|
||||
const hash = window.location.hash.replace('#', '') || 'customers';
|
||||
switchToTab(hash);
|
||||
} catch (e) { alert(e.message); }
|
||||
}
|
||||
|
||||
// ==================== TABS ====================
|
||||
|
||||
function switchToTab(target) {
|
||||
@@ -196,6 +227,7 @@ function switchToTab(target) {
|
||||
if (target === 'support') { loadTickets(); showTicketListView(); }
|
||||
if (target === 'users') loadUsers();
|
||||
if (target === 'settings') loadSettings();
|
||||
if (target === 'companies') loadCompaniesTab();
|
||||
}
|
||||
|
||||
document.querySelectorAll('.tab').forEach(tab => {
|
||||
@@ -915,6 +947,26 @@ function openUserForm(user = null) {
|
||||
document.getElementById('user-form-password').value = '';
|
||||
document.getElementById('user-pw-hint').textContent = user ? '(jätä tyhjäksi jos ei muuteta)' : '*';
|
||||
document.getElementById('user-form-role').value = user ? user.role : 'user';
|
||||
// Yrityscheckboxit
|
||||
const allComps = availableCompanies.length > 0 ? availableCompanies : [];
|
||||
const userComps = user ? (user.companies || []) : [];
|
||||
const container = document.getElementById('user-company-checkboxes');
|
||||
// Hae kaikki yritykset admin-näkymää varten
|
||||
apiCall('companies_all').then(companies => {
|
||||
container.innerHTML = companies.map(c =>
|
||||
`<label style="display:flex;align-items:center;gap:0.3rem;cursor:pointer;">
|
||||
<input type="checkbox" class="user-company-cb" value="${c.id}" ${userComps.includes(c.id) ? 'checked' : ''}>
|
||||
${esc(c.nimi)}
|
||||
</label>`
|
||||
).join('');
|
||||
}).catch(() => {
|
||||
container.innerHTML = allComps.map(c =>
|
||||
`<label style="display:flex;align-items:center;gap:0.3rem;cursor:pointer;">
|
||||
<input type="checkbox" class="user-company-cb" value="${c.id}" ${userComps.includes(c.id) ? 'checked' : ''}>
|
||||
${esc(c.nimi)}
|
||||
</label>`
|
||||
).join('');
|
||||
});
|
||||
userModal.style.display = 'flex';
|
||||
}
|
||||
|
||||
@@ -937,11 +989,13 @@ async function deleteUser(id, username) {
|
||||
document.getElementById('user-form').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const id = document.getElementById('user-form-id').value;
|
||||
const companies = [...document.querySelectorAll('.user-company-cb:checked')].map(cb => cb.value);
|
||||
const data = {
|
||||
username: document.getElementById('user-form-username').value,
|
||||
nimi: document.getElementById('user-form-nimi').value,
|
||||
email: document.getElementById('user-form-email').value,
|
||||
role: document.getElementById('user-form-role').value,
|
||||
companies,
|
||||
};
|
||||
const pw = document.getElementById('user-form-password').value;
|
||||
if (pw) data.password = pw;
|
||||
@@ -1037,7 +1091,7 @@ function renderTickets() {
|
||||
<td><span class="ticket-status ticket-status-${t.status}">${ticketStatusLabels[t.status] || t.status}</span></td>
|
||||
<td><span class="ticket-type ticket-type-${t.type || 'muu'}">${typeLabel}</span></td>
|
||||
<td><strong>${esc(t.subject)}</strong></td>
|
||||
<td>${esc(t.from_name || t.from_email)}</td>
|
||||
<td>${esc(t.mailbox_name || t.from_name || t.from_email)}</td>
|
||||
<td>${t.customer_name ? esc(t.customer_name) : '<span style="color:#ccc;">-</span>'}</td>
|
||||
<td>${(t.tags || []).length > 0 ? (t.tags || []).map(tag => '<span class="ticket-tag">#' + esc(tag) + '</span>').join(' ') : '<span style="color:#ccc;">-</span>'}</td>
|
||||
<td style="text-align:center;">${lastType} ${t.message_count}</td>
|
||||
@@ -1556,12 +1610,6 @@ async function loadSettings() {
|
||||
document.getElementById('settings-cors').value = (config.cors_origins || ['https://cuitunet.fi', 'https://www.cuitunet.fi']).join('\n');
|
||||
const key = config.api_key || 'AVAIN';
|
||||
document.getElementById('api-example-url').textContent = `api.php?action=saatavuus&key=${key}&osoite=Kauppakatu+5&postinumero=20100&kaupunki=Turku`;
|
||||
// IMAP settings
|
||||
document.getElementById('settings-imap-host').value = config.imap_host || '';
|
||||
document.getElementById('settings-imap-port').value = config.imap_port || 993;
|
||||
document.getElementById('settings-imap-user').value = config.imap_user || '';
|
||||
document.getElementById('settings-imap-password').value = config.imap_password || '';
|
||||
document.getElementById('settings-imap-encryption').value = config.imap_encryption || 'ssl';
|
||||
} catch (e) { console.error(e); }
|
||||
}
|
||||
|
||||
@@ -1578,11 +1626,6 @@ document.getElementById('btn-save-settings').addEventListener('click', async ()
|
||||
const config = await apiCall('config_update', 'POST', {
|
||||
api_key: document.getElementById('settings-api-key').value,
|
||||
cors_origins: document.getElementById('settings-cors').value,
|
||||
imap_host: document.getElementById('settings-imap-host').value,
|
||||
imap_port: document.getElementById('settings-imap-port').value,
|
||||
imap_user: document.getElementById('settings-imap-user').value,
|
||||
imap_password: document.getElementById('settings-imap-password').value,
|
||||
imap_encryption: document.getElementById('settings-imap-encryption').value,
|
||||
});
|
||||
alert('Asetukset tallennettu!');
|
||||
} catch (e) { alert(e.message); }
|
||||
@@ -1622,6 +1665,234 @@ document.addEventListener('keydown', (e) => {
|
||||
}
|
||||
});
|
||||
|
||||
// ==================== COMPANY SELECTOR ====================
|
||||
|
||||
document.getElementById('company-selector').addEventListener('change', function () {
|
||||
switchCompany(this.value);
|
||||
});
|
||||
|
||||
// ==================== YRITYKSET-TAB (admin) ====================
|
||||
|
||||
let companiesTabData = [];
|
||||
let currentCompanyDetail = null;
|
||||
|
||||
async function loadCompaniesTab() {
|
||||
try {
|
||||
companiesTabData = await apiCall('companies_all');
|
||||
renderCompaniesTable();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
// Fallback: käytä availableCompanies
|
||||
companiesTabData = availableCompanies;
|
||||
renderCompaniesTable();
|
||||
}
|
||||
}
|
||||
|
||||
function renderCompaniesTable() {
|
||||
const tbody = document.getElementById('companies-tbody');
|
||||
tbody.innerHTML = companiesTabData.map(c => `<tr>
|
||||
<td><code>${esc(c.id)}</code></td>
|
||||
<td><strong>${esc(c.nimi)}</strong></td>
|
||||
<td>-</td>
|
||||
<td class="nowrap">${esc((c.luotu || '').substring(0, 10))}</td>
|
||||
<td>${c.aktiivinen !== false ? '<span style="color:#22c55e;">Aktiivinen</span>' : '<span style="color:#888;">Ei aktiivinen</span>'}</td>
|
||||
<td>
|
||||
<button class="btn-link" onclick="showCompanyDetail('${c.id}')">Asetukset</button>
|
||||
<button class="btn-link" style="color:#dc2626;" onclick="deleteCompany('${c.id}','${esc(c.nimi)}')">Poista</button>
|
||||
</td>
|
||||
</tr>`).join('');
|
||||
document.getElementById('companies-list-view').style.display = '';
|
||||
document.getElementById('company-detail-view').style.display = 'none';
|
||||
}
|
||||
|
||||
document.getElementById('btn-add-company').addEventListener('click', () => {
|
||||
const nimi = prompt('Yrityksen nimi:');
|
||||
if (!nimi) return;
|
||||
const id = prompt('Yrityksen ID (pienillä kirjaimilla, a-z, 0-9, viiva sallittu):');
|
||||
if (!id) return;
|
||||
apiCall('company_create', 'POST', { id, nimi }).then(() => {
|
||||
loadCompaniesTab();
|
||||
// Päivitä myös company-selector
|
||||
apiCall('check_auth').then(data => {
|
||||
if (data.authenticated) {
|
||||
availableCompanies = data.companies || [];
|
||||
currentCompany = availableCompanies.find(c => c.id === data.company_id) || currentCompany;
|
||||
populateCompanySelector();
|
||||
}
|
||||
});
|
||||
}).catch(e => alert(e.message));
|
||||
});
|
||||
|
||||
async function deleteCompany(id, nimi) {
|
||||
if (!confirm(`Poistetaanko yritys "${nimi}"? Tämä poistaa pääsyn yrityksen dataan.`)) return;
|
||||
try {
|
||||
await apiCall('company_delete', 'POST', { id });
|
||||
loadCompaniesTab();
|
||||
// Päivitä selector
|
||||
availableCompanies = availableCompanies.filter(c => c.id !== id);
|
||||
if (currentCompany && currentCompany.id === id) {
|
||||
currentCompany = availableCompanies[0] || null;
|
||||
if (currentCompany) switchCompany(currentCompany.id);
|
||||
}
|
||||
populateCompanySelector();
|
||||
} catch (e) { alert(e.message); }
|
||||
}
|
||||
|
||||
async function showCompanyDetail(id) {
|
||||
currentCompanyDetail = id;
|
||||
document.getElementById('companies-list-view').style.display = 'none';
|
||||
document.getElementById('company-detail-view').style.display = '';
|
||||
const comp = companiesTabData.find(c => c.id === id);
|
||||
document.getElementById('company-detail-title').textContent = (comp ? comp.nimi : id) + ' — Asetukset';
|
||||
document.getElementById('company-edit-nimi').value = comp ? comp.nimi : '';
|
||||
|
||||
// Vaihda aktiivinen yritys jotta API-kutsut kohdistuvat oikein
|
||||
await apiCall('company_switch', 'POST', { company_id: id });
|
||||
|
||||
// Lataa postilaatikot
|
||||
loadMailboxes();
|
||||
// Lataa käyttäjäoikeudet
|
||||
loadCompanyUsers(id);
|
||||
}
|
||||
|
||||
document.getElementById('btn-company-back').addEventListener('click', () => {
|
||||
// Vaihda takaisin alkuperäiseen yritykseen
|
||||
if (currentCompany) apiCall('company_switch', 'POST', { company_id: currentCompany.id });
|
||||
renderCompaniesTable();
|
||||
});
|
||||
|
||||
document.getElementById('btn-save-company-name').addEventListener('click', async () => {
|
||||
const nimi = document.getElementById('company-edit-nimi').value.trim();
|
||||
if (!nimi) return;
|
||||
try {
|
||||
await apiCall('company_update', 'POST', { id: currentCompanyDetail, nimi });
|
||||
alert('Nimi tallennettu!');
|
||||
// Päivitä paikalliset tiedot
|
||||
const comp = companiesTabData.find(c => c.id === currentCompanyDetail);
|
||||
if (comp) comp.nimi = nimi;
|
||||
const avail = availableCompanies.find(c => c.id === currentCompanyDetail);
|
||||
if (avail) avail.nimi = nimi;
|
||||
populateCompanySelector();
|
||||
} catch (e) { alert(e.message); }
|
||||
});
|
||||
|
||||
// ==================== POSTILAATIKOT ====================
|
||||
|
||||
let mailboxesData = [];
|
||||
|
||||
async function loadMailboxes() {
|
||||
try {
|
||||
mailboxesData = await apiCall('mailboxes');
|
||||
renderMailboxes();
|
||||
} catch (e) { console.error(e); }
|
||||
}
|
||||
|
||||
function renderMailboxes() {
|
||||
const container = document.getElementById('mailboxes-list');
|
||||
if (mailboxesData.length === 0) {
|
||||
container.innerHTML = '<p style="color:#888;font-size:0.9rem;">Ei postilaatikoita. Lisää ensimmäinen postilaatikko.</p>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = mailboxesData.map(mb => `<div class="mailbox-item" style="display:flex;justify-content:space-between;align-items:center;padding:0.75rem;background:#fff;border:1px solid #e0e0e0;border-radius:8px;margin-bottom:0.5rem;">
|
||||
<div>
|
||||
<strong>${esc(mb.nimi)}</strong>
|
||||
<span style="color:#888;font-size:0.85rem;margin-left:0.75rem;">${esc(mb.imap_user)}</span>
|
||||
<span style="color:${mb.aktiivinen !== false ? '#22c55e' : '#888'};font-size:0.8rem;margin-left:0.5rem;">${mb.aktiivinen !== false ? 'Aktiivinen' : 'Ei aktiivinen'}</span>
|
||||
</div>
|
||||
<div style="display:flex;gap:0.5rem;">
|
||||
<button class="btn-link" onclick="editMailbox('${mb.id}')">Muokkaa</button>
|
||||
<button class="btn-link" style="color:#dc2626;" onclick="deleteMailbox('${mb.id}','${esc(mb.nimi)}')">Poista</button>
|
||||
</div>
|
||||
</div>`).join('');
|
||||
}
|
||||
|
||||
document.getElementById('btn-add-mailbox').addEventListener('click', () => {
|
||||
showMailboxForm();
|
||||
});
|
||||
|
||||
function showMailboxForm(mb = null) {
|
||||
document.getElementById('mailbox-form-title').textContent = mb ? 'Muokkaa postilaatikkoa' : 'Uusi postilaatikko';
|
||||
document.getElementById('mailbox-form-id').value = mb ? mb.id : '';
|
||||
document.getElementById('mailbox-form-nimi').value = mb ? mb.nimi : '';
|
||||
document.getElementById('mailbox-form-host').value = mb ? mb.imap_host : '';
|
||||
document.getElementById('mailbox-form-port').value = mb ? mb.imap_port : 993;
|
||||
document.getElementById('mailbox-form-user').value = mb ? mb.imap_user : '';
|
||||
document.getElementById('mailbox-form-password').value = mb ? mb.imap_password : '';
|
||||
document.getElementById('mailbox-form-encryption').value = mb ? (mb.imap_encryption || 'ssl') : 'ssl';
|
||||
document.getElementById('mailbox-form-smtp-email').value = mb ? (mb.smtp_from_email || '') : '';
|
||||
document.getElementById('mailbox-form-smtp-name').value = mb ? (mb.smtp_from_name || '') : '';
|
||||
document.getElementById('mailbox-form-container').style.display = '';
|
||||
}
|
||||
|
||||
function editMailbox(id) {
|
||||
const mb = mailboxesData.find(m => m.id === id);
|
||||
if (mb) showMailboxForm(mb);
|
||||
}
|
||||
|
||||
async function deleteMailbox(id, nimi) {
|
||||
if (!confirm(`Poistetaanko postilaatikko "${nimi}"?`)) return;
|
||||
try {
|
||||
await apiCall('mailbox_delete', 'POST', { id });
|
||||
loadMailboxes();
|
||||
} catch (e) { alert(e.message); }
|
||||
}
|
||||
|
||||
document.getElementById('btn-save-mailbox').addEventListener('click', async () => {
|
||||
const data = {
|
||||
id: document.getElementById('mailbox-form-id').value || undefined,
|
||||
nimi: document.getElementById('mailbox-form-nimi').value,
|
||||
imap_host: document.getElementById('mailbox-form-host').value,
|
||||
imap_port: parseInt(document.getElementById('mailbox-form-port').value) || 993,
|
||||
imap_user: document.getElementById('mailbox-form-user').value,
|
||||
imap_password: document.getElementById('mailbox-form-password').value,
|
||||
imap_encryption: document.getElementById('mailbox-form-encryption').value,
|
||||
smtp_from_email: document.getElementById('mailbox-form-smtp-email').value,
|
||||
smtp_from_name: document.getElementById('mailbox-form-smtp-name').value,
|
||||
aktiivinen: true,
|
||||
};
|
||||
try {
|
||||
await apiCall('mailbox_save', 'POST', data);
|
||||
document.getElementById('mailbox-form-container').style.display = 'none';
|
||||
loadMailboxes();
|
||||
} catch (e) { alert(e.message); }
|
||||
});
|
||||
|
||||
document.getElementById('btn-cancel-mailbox').addEventListener('click', () => {
|
||||
document.getElementById('mailbox-form-container').style.display = 'none';
|
||||
});
|
||||
|
||||
// ==================== YRITYKSEN KÄYTTÄJÄOIKEUDET ====================
|
||||
|
||||
async function loadCompanyUsers(companyId) {
|
||||
try {
|
||||
const users = await apiCall('users');
|
||||
const container = document.getElementById('company-users-list');
|
||||
container.innerHTML = users.map(u => {
|
||||
const hasAccess = (u.companies || []).includes(companyId);
|
||||
return `<label style="display:flex;align-items:center;gap:0.5rem;padding:0.4rem 0;cursor:pointer;">
|
||||
<input type="checkbox" class="company-user-cb" data-user-id="${u.id}" ${hasAccess ? 'checked' : ''} onchange="toggleCompanyUser('${u.id}','${companyId}',this.checked)">
|
||||
<strong>${esc(u.nimi || u.username)}</strong>
|
||||
<span style="color:#888;font-size:0.85rem;">(${u.username}) — ${u.role === 'admin' ? 'Ylläpitäjä' : 'Käyttäjä'}</span>
|
||||
</label>`;
|
||||
}).join('');
|
||||
} catch (e) { console.error(e); }
|
||||
}
|
||||
|
||||
async function toggleCompanyUser(userId, companyId, add) {
|
||||
try {
|
||||
const users = await apiCall('users');
|
||||
const user = users.find(u => u.id === userId);
|
||||
if (!user) return;
|
||||
let companies = user.companies || [];
|
||||
if (add && !companies.includes(companyId)) {
|
||||
companies.push(companyId);
|
||||
} else if (!add) {
|
||||
companies = companies.filter(c => c !== companyId);
|
||||
}
|
||||
await apiCall('user_update', 'POST', { id: userId, companies });
|
||||
} catch (e) { alert(e.message); }
|
||||
}
|
||||
|
||||
// Init
|
||||
loadCaptcha();
|
||||
checkAuth();
|
||||
|
||||
Reference in New Issue
Block a user