svod-otcheta-po-obucheniyu-d/script.js

705 lines
34 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* Свод отчета по обучению ДЦБ — логика прототипа (статика + localStorage) */
(function () {
"use strict";
var STORE_KEY = "dc-svod-v1";
var MONTH = "Сентябрь 2026";
var COLLECTOR = "Специалист";
// ------- демо-данные: черновик отчета (12 строк) -------
var SEED_ROWS = [
{ id: 1, row: 1, month: "Сентябрь", name: "Обучение по работе с АТС", ap: "Астана", pp: "Связь", contract: "ДГ-2026-0114", topic: "Эксплуатация АТС", person: "Каримова Айдана Сериковна", filled: true, error: null },
{ id: 2, row: 2, month: "Сентябрь", name: "Повышение квалификации по линии ВОЛС", ap: "Алматы", pp: "Оптика", contract: "ДГ-2026-0121", topic: "Монтаж ВОЛС", person: "Бектурсин Данияр Уланович", filled: true, error: null },
{ id: 3, row: 3, month: "Сентябрь", name: "Инструктаж по охране труда", ap: "Караганда", pp: "Технология", contract: "ДГ-2026-0128", topic: "Охрана труда", person: "Оспанова Гульнар Мукатовна", filled: true, error: null },
{ id: 4, row: 4, month: "Сентябрь", name: "Обучение по работе с АТС", ap: "Шымкент", pp: "Связь", contract: "ДГ-2026-0132", topic: "Эксплуатация АТС", person: "Мухитдинов Ержан Серикovich", filled: false, error: null },
{ id: 5, row: 5, month: "Сентябрь", name: "Курс по волоконно-оптическим линиям", ap: "Астана", pp: "Оптика", contract: "", topic: "", person: "Сейткулов Мадан Алиевич", filled: false, error: null },
{ id: 6, row: 6, month: "Сентябрь", name: "Повышение квалификации по линии ВОЛС", ap: "Астана", pp: "Оптика", contract: "ДГ-2026-0140", topic: "Монтаж ВОЛС", person: "Турсынов Ислам Бахытжанович", filled: true, error: "contract" },
{ id: 7, row: 7, month: "Сентябрь", name: "Инструктаж по пожарным эвакуациям", ap: "Петропавловск", pp: "Технология", contract: "ДГ-2026-0147", topic: "Пожарная безопасность", person: "Хамитова Дина Сапаролевна", filled: true, error: null },
{ id: 8, row: 8, month: "Сентябрь", name: "Обучение по работе с АТС", ap: "", pp: "", contract: "", topic: "", person: "", filled: false, error: null },
{ id: 9, row: 9, month: "Сентябрь", name: "Инструктаж по охране труда", ap: "Павлодар", pp: "Технология", contract: "ДГ-2026-0155", topic: "Охрана труда", person: "Рахимбеков Тимур Азаматович", filled: true, error: null },
{ id: 10, row: 10, month: "Сентябрь", name: "Курс по волоконно-оптическим линиям", ap: "Алматы", pp: "Оптика", contract: "ДГ-2026-0161", topic: "Монтаж ВОЛС", person: "Ералиев Нурлан Кайратович", filled: true, error: null },
{ id: 11, row: 11, month: "Сентябрь", name: "Повышение квалификации по линии ВОЛС", ap: "", pp: "", contract: "", topic: "", person: "Сапарова Алия Ержановна", filled: false, error: null },
{ id: 12, row: 12, month: "Сентябрь", name: "Инструктаж по пожарным эвакуациям", ap: "Костанай", pp: "Технология", contract: "ДГ-2026-0170", topic: "Пожарная безопасность", person: "Муканов Асхат Даниярович", filled: true, error: null }
];
// ------- данные экрана «Черновик отчета» -------
var SEED_DRAFT = [
{ id: 1, row: 1, month: "Сентябрь", name: "Обучение по работе с АТС", ap: "Астана", pp: "Связь", contract: "ДГ-2026-0114", topic: "Эксплуатация АТС", person: "Каримова Айдана Сериковна", note: null },
{ id: 2, row: 2, month: "Сентябрь", name: "Повышение квалификации по линии ВОЛС", ap: "Алматы", pp: "Оптика", contract: "ДГ-2026-0121", topic: "Монтаж ВОЛС", person: "Бектурсин Данияр Уланович", note: null },
{ id: 3, row: 3, month: "Сентябрь", name: "Инструктаж по охране труда", ap: "Караганда", pp: "Технология", contract: "ДГ-2026-0128", topic: "Охрана труда", person: "Оспанова Гульнар Мукатовна", note: null },
{ id: 4, row: 4, month: "Сентябрь", name: "Обучение по работе с АТС", ap: "Шымкент", pp: "Связь", contract: "ДГ-2026-0132", topic: "Эксплуатация АТС", person: "Мухитдинов Ержан Серикovich", note: "Тема обучения совпадает со строкой 1 — вероятно, дубликат записи" },
{ id: 5, row: 5, month: "Сентябрь", name: "Курс по волоконно-оптическим линиям", ap: "Астана", pp: "Оптика", contract: "ДГ-2026-0136", topic: "Монтаж ВОЛС", person: "Сейткулов Мадан Алиевич", note: "Договор 2025 года — проверить актуальность" },
{ id: 6, row: 6, month: "Сентябрь", name: "Повышение квалификации по линии ВОЛС", ap: "Астана", pp: "Оптика", contract: "ДГ-2026-0140", topic: "Монтаж ВОЛС", person: "Турсынов Ислам Бахытжанович", note: null },
{ id: 7, row: 7, month: "Сентябрь", name: "Инструктаж по пожарным эвакуациям", ap: "Петропавловск", pp: "Технология", contract: "ДГ-2026-0147", topic: "Пожарная безопасность", person: "Хамитова Дина Сапаролевна", note: null },
{ id: 8, row: 8, month: "Сентябрь", name: "Обучение по работе с АТС", ap: "Шымкент", pp: "Связь", contract: "ДГ-2026-0132", topic: "Эксплуатация АТС", person: "Мухитдинов Ержан Серикovich", note: null },
{ id: 9, row: 9, month: "Сентябрь", name: "Инструктаж по охране труда", ap: "Павлодар", pp: "Технология", contract: "ДГ-2026-0155", topic: "Охрана труда", person: "Рахимбеков Тимур Азаматович", note: "Строка дублируется со строкой 3 — сверить ФИО" },
{ id: 10, row: 10, month: "Сентябрь", name: "Курс по волоконно-оптическим линиям", ap: "Алматы", pp: "Оптика", contract: "ДГ-2026-0161", topic: "Монтаж ВОЛС", person: "Ералиев Нурлан Кайратович", note: null },
{ id: 11, row: 11, month: "Сентябрь", name: "Повышение квалификации по линии ВОЛС", ap: "Астана", pp: "Оптика", contract: "ДГ-2026-0165", topic: "Монтаж ВОЛС", person: "Сапарова Алия Ержановна", note: null },
{ id: 12, row: 12, month: "Сентябрь", name: "Инструктаж по пожарным эвакуациям", ap: "Костанай", pp: "Технология", contract: "ДГ-2026-0170", topic: "Пожарная безопасность", person: "Муканов Асхат Даниярович", note: null }
];
// ------- данные экрана «Уведомления» -------
var SEED_NOTIFIES = [
{ id: 1, person: "Каримова Айдана Сериковна", topic: "Эксплуатация АТС", status: "pending" },
{ id: 2, person: "Бектурсин Данияр Уланович", topic: "Монтаж ВОЛС", status: "pending" },
{ id: 3, person: "Оспанова Гульнар Мукатовна", topic: "Охрана труда", status: "pending" },
{ id: 4, person: "Мухитдинов Ержан Серикovich", topic: "Эксплуатация АТС", status: "pending" },
{ id: 5, person: "Сейткулов Мадан Алиевич", topic: "Монтаж ВОЛС", status: "pending" },
{ id: 6, person: "Турсынов Ислам Бахытжанович", topic: "Монтаж ВОЛС", status: "pending" },
{ id: 7, person: "Хамитова Дина Сапаролевна", topic: "Пожарная безопасность", status: "pending" },
{ id: 8, person: "Рахимбеков Тимур Азаматович", topic: "Охрана труда", status: "pending" },
{ id: 9, person: "Ералиев Нурлан Кайратович", topic: "Монтаж ВОЛС", status: "pending" },
{ id: 10, person: "Сапарова Алия Ержановна", topic: "Монтаж ВОЛС", status: "pending" },
{ id: 11, person: "Муканов Асхат Даниярович", topic: "Пожарная безопасность", status: "pending" }
];
// ------- состояние -------
var state = {
collect: SEED_ROWS,
draft: SEED_DRAFT,
notifies: SEED_NOTIFIES,
draftAccepted: false,
manualMode: false,
log: [
{ t: "Сегодня 09:14", who: "Система", act: "Загружен черновик отчета за сентябрь" },
{ t: "Сегодня 09:14", who: "ИИ", act: "Обнаружено 4 строки с несоответствиями и 1 дубликат" }
]
};
var ui = { tab: "collect", editingCollect: null, editingDraft: null, openNotif: null, sending: false };
function now() {
var d = new Date();
var h = d.getHours(); if (h < 10) h = "0" + h;
var m = d.getMinutes(); if (m < 10) m = "0" + m;
return "Сегодня " + h + ":" + m;
}
function save() {
try {
localStorage.setItem(STORE_KEY, JSON.stringify(state));
} catch (e) { /* локальное хранилище может быть недоступно */ }
}
function load() {
try {
var raw = localStorage.getItem(STORE_KEY);
if (raw) {
var parsed = JSON.parse(raw);
if (parsed && Array.isArray(parsed.collect) && parsed.collect.length) {
state.collect = parsed.collect;
state.draft = parsed.draft || state.draft;
state.notifies = parsed.notifies || state.notifies;
state.draftAccepted = !!parsed.draftAccepted;
state.manualMode = !!parsed.manualMode;
state.log = parsed.log || state.log;
}
}
} catch (e) { /* поврежденные данные — берем seed */ }
}
function log(who, act) {
state.log.unshift({ t: now(), who: who, act: act });
save();
renderLog();
}
// ------- утилиты DOM -------
function $(id) { return document.getElementById(id); }
function el(tag, cls, text) {
var n = document.createElement(tag);
if (cls) n.className = cls;
if (text != null) n.textContent = text;
return n;
}
function escapeHtml(s) {
return String(s == null ? "" : s)
.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
.replace(/"/g, "&quot;").replace(/'/g, "&#39;");
}
function toast(msg, tone) {
var stack = $("toastStack");
if (!stack) return;
var t = el("div", "kt-ai-toast");
if (tone) t.setAttribute("data-tone", tone);
t.textContent = msg;
stack.appendChild(t);
setTimeout(function () {
if (t.parentNode) t.parentNode.removeChild(t);
}, 3500);
}
// ------- статусы строк экрана 1 -------
function rowStatus(r) {
if (r.error) return "error";
if (!r.ap || !r.pp || !r.contract || !r.topic || !r.person) return "pending";
return "filled";
}
function statusPill(r) {
var st = rowStatus(r);
if (st === "filled") return '<span class="kt-ai-status-pill" data-status="ok">Заполнено</span>';
if (st === "error") return '<span class="kt-ai-status-pill" data-status="risk">Ошибка сверки</span>';
return '<span class="kt-ai-status-pill" data-status="warn">Ожидает данных</span>';
}
function collectKpis() {
var filled = 0, pending = 0, errors = 0;
state.collect.forEach(function (r) {
var st = rowStatus(r);
if (st === "filled") filled++;
else if (st === "error") errors++;
else pending++;
});
return [
{ label: "Всего строк", value: String(state.collect.length) },
{ label: "Заполнено", value: String(filled) },
{ label: "Ожидают данных", value: String(pending) },
{ label: "Ошибки сверки", value: String(errors) }
];
}
function renderKpis(strip, items) {
if (!strip) return;
strip.innerHTML = "";
items.forEach(function (k) {
var d = el("div", "kt-ai-kpi");
d.appendChild(el("span", "value", k.value));
d.appendChild(el("span", "label", k.label));
if (k.hint) d.appendChild(el("span", "hint", k.hint));
strip.appendChild(d);
});
}
function renderCollectKpis() { renderKpis($("collectKpis"), collectKpis()); }
// ------- экран 1: таблица сбора -------
function renderCollect() {
var body = $("collectBody");
if (!body) return;
body.innerHTML = "";
state.collect.forEach(function (r) {
var tr = document.createElement("tr");
if (!r.filled) tr.className = "dc-row-pending";
tr.setAttribute("data-id", String(r.id));
var html = "";
html += "<td>" + r.row + "</td>";
html += "<td>" + escapeHtml(r.month) + "</td>";
html += "<td>" + escapeHtml(r.name) + "</td>";
html += "<td>" + escapeHtml(r.ap) + "</td>";
html += "<td>" + escapeHtml(r.pp) + "</td>";
html += "<td>" + escapeHtml(r.contract) + "</td>";
html += "<td>" + escapeHtml(r.topic) + "</td>";
html += "<td>" + escapeHtml(r.person) + "</td>";
html += '<td class="dc-status-cell">' + statusPill(r) + "</td>";
html += '<td class="dc-actions">' +
'<button class="kt-ai-icon-button" type="button" data-act="edit" aria-label="Заполнить строку">' +
'<svg class="kt-icon" aria-hidden="true"><use href="#pencil"></use></svg></button></td>';
tr.innerHTML = html;
body.appendChild(tr);
});
renderCollectKpis();
renderProgressState();
}
function renderProgressState() {
var b = $("collectProgress");
var fill = $("collectProgressFill");
var pct = $("collectProgressPct");
if (b && !ui.savingProgressActive) b.hidden = true;
if (fill) fill.style.width = "0%";
if (pct) pct.textContent = "";
}
// ------- экран 1: форма ручного ввода -------
function openCollectForm(id) {
var r = null;
state.collect.forEach(function (x) { if (x.id === id) r = x; });
if (!r) return;
ui.editingCollect = id;
$("editRowLabel").textContent = "По.ст. " + r.row + " — " + r.name;
$("f_ap").value = r.ap;
$("f_pp").value = r.pp;
$("f_contract").value = r.contract;
$("f_topic").value = r.topic;
$("f_person").value = r.person;
$("editCard").hidden = false;
$("f_ap").focus();
}
function closeCollectForm() {
ui.editingCollect = null;
$("editCard").hidden = true;
}
function saveCollectForm(e) {
e.preventDefault();
var r = null;
state.collect.forEach(function (x) { if (x.id === ui.editingCollect) r = x; });
if (!r) return;
r.ap = $("f_ap").value.trim();
r.pp = $("f_pp").value.trim();
r.contract = $("f_contract").value.trim();
r.topic = $("f_topic").value.trim();
r.person = $("f_person").value.trim();
r.filled = !!(r.ap && r.pp && r.contract && r.topic && r.person);
if (r.filled) r.error = null;
save();
log(COLLECTOR, "Заполнена строка № " + r.row + " вручную (По.ст. " + r.row + ", " + r.person + ")");
toast("Строка сохранена", "ok");
closeCollectForm();
renderCollect();
}
// ------- экран 1: обновление из SAP -------
function updateFromSap() {
if (ui.savingProgressActive) return;
ui.savingProgressActive = true;
var b = $("collectProgress");
var fill = $("collectProgressFill");
var pct = $("collectProgressPct");
var btn = $("btnSap");
var pill = $("sapStatus");
b.hidden = false;
btn.disabled = true;
if (pill) { pill.textContent = "Соединение…"; pill.setAttribute("data-status", "info"); }
var step = 0;
var total = 6;
var timer = setInterval(function () {
step++;
var p = Math.min(100, Math.round(step / total * 100));
if (fill) fill.style.width = p + "%";
if (pct) pct.textContent = " · " + p + "%";
if (step >= total) {
clearInterval(timer);
applySapData();
save();
log("ИИ", "Запрошены данные из SAP, обновлены строки № " + sapUpdates.join(", "));
if (pill) { pill.textContent = "Подключение активное"; pill.setAttribute("data-status", "ok"); }
btn.disabled = false;
b.hidden = true;
ui.savingProgressActive = false;
renderCollect();
toast("Данные из SAP получены", "ok");
}
}, 450);
}
var sapUpdates = [];
function applySapData() {
// Имитация ответа SAP: заполняем недостающие данные
sapUpdates = [];
var sapMap = {
4: { ap: "Шымкент", pp: "Связь", contract: "ДГ-2026-0132", topic: "Эксплуатация АТС", person: "Мухитдинов Ержан Серикovich" },
5: { ap: "Астана", pp: "Оптика", contract: "ДГ-2026-0136", topic: "Монтаж ВОЛС", person: "Сейткулов Мадан Алиевич" },
6: { ap: "Астана", pp: "Оптика", contract: "ДГ-2026-0140", topic: "Монтаж ВОЛС", person: "Турсынов Ислам Бахытжанович" },
8: { ap: "Шымкент", pp: "Связь", contract: "ДГ-2026-0153", topic: "Эксплуатация АТС", person: "Абишова Маржан Касымовна" },
11: { ap: "Астана", pp: "Оптика", contract: "ДГ-2026-0165", topic: "Монтаж ВОЛС", person: "Сапарова Алия Ержановна" }
};
state.collect.forEach(function (r) {
var src = sapMap[r.id];
if (!src) return;
var changed = false;
["ap", "pp", "contract", "topic", "person"].forEach(function (k) {
if (!r[k] && src[k]) { r[k] = src[k]; changed = true; }
});
if (changed) sapUpdates.push(r.row);
});
// пересчет filled / error
state.collect.forEach(function (r) {
var all = !!(r.ap && r.pp && r.contract && r.topic && r.person);
if (all) { r.filled = true; r.error = null; }
else r.filled = false;
// строки, которые SAP не вернул, остаются «Ожидает данных»
if (!sapMap[r.id] && !all) r.error = null;
});
}
// ------- экран 1 → экран 2: формирование черновика -------
function generateDraft() {
// Черновик строится из заполненных строк экрана сбора
var filled = state.collect.filter(function (r) { return rowStatus(r) === "filled"; });
if (filled.length === 0) {
toast("Нет заполненных строк — сначала введите данные", "warn");
return;
}
// Переносим в черновик, сохраняя примечания по id из seed (если есть)
state.draft = [];
var prev = {};
SEED_DRAFT.forEach(function (d) { prev[d.id] = d.note; });
filled.forEach(function (r) {
state.draft.push({
id: r.id,
row: state.draft.length + 1,
month: r.month,
name: r.name,
ap: r.ap,
pp: r.pp,
contract: r.contract,
topic: r.topic,
person: r.person,
note: prev[r.id] || null
});
});
// Дубликаты: совпадение «АП + Договор + ФИО»
var seen = {};
state.draft.forEach(function (d) {
var key = d.ap + "|" + d.contract + "|" + d.person;
if (seen[key]) {
if (!d.note) d.note = "Возможный дубликат: совпадает со строкой № " + seen[key];
} else {
seen[key] = d.row;
}
});
state.draftAccepted = false;
state.manualMode = false;
save();
log("ИИ", "Сформирован черновик отчета: " + state.draft.length + " строк");
log(COLLECTOR, "Черновик передан на проверку");
setTab("draft");
toast("Черновик сформирован", "ok");
renderAll();
}
// ------- экран 2: черновик -------
function draftKpis() {
var errors = 0, ok = 0;
state.draft.forEach(function (d) {
if (d.note) errors++;
else ok++;
});
return [
{ label: "Всего строк", value: String(state.draft.length) },
{ label: "Строк с ошибками", value: String(errors) },
{ label: "Строк без замечаний", value: String(ok) }
];
}
function renderDraftKpis() { renderKpis($("draftKpis"), draftKpis()); }
function renderDraft() {
var body = $("draftBody");
if (!body) return;
body.innerHTML = "";
state.draft.forEach(function (d) {
var tr = document.createElement("tr");
if (d.note) tr.className = "dc-draft-flag";
else tr.className = "dc-draft-fine";
tr.setAttribute("data-id", String(d.id));
var noteHtml = "";
if (d.note) {
noteHtml = '<span class="dc-note">' +
'<svg class="kt-icon" aria-hidden="true"><use href="#warning"></use></svg>' +
escapeHtml(d.note) + "</span>";
} else {
noteHtml = '<span class="dc-note dc-note--ok">' +
'<svg class="kt-icon" aria-hidden="true"><use href="#check-circle"></use></svg>Без замечаний</span>';
}
tr.innerHTML =
"<td>" + d.row + "</td>" +
"<td>" + escapeHtml(d.month) + "</td>" +
"<td>" + escapeHtml(d.name) + "</td>" +
"<td>" + escapeHtml(d.ap) + "</td>" +
"<td>" + escapeHtml(d.pp) + "</td>" +
"<td>" + escapeHtml(d.contract) + "</td>" +
"<td>" + escapeHtml(d.topic) + "</td>" +
"<td>" + escapeHtml(d.person) + "</td>" +
"<td>" + noteHtml + "</td>";
body.appendChild(tr);
});
renderDraftKpis();
}
function openDraftForm(id) {
var d = null;
state.draft.forEach(function (x) { if (x.id === id) d = x; });
if (!d) return;
ui.editingDraft = id;
$("draftEditRowLabel").textContent = "По.ст. " + d.row + " — " + d.person;
$("df_ap").value = d.ap;
$("df_pp").value = d.pp;
$("df_contract").value = d.contract;
$("df_topic").value = d.topic;
$("df_person").value = d.person;
$("df_note").value = d.note || "";
$("draftEditCard").hidden = false;
$("df_ap").focus();
}
function closeDraftForm() {
ui.editingDraft = null;
$("draftEditCard").hidden = true;
}
function saveDraftForm(e) {
e.preventDefault();
var d = null;
state.draft.forEach(function (x) { if (x.id === ui.editingDraft) d = x; });
if (!d) return;
d.ap = $("df_ap").value.trim();
d.pp = $("df_pp").value.trim();
d.contract = $("df_contract").value.trim();
d.topic = $("df_topic").value.trim();
d.person = $("df_person").value.trim();
d.note = $("df_note").value.trim();
// Строка считается исправленной, если заполнены все поля и примечание убрано
if (d.ap && d.pp && d.contract && d.topic && d.person && !d.note) {
d.note = null;
log(COLLECTOR, "Строка № " + d.row + " исправлена вручную: " + d.person);
} else {
log(COLLECTOR, "Строка № " + d.row + " — примечание обновлено: " + (d.note || "не указано"));
}
save();
toast("Строка сохранена", "ok");
closeDraftForm();
renderDraft();
}
function manualMode() {
state.manualMode = true;
save();
$("manualNote").hidden = false;
log("ИИ", "ИИ сброшен в ручной режим — дальнейшая проверка выполняется вручную");
toast("Переход в ручной режим", "warn");
}
function acceptDraft() {
var errors = 0;
state.draft.forEach(function (d) { if (d.note) errors++; });
state.draftAccepted = true;
save();
log(COLLECTOR, "Черновик принят: " + state.draft.length + " строк, " + errors + " с примечаниями");
// Пересобираем уведомления по принятым строкам
state.notifies = state.draft.map(function (d, i) {
var prev = null;
SEED_NOTIFIES.forEach(function (n) { if (n.person === d.person) prev = n; });
var st = (prev && prev.status === "sent") ? "sent" : "pending";
return { id: i + 1, person: d.person, topic: d.topic, status: st };
});
// Убираем дубли по ФИО, сохраняя статус
var byPerson = {};
var out = [];
state.notifies.forEach(function (n) {
if (byPerson[n.person]) {
if (n.status === "sent") byPerson[n.person].status = "sent";
} else {
byPerson[n.person] = n;
out.push(n);
}
});
state.notifies = out;
state.notifies.forEach(function (n, i) { n.id = i + 1; });
save();
setTab("notify");
toast("Черновик принят — уведомления сформированы", "ok");
renderAll();
}
function renderLog() {
var list = $("actionLog");
if (!list) return;
list.innerHTML = "";
state.log.slice(0, 12).forEach(function (e) {
var li = el("li");
li.innerHTML =
'<span class="dc-log-when kt-ai-t-xs kt-ai-t-muted">' + escapeHtml(e.t) + "</span>" +
'<span class="kt-ai-chip ' + (e.who === "ИИ" ? "dc-log-ai" : "") + '">' + escapeHtml(e.who) + "</span>" +
'<span class="dc-log-act kt-ai-t-sm">' + escapeHtml(e.act) + "</span>";
list.appendChild(li);
});
}
// ------- экран 3: уведомления -------
function notifyKpis() {
var sent = 0, pending = 0;
state.notifies.forEach(function (n) { if (n.status === "sent") sent++; else pending++; });
return [
{ label: "Адресатов", value: String(state.notifies.length) },
{ label: "Готово к отправке", value: String(pending) },
{ label: "Отправлено", value: String(sent) }
];
}
function renderNotifyKpis() { renderKpis($("notifyKpis"), notifyKpis()); }
function notificationText(n) {
return "Здравствуйте, " + n.person + "!\n\n" +
"В сводном отчете по обучению ДЦБ за " + MONTH.toLowerCase() + " зафиксировано ваше участие в теме: «" + n.topic + "».\n\n" +
"Просим подтвердить корректность записи в срок до конца месяца.\n\n" +
"С уважением,\nСпециалист по обучению ДЦБ";
}
function renderNotify() {
renderNotifyKpis();
var btn = $("btnSendAll");
var pendingNote = $("notifyPendingNote");
var ready = state.draftAccepted;
btn.disabled = !ready;
if (pendingNote) pendingNote.hidden = ready;
var list = $("notifyList");
if (!list) return;
list.innerHTML = "";
state.notifies.forEach(function (n) {
var card = el("div", "kt-ai-card dc-notify-card");
card.setAttribute("data-nid", String(n.id));
var head = el("div", "dc-notify-head");
var person = el("span", "dc-notify-title", n.person + (n.status === "sent" ? " · отправлено" : ""));
head.appendChild(person);
var st = n.status === "sent"
? '<span class="kt-ai-status-pill" data-status="ok">Отправлено</span>'
: (ready ? '<span class="kt-ai-status-pill" data-status="info">Готово к отправке</span>'
: '<span class="kt-ai-status-pill" data-status="muted">Сформируется после принятия черновика</span>');
var stWrap = el("span");
stWrap.innerHTML = st;
head.appendChild(stWrap);
card.appendChild(head);
var meta = el("div", "kt-ai-t-xs kt-ai-t-muted", "Тема: " + n.topic + " · " + MONTH);
card.appendChild(meta);
var body = el("div", "dc-notify-body");
body.textContent = notificationText(n);
card.appendChild(body);
var actions = el("div", "kt-ai-h-stack dc-notify-actions");
actions.setAttribute("data-gap", "tight");
var toggle = el("button", "kt-ai-btn");
toggle.type = "button";
toggle.textContent = n.status === "sent" ? "Отправлено" : "Отправить";
if (n.status === "sent") toggle.disabled = true;
toggle.setAttribute("data-act", "send");
toggle.setAttribute("data-nid", String(n.id));
actions.appendChild(toggle);
card.appendChild(actions);
list.appendChild(card);
});
}
function sendOne(id) {
var n = null;
state.notifies.forEach(function (x) { if (x.id === id) n = x; });
if (!n || n.status === "sent") return;
n.status = "sent";
save();
log(COLLECTOR, "Отправлено уведомление: " + n.person + " (" + n.topic + ")");
toast("Уведомление отправлено: " + n.person.split(" ")[0] + " " + n.person.split(" ")[1] + "…", "ok");
renderNotify();
}
function sendAll() {
if (!state.draftAccepted) return;
state.notifies.forEach(function (n) { n.status = "sent"; });
save();
log(COLLECTOR, "Отправлены все уведомления: " + state.notifies.length + " адресатов");
toast("Все уведомления отправлены", "ok");
renderNotify();
}
function renderAll() {
renderCollect();
renderDraft();
renderNotify();
renderLog();
}
// ------- вкладки -------
function setTab(name) {
ui.tab = name;
var tabs = document.querySelectorAll(".kt-ai-tab");
tabs.forEach(function (t) {
t.setAttribute("data-active", t.getAttribute("data-tab") === name ? "true" : "false");
});
["collect", "draft", "notify", "about"].forEach(function (s) {
var elx = $("screen-" + s);
if (elx) elx.hidden = (s !== name);
});
}
// ------- события -------
function wire() {
// вкладки
document.querySelectorAll(".kt-ai-tab").forEach(function (t) {
t.addEventListener("click", function () { setTab(t.getAttribute("data-tab")); });
});
// экран 1
$("btnSap").addEventListener("click", updateFromSap);
$("btnToDraft").addEventListener("click", generateDraft);
$("editClose").addEventListener("click", closeCollectForm);
$("editCancel").addEventListener("click", closeCollectForm);
$("rowForm").addEventListener("submit", saveCollectForm);
var cbody = $("collectBody");
cbody.addEventListener("click", function (e) {
var b = e.target.closest("[data-act='edit']");
if (!b) return;
var tr = b.closest("tr");
if (!tr) return;
openCollectForm(parseInt(tr.getAttribute("data-id"), 10));
});
// экран 2
$("btnManual").addEventListener("click", manualMode);
$("btnBackCollect").addEventListener("click", function () { setTab("collect"); });
$("btnAcceptDraft").addEventListener("click", acceptDraft);
$("draftEditClose").addEventListener("click", closeDraftForm);
$("draftEditCancel").addEventListener("click", closeDraftForm);
$("draftForm").addEventListener("submit", saveDraftForm);
var dbody = $("draftBody");
dbody.addEventListener("click", function (e) {
var tr = e.target.closest("tr[data-id]");
if (!tr) return;
openDraftForm(parseInt(tr.getAttribute("data-id"), 10));
});
$("btnClearLog").addEventListener("click", function () {
state.log = [];
save();
renderLog();
toast("Журнал очищен");
});
// экран 3
$("btnSendAll").addEventListener("click", sendAll);
$("btnBackDraft").addEventListener("click", function () { setTab("draft"); });
$("btnPrint").addEventListener("click", function () {
window.print();
});
var nlist = $("notifyList");
nlist.addEventListener("click", function (e) {
var b = e.target.closest("[data-act='send']");
if (!b) return;
sendOne(parseInt(b.getAttribute("data-nid"), 10));
});
}
// ------- старт -------
function init() {
load();
$("monthLabel").textContent = MONTH;
wire();
setTab("collect");
renderAll();
if (state.manualMode) $("manualNote").hidden = false;
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
} else {
init();
}
})();