feat: student achievements (admin-managed types + per-student records, UI & backup)
This commit is contained in:
+161
-1
@@ -1,6 +1,6 @@
|
||||
const DIRTY_FIELDS = ['systemName', 'timezone', 'timeFormat', 'spamInterval', 'footerLeft', 'footerRight', 'aiPrompt', 'aiAutoCheck', 'lessonAiPrompt', 'lessonAiEnabled', 'notesAiEnabled', 'shareShowMessage', 'shareShowDate', 'shareShowNames', 'shareShowPhotos', 'cookieNoticeText', 'photoResolution', 'photoQuality', 'photoEngine', 'camEnabled', 'photoAiFaceMode', 'photoAiFaceModel', 'photoAiDevicePref', 'trashPurgeDays', 'notifyEnabled', 'notifyRetentionDays'];
|
||||
const NOTIFY_IDS = [];
|
||||
const SECTION_IDS = ['sec-system', 'sec-stack', 'sec-brand', 'sec-datetime', 'sec-antispam', 'sec-share', 'sec-ai', 'sec-lesson-ai', 'sec-notes-ai', 'sec-tls', 'sec-backup', 'sec-trash', 'sec-form', 'sec-notify', 'sec-photo', 'sec-photo-ai', 'sec-bans'];
|
||||
const SECTION_IDS = ['sec-system', 'sec-stack', 'sec-brand', 'sec-datetime', 'sec-antispam', 'sec-share', 'sec-ai', 'sec-lesson-ai', 'sec-notes-ai', 'sec-achievements', 'sec-tls', 'sec-backup', 'sec-trash', 'sec-form', 'sec-notify', 'sec-photo', 'sec-photo-ai', 'sec-bans'];
|
||||
const SPAM_MAX = 10080;
|
||||
const BAN_REASONS = {
|
||||
'honeypot': 'Антиспам-поле',
|
||||
@@ -1479,6 +1479,165 @@ window.addEventListener('beforeunload', e => {
|
||||
}
|
||||
});
|
||||
|
||||
let seAchTypes = [];
|
||||
|
||||
function seAchRowHtml(t) {
|
||||
return `<div class="se-ach-row${t.is_active ? '' : ' is-off'}" data-id="${t.id}">
|
||||
<span class="se-ach-drag" draggable="true" title="Перетащите, чтобы изменить порядок">⠿</span>
|
||||
<button type="button" class="se-ach-on${t.is_active ? ' on' : ''}" data-ach-on title="${t.is_active ? 'Скрыть из выбора при добавлении' : 'Вернуть в выбор'}">${t.is_active ? 'Вкл' : 'Выкл'}</button>
|
||||
<span class="se-ach-name">${esc(t.name)}</span>
|
||||
<button type="button" class="se-ach-btn" data-ach-edit title="Переименовать"><i data-lucide="pencil"></i></button>
|
||||
<button type="button" class="se-ach-btn danger" data-ach-del title="Удалить"><i data-lucide="trash-2"></i></button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function seAchRender() {
|
||||
const list = document.getElementById('seAchList');
|
||||
if (!list) return;
|
||||
list.innerHTML = seAchTypes.length ? seAchTypes.map(seAchRowHtml).join('') : '<div class="se-ach-empty">Типов пока нет — добавьте первый выше</div>';
|
||||
renderIcons();
|
||||
}
|
||||
|
||||
function seAchApi(url, body, method) {
|
||||
return fetch(url, {
|
||||
method: method || (body ? 'POST' : 'GET'),
|
||||
headers: body ? { ...hdr(), 'Content-Type': 'application/json' } : hdr(),
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
}).then(res => res.json().then(data => {
|
||||
if (!res.ok) throw new Error(data.error || 'Ошибка');
|
||||
return data;
|
||||
}));
|
||||
}
|
||||
|
||||
async function seAchLoad() {
|
||||
try {
|
||||
const data = await seAchApi(`${API}/api/achievement-types`);
|
||||
seAchTypes = Array.isArray(data.items) ? data.items : [];
|
||||
} catch {
|
||||
seAchTypes = [];
|
||||
}
|
||||
seAchRender();
|
||||
}
|
||||
|
||||
async function seAchPersistOrder(ids) {
|
||||
const oldIds = seAchTypes.map(t => t.id);
|
||||
if (oldIds.join() === ids.join()) { seAchRender(); return; }
|
||||
try {
|
||||
await seAchApi(`${API}/api/achievement-types/reorder`, { ids }, 'PUT');
|
||||
seAchTypes.sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id));
|
||||
seAchRender();
|
||||
} catch (err) {
|
||||
showToast(err.message || 'Не удалось сохранить порядок', true);
|
||||
await seAchLoad();
|
||||
}
|
||||
}
|
||||
|
||||
async function initAchievementTypes() {
|
||||
if (!document.getElementById('seAchList')) return;
|
||||
const box = document.getElementById('seAchList');
|
||||
let seAchDragged = null;
|
||||
box.addEventListener('dragstart', e => {
|
||||
const row = e.target.closest('.se-ach-row');
|
||||
if (!row) return;
|
||||
seAchDragged = row;
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
try { e.dataTransfer.setData('text/plain', row.dataset.id); } catch {}
|
||||
});
|
||||
box.addEventListener('dragover', e => {
|
||||
if (!seAchDragged) return;
|
||||
e.preventDefault();
|
||||
const row = e.target.closest('.se-ach-row');
|
||||
if (!row || row === seAchDragged) return;
|
||||
const rect = row.getBoundingClientRect();
|
||||
box.insertBefore(seAchDragged, e.clientY < rect.top + rect.height / 2 ? row : row.nextSibling);
|
||||
});
|
||||
box.addEventListener('drop', e => e.preventDefault());
|
||||
box.addEventListener('dragend', () => {
|
||||
if (!seAchDragged) return;
|
||||
const ids = [...box.querySelectorAll('.se-ach-row')].map(r => Number(r.dataset.id));
|
||||
seAchDragged = null;
|
||||
seAchPersistOrder(ids);
|
||||
});
|
||||
box.addEventListener('click', async e => {
|
||||
const row = e.target.closest('.se-ach-row');
|
||||
if (!row) return;
|
||||
const cur = seAchTypes.find(t => String(t.id) === String(row.dataset.id));
|
||||
if (!cur) return;
|
||||
const editBtn = e.target.closest('[data-ach-edit]');
|
||||
if (editBtn) {
|
||||
const nameEl = row.querySelector('.se-ach-name');
|
||||
const input = document.createElement('input');
|
||||
input.className = 'se-ach-name-input';
|
||||
input.value = cur.name;
|
||||
input.maxLength = 150;
|
||||
nameEl.replaceWith(input);
|
||||
input.focus();
|
||||
input.select();
|
||||
let done = false;
|
||||
const finish = save => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
const val = input.value.trim();
|
||||
if (!save || !val || val === cur.name) { seAchRender(); return; }
|
||||
seAchApi(`${API}/api/achievement-types/${cur.id}`, { name: val, is_active: cur.is_active }, 'PUT')
|
||||
.then(data => { cur.name = data.item.name; cur.is_active = data.item.is_active; showToast('Тип переименован'); seAchRender(); })
|
||||
.catch(err => { showToast(err.message || 'Не удалось переименовать', true); seAchRender(); });
|
||||
};
|
||||
input.addEventListener('keydown', ev => {
|
||||
if (ev.key === 'Enter') { ev.preventDefault(); finish(true); }
|
||||
if (ev.key === 'Escape') { ev.preventDefault(); finish(false); }
|
||||
});
|
||||
input.addEventListener('blur', () => finish(true));
|
||||
return;
|
||||
}
|
||||
const on = e.target.closest('[data-ach-on]');
|
||||
if (on) {
|
||||
try {
|
||||
const data = await seAchApi(`${API}/api/achievement-types/${cur.id}`, { name: cur.name, is_active: !cur.is_active }, 'PUT');
|
||||
Object.assign(cur, data.item);
|
||||
seAchRender();
|
||||
showToast(cur.is_active ? 'Тип снова доступен' : 'Тип скрыт из выбора');
|
||||
} catch (err) {
|
||||
showToast(err.message || 'Не удалось изменить тип', true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const del = e.target.closest('[data-ach-del]');
|
||||
if (del) {
|
||||
if (!confirm(`Удалить тип «${cur.name}»? Уже внесённые достижения сохранят его название`)) return;
|
||||
try {
|
||||
await seAchApi(`${API}/api/achievement-types/${cur.id}`, null, 'DELETE');
|
||||
seAchTypes = seAchTypes.filter(t => t.id !== cur.id);
|
||||
seAchRender();
|
||||
showToast('Тип удалён');
|
||||
} catch (err) {
|
||||
showToast(err.message || 'Не удалось удалить тип', true);
|
||||
}
|
||||
}
|
||||
});
|
||||
document.getElementById('seAchAddBtn').addEventListener('click', async () => {
|
||||
const input = document.getElementById('seAchNewName');
|
||||
const name = input.value.trim();
|
||||
if (!name) { showToast('Введите название типа', true); return; }
|
||||
try {
|
||||
const data = await seAchApi(`${API}/api/achievement-types`, { name });
|
||||
seAchTypes.unshift(data.item);
|
||||
input.value = '';
|
||||
seAchRender();
|
||||
showToast('Тип добавлен');
|
||||
} catch (err) {
|
||||
showToast(err.message || 'Не удалось добавить тип', true);
|
||||
}
|
||||
});
|
||||
document.getElementById('seAchNewName').addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
document.getElementById('seAchAddBtn').click();
|
||||
}
|
||||
});
|
||||
await seAchLoad();
|
||||
}
|
||||
|
||||
(async () => {
|
||||
if (await requireAdminPage()) {
|
||||
buildSidebar(document.body.dataset.page);
|
||||
@@ -1493,6 +1652,7 @@ window.addEventListener('beforeunload', e => {
|
||||
} catch {
|
||||
if (authStatus) { authStatus.classList.remove('loaded'); authStatus.classList.add('err'); authStatus.textContent = 'Ошибка загрузки настроек'; }
|
||||
}
|
||||
initAchievementTypes();
|
||||
loadBans();
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -6,9 +6,13 @@
|
||||
let activeTab = 'entries';
|
||||
let facesLoaded = false;
|
||||
let facesData = null;
|
||||
let achTypes = [];
|
||||
let achTypesLoaded = false;
|
||||
let achEditId = null;
|
||||
|
||||
const TABS = [
|
||||
{ key: 'entries', label: 'Журнал', icon: 'book-open' },
|
||||
{ key: 'ach', label: 'Достижения', icon: 'trophy' },
|
||||
{ key: 'shorts', label: 'Короткие сообщения', icon: 'zap' },
|
||||
{ key: 'feedbacks', label: 'Обратная связь', icon: 'message-square-heart' },
|
||||
{ key: 'photos', label: 'Фото', icon: 'image' },
|
||||
@@ -82,8 +86,15 @@
|
||||
</button>`;
|
||||
}
|
||||
|
||||
function achCount() {
|
||||
if (!data.achievements) return 0;
|
||||
if (typeof data.achievements.total === 'number') return data.achievements.total;
|
||||
return (data.achievements.items || []).length;
|
||||
}
|
||||
|
||||
function tabCount(key) {
|
||||
if (key === 'entries') return data.entries.total;
|
||||
if (key === 'ach') return achCount();
|
||||
if (key === 'shorts') return data.shorts.total;
|
||||
if (key === 'feedbacks') return data.feedbacks.total;
|
||||
if (key === 'photos') return data.photos.items.length + (data.photos.photo_path ? 1 : 0);
|
||||
@@ -235,6 +246,10 @@
|
||||
pane.innerHTML = facesHtml();
|
||||
} else if (activeTab === 'entries') {
|
||||
pane.innerHTML = entriesHtml();
|
||||
} else if (activeTab === 'ach') {
|
||||
ensureAchTypes();
|
||||
pane.innerHTML = achievementsHtml();
|
||||
bindAch();
|
||||
} else if (activeTab === 'shorts') {
|
||||
pane.innerHTML = shortsHtml();
|
||||
} else if (activeTab === 'feedbacks') {
|
||||
@@ -256,6 +271,166 @@
|
||||
if (activeTab === 'faces') renderPane();
|
||||
}
|
||||
|
||||
function achItemHtml(a) {
|
||||
return `<div class="sp-ach-item" data-ach-id="${a.id}">
|
||||
<div class="sp-ach-top">
|
||||
<span class="sp-ach-type"><i data-lucide="trophy"></i> ${esc(a.type_name)}</span>
|
||||
${a.value ? `<span class="sp-ach-value">${esc(a.value)}</span>` : ''}
|
||||
<span class="sp-ach-date">
|
||||
${a.achieved_at ? esc(fmtDateIso(a.achieved_at)) : ''}
|
||||
<button type="button" class="icon-btn" data-ach-edit="${a.id}" title="Редактировать"><i data-lucide="pencil"></i></button>
|
||||
<button type="button" class="icon-btn danger" data-ach-del="${a.id}" title="Удалить"><i data-lucide="trash-2"></i></button>
|
||||
</span>
|
||||
</div>
|
||||
${a.note ? `<div class="sp-ach-note">${esc(a.note)}</div>` : ''}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function achFormHtml() {
|
||||
return `<form class="sp-ach-form" id="spAchForm" hidden>
|
||||
<select id="spAchType"></select>
|
||||
<input id="spAchValue" maxlength="200" placeholder="Результат: 271 знак/мин, 1 место">
|
||||
<input type="date" id="spAchDate">
|
||||
<textarea id="spAchNote" maxlength="800" rows="2" placeholder="Комментарий (необязательно)"></textarea>
|
||||
<div class="sp-ach-acts">
|
||||
<button type="button" class="btn-primary ghost" id="spAchCancelBtn">Отмена</button>
|
||||
<button type="submit" class="btn-primary" id="spAchSaveBtn">Сохранить</button>
|
||||
</div>
|
||||
</form>`;
|
||||
}
|
||||
|
||||
function achievementsHtml() {
|
||||
const list = (data.achievements && data.achievements.items) || [];
|
||||
return `<div class="sp-ach-head">
|
||||
<button type="button" class="btn-link" id="spAchAddBtn"><i data-lucide="plus"></i> Добавить достижение</button>
|
||||
${achTypesLoaded ? (achTypes.length ? '<span class="sp-ach-hint">Типы достижений настраивает администратор (Настройки → Достижения)</span>' : '<span class="sp-ach-hint">Администратор ещё не добавил типы — он делает это в Настройки → Достижения</span>') : ''}
|
||||
</div>${achFormHtml()}${list.length ? `<div class="sp-ach-list" id="spAchList">${list.map(achItemHtml).join('')}</div>` : emptyHtml('Достижений пока нет')}`;
|
||||
}
|
||||
|
||||
function achTypeForm(selected) {
|
||||
const act = achTypes.filter(t => t.is_active);
|
||||
const a = v => esc(String(v)).replace(/"/g, '"');
|
||||
const opts = ['<option value="">Выберите тип…</option>']
|
||||
.concat(act.map(t => `<option value="${a(t.name)}"${selected === t.name ? ' selected' : ''}>${esc(t.name)}</option>`));
|
||||
if (selected && !act.some(t => t.name === selected)) {
|
||||
opts.push(`<option value="${a(selected)}" selected>${esc(selected)} (недоступен)</option>`);
|
||||
}
|
||||
return opts.join('');
|
||||
}
|
||||
|
||||
function achFormOpen(rec) {
|
||||
const form = document.getElementById('spAchForm');
|
||||
if (!form) return;
|
||||
achEditId = rec ? rec.id : null;
|
||||
document.getElementById('spAchType').innerHTML = achTypeForm(rec ? rec.type_name : '');
|
||||
document.getElementById('spAchValue').value = rec ? (rec.value || '') : '';
|
||||
document.getElementById('spAchDate').value = rec ? (rec.achieved_at || '') : todayIso();
|
||||
document.getElementById('spAchNote').value = rec ? (rec.note || '') : '';
|
||||
form.hidden = false;
|
||||
document.getElementById('spAchType').focus();
|
||||
}
|
||||
|
||||
function achFormClose() {
|
||||
const form = document.getElementById('spAchForm');
|
||||
if (form) form.hidden = true;
|
||||
achEditId = null;
|
||||
}
|
||||
|
||||
async function ensureAchTypes() {
|
||||
if (achTypesLoaded) return;
|
||||
try {
|
||||
const res = await fetch(`${API}/api/achievement-types`, { headers: hdr() });
|
||||
const d = await res.json();
|
||||
achTypes = res.ok && Array.isArray(d.items) ? d.items : [];
|
||||
achTypesLoaded = true;
|
||||
} catch {
|
||||
achTypes = [];
|
||||
}
|
||||
if (activeTab === 'ach') renderPane();
|
||||
}
|
||||
|
||||
function bindAch() {
|
||||
const addBtn = document.getElementById('spAchAddBtn');
|
||||
if (addBtn) addBtn.addEventListener('click', () => achFormOpen(null));
|
||||
const form = document.getElementById('spAchForm');
|
||||
if (!form) return;
|
||||
form.addEventListener('submit', onAchSubmit);
|
||||
document.getElementById('spAchCancelBtn').addEventListener('click', achFormClose);
|
||||
const list = document.getElementById('spAchList');
|
||||
if (list) {
|
||||
list.addEventListener('click', async e => {
|
||||
const items = (data.achievements && data.achievements.items) || [];
|
||||
const edit = e.target.closest('[data-ach-edit]');
|
||||
if (edit) {
|
||||
const rec = items.find(x => String(x.id) === edit.dataset.achEdit);
|
||||
if (rec) achFormOpen(rec);
|
||||
return;
|
||||
}
|
||||
const del = e.target.closest('[data-ach-del]');
|
||||
if (del) {
|
||||
const rec = items.find(x => String(x.id) === del.dataset.achDel);
|
||||
if (!rec) return;
|
||||
if (!confirm(`Удалить «${rec.type_name}${rec.value ? ' — ' + rec.value : ''}»?`)) return;
|
||||
try {
|
||||
const res = await fetch(`${API}/api/students/${studentId}/achievements/${rec.id}`, { method: 'DELETE', headers: hdr() });
|
||||
if (!res.ok) throw new Error('delete failed');
|
||||
showToast('Достижение удалено');
|
||||
await refreshAch();
|
||||
} catch {
|
||||
showToast('Не удалось удалить достижение', true);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function onAchSubmit(e) {
|
||||
e.preventDefault();
|
||||
const typeName = document.getElementById('spAchType').value.trim();
|
||||
if (!typeName) { showToast('Выберите тип достижения', true); return; }
|
||||
const body = {
|
||||
type_name: typeName,
|
||||
value: document.getElementById('spAchValue').value.trim(),
|
||||
achieved_at: document.getElementById('spAchDate').value || null,
|
||||
note: document.getElementById('spAchNote').value.trim(),
|
||||
};
|
||||
const btn = document.getElementById('spAchSaveBtn');
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const url = achEditId
|
||||
? `${API}/api/students/${studentId}/achievements/${achEditId}`
|
||||
: `${API}/api/students/${studentId}/achievements`;
|
||||
const res = await fetch(url, {
|
||||
method: achEditId ? 'PUT' : 'POST',
|
||||
headers: { ...hdr(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err.error || 'Не удалось сохранить достижение');
|
||||
}
|
||||
showToast(achEditId ? 'Достижение обновлено' : 'Достижение добавлено');
|
||||
achFormClose();
|
||||
await refreshAch();
|
||||
} catch (err) {
|
||||
showToast(err.message || 'Не удалось сохранить достижение', true);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshAch() {
|
||||
try {
|
||||
const res = await fetch(`${API}/api/students/${studentId}/achievements`, { headers: hdr() });
|
||||
if (res.ok) {
|
||||
const d = await res.json();
|
||||
data.achievements = { items: d.items || [], total: typeof d.total === 'number' ? d.total : (d.items || []).length };
|
||||
}
|
||||
} catch {}
|
||||
renderTabs();
|
||||
if (activeTab === 'ach') renderPane();
|
||||
}
|
||||
|
||||
async function downloadProfile() {
|
||||
const btn = document.getElementById('spDownloadBtn');
|
||||
if (btn) btn.disabled = true;
|
||||
|
||||
@@ -367,6 +367,9 @@ let profilePhotos = [];
|
||||
let pfState = null;
|
||||
let pfBaseline = '';
|
||||
let pfActiveTab = 'general';
|
||||
let achRecords = [];
|
||||
let achTypes = [];
|
||||
let achEditId = null;
|
||||
|
||||
const PF_CONTACT_ICONS = ['mail', 'send', 'phone', 'github', 'globe', 'link', 'at-sign'];
|
||||
|
||||
@@ -587,6 +590,9 @@ function openProfileData(id) {
|
||||
document.getElementById('profileDataModal').classList.add('open');
|
||||
loadGroupOptions();
|
||||
loadStudentPhotos(id);
|
||||
resetAchForm();
|
||||
loadAchRecords(id);
|
||||
loadAchTypes();
|
||||
fetch(`${API}/api/students/${id}/profile`, { headers: hdr() })
|
||||
.then(r => (r.ok ? r.json() : Promise.reject(new Error('load'))))
|
||||
.then(data => {
|
||||
@@ -609,6 +615,124 @@ function closeProfileData(skipCheck) {
|
||||
return true;
|
||||
}
|
||||
|
||||
function achTypeSelect(selected) {
|
||||
const act = achTypes.filter(t => t.is_active);
|
||||
const opts = ['<option value="">Выберите тип…</option>'].concat(
|
||||
act.map(t => `<option value="${pfE(t.name)}"${selected === t.name ? ' selected' : ''}>${esc(t.name)}</option>`)
|
||||
);
|
||||
if (selected && !act.some(t => t.name === selected)) {
|
||||
opts.push(`<option value="${pfE(selected)}" selected>${esc(selected)} (недоступен)</option>`);
|
||||
}
|
||||
return opts.join('');
|
||||
}
|
||||
|
||||
function openAchForm(rec) {
|
||||
const form = document.getElementById('pfAchForm');
|
||||
if (!form) return;
|
||||
achEditId = rec ? rec.id : null;
|
||||
document.getElementById('pfAchType').innerHTML = achTypeSelect(rec ? rec.type_name : '');
|
||||
document.getElementById('pfAchValue').value = rec ? (rec.value || '') : '';
|
||||
document.getElementById('pfAchDate').value = rec ? (rec.achieved_at || '') : todayIso();
|
||||
document.getElementById('pfAchNote').value = rec ? (rec.note || '') : '';
|
||||
form.hidden = false;
|
||||
document.getElementById('pfAchType').focus();
|
||||
}
|
||||
|
||||
function resetAchForm() {
|
||||
const form = document.getElementById('pfAchForm');
|
||||
if (form) form.hidden = true;
|
||||
achEditId = null;
|
||||
}
|
||||
|
||||
function pfAchItemHtml(a) {
|
||||
return `<div class="pf-ach-row">
|
||||
<div class="pf-ach-main">
|
||||
<div class="pf-ach-top">
|
||||
<span class="pf-ach-type">${esc(a.type_name)}</span>
|
||||
${a.value ? `<b class="pf-ach-value">${esc(a.value)}</b>` : ''}
|
||||
<span class="pf-ach-when">${a.achieved_at ? esc(fmtDateOnlyIso(a.achieved_at)) : ''}</span>
|
||||
</div>
|
||||
${a.note ? `<div class="pf-ach-note">${esc(a.note)}</div>` : ''}
|
||||
</div>
|
||||
<div class="pf-ach-acts">
|
||||
<button type="button" class="icon-btn" data-ach-edit="${a.id}" title="Редактировать"><i data-lucide="pencil"></i></button>
|
||||
<button type="button" class="icon-btn" data-ach-del="${a.id}" title="Удалить"><i data-lucide="trash-2"></i></button>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function pfAchRender() {
|
||||
const wrap = document.getElementById('pfAchRecords');
|
||||
if (!wrap) return;
|
||||
wrap.innerHTML = achRecords.length ? achRecords.map(pfAchItemHtml).join('') : '<div class="pf-ach-empty">Достижений пока нет</div>';
|
||||
const cnt = document.getElementById('pfCountAch');
|
||||
if (cnt) cnt.textContent = achRecords.length ? String(achRecords.length) : '';
|
||||
renderIcons();
|
||||
}
|
||||
|
||||
async function loadAchRecords(id) {
|
||||
achRecords = [];
|
||||
pfAchRender();
|
||||
try {
|
||||
const res = await fetch(`${API}/api/students/${id}/achievements`, { headers: hdr() });
|
||||
const d = await res.json();
|
||||
achRecords = res.ok && Array.isArray(d.items) ? d.items : [];
|
||||
} catch {
|
||||
achRecords = [];
|
||||
}
|
||||
pfAchRender();
|
||||
}
|
||||
|
||||
async function loadAchTypes() {
|
||||
try {
|
||||
const res = await fetch(`${API}/api/achievement-types`, { headers: hdr() });
|
||||
const d = await res.json();
|
||||
achTypes = res.ok && Array.isArray(d.items) ? d.items : [];
|
||||
} catch {
|
||||
achTypes = [];
|
||||
}
|
||||
const form = document.getElementById('pfAchForm');
|
||||
if (form && !form.hidden && achEditId == null) {
|
||||
document.getElementById('pfAchType').innerHTML = achTypeSelect('');
|
||||
}
|
||||
}
|
||||
|
||||
async function onAchSubmit(e) {
|
||||
e.preventDefault();
|
||||
if (!profileDataId) return;
|
||||
const typeName = document.getElementById('pfAchType').value.trim();
|
||||
if (!typeName) { showToast('Выберите тип достижения', true); return; }
|
||||
const body = {
|
||||
type_name: typeName,
|
||||
value: document.getElementById('pfAchValue').value.trim(),
|
||||
achieved_at: document.getElementById('pfAchDate').value || null,
|
||||
note: document.getElementById('pfAchNote').value.trim(),
|
||||
};
|
||||
const btn = document.getElementById('pfAchSaveBtn');
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const url = achEditId
|
||||
? `${API}/api/students/${profileDataId}/achievements/${achEditId}`
|
||||
: `${API}/api/students/${profileDataId}/achievements`;
|
||||
const res = await fetch(url, {
|
||||
method: achEditId ? 'PUT' : 'POST',
|
||||
headers: { ...hdr(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err.error || 'Не удалось сохранить достижение');
|
||||
}
|
||||
showToast(achEditId ? 'Достижение обновлено' : 'Достижение добавлено');
|
||||
resetAchForm();
|
||||
await loadAchRecords(profileDataId);
|
||||
} catch (err) {
|
||||
showToast(err.message || 'Не удалось сохранить достижение', true);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function openStudentFaces(id, name) {
|
||||
profileDataId = id;
|
||||
faceRefs = [];
|
||||
@@ -1595,6 +1719,39 @@ document.getElementById('profileDataForm').addEventListener('click', e => {
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('pfAchAddBtn').addEventListener('click', () => openAchForm(null));
|
||||
document.getElementById('pfAchSaveBtn').addEventListener('click', onAchSubmit);
|
||||
document.getElementById('pfAchForm').addEventListener('keydown', e => {
|
||||
if (e.key !== 'Enter' || e.shiftKey) return;
|
||||
if (e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT' || e.target.tagName === 'BUTTON') return;
|
||||
e.preventDefault();
|
||||
onAchSubmit(e);
|
||||
});
|
||||
document.getElementById('pfAchCancelBtn').addEventListener('click', resetAchForm);
|
||||
document.getElementById('pfAchRecords').addEventListener('click', async e => {
|
||||
const edit = e.target.closest('[data-ach-edit]');
|
||||
if (edit) {
|
||||
const rec = achRecords.find(x => String(x.id) === edit.dataset.achEdit);
|
||||
if (rec) openAchForm(rec);
|
||||
return;
|
||||
}
|
||||
const del = e.target.closest('[data-ach-del]');
|
||||
if (del) {
|
||||
if (!profileDataId) return;
|
||||
const rec = achRecords.find(x => String(x.id) === del.dataset.achDel);
|
||||
if (!rec) return;
|
||||
if (!confirm(`Удалить «${rec.type_name}${rec.value ? ' — ' + rec.value : ''}»?`)) return;
|
||||
try {
|
||||
const res = await fetch(`${API}/api/students/${profileDataId}/achievements/${rec.id}`, { method: 'DELETE', headers: hdr() });
|
||||
if (!res.ok) throw new Error('Не удалось удалить достижение');
|
||||
showToast('Достижение удалено');
|
||||
await loadAchRecords(profileDataId);
|
||||
} catch (err) {
|
||||
showToast(err.message || 'Не удалось удалить достижение', true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('pfTagsInput').addEventListener('keydown', e => {
|
||||
if (e.key !== 'Enter' && e.key !== ',') return;
|
||||
e.preventDefault();
|
||||
|
||||
Reference in New Issue
Block a user