diff --git a/content.js b/content.js
index b0a6aff..6e1981c 100644
--- a/content.js
+++ b/content.js
@@ -1,6 +1,17 @@
// content.js
+
+function hasDocumentElements() {
+ if (!isDocumentsPage()) return;
+
+ const elements = document.querySelectorAll('[class*="document" i]');
+ if (elements.length === 9) {
+ window.location.reload();
+ }
+}
+
if (isDocumentsPage()) {
console.log('[EXT][content] loaded');
+ setInterval(hasDocumentElements, 500);
}
const dataType = 'metaData';
@@ -48,6 +59,7 @@ async function loadStorageData() {
}
async function updateStorageData() {
+ await loadStorageData();
if (!storageData.metaData || !storageData.userData) {
await loadStorageData();
}
diff --git a/documents.js b/documents.js
index 2bc1632..2982025 100644
--- a/documents.js
+++ b/documents.js
@@ -241,7 +241,7 @@
// Функция отображения PDF
- async function viewDocument(documentPath, title) {
+ async function viewDocument(documentPath) {
try {
showMessage('Загрузка документа...', 'info', 1000);
@@ -874,8 +874,7 @@
btn.addEventListener('click', (e) => {
e.stopPropagation();
const path = btn.dataset.path;
- const title = btn.dataset.title;
- viewDocument(path, title);
+ viewDocument(path);
});
});
@@ -883,8 +882,7 @@
btn.addEventListener('click', (e) => {
e.stopPropagation();
const path = btn.dataset.path;
- const title = btn.dataset.title;
- viewDocument(path, title);
+ viewDocument(path);
});
});
@@ -915,18 +913,33 @@
}
}
+ async function getDocuments() {
+ try {
+ return await sendMessageToContent('prepareDocuments', {});
+ } catch (error) {
+ console.error('Ошибка получения документов:', error);
+ showMessage('Ошибка загрузки документов', 'error');
+ return null;
+ }
+ }
+
// Основная функция подготовки документов
async function prepareDocuments() {
try {
showMessage('Загрузка документов...', 'info');
- const response = await sendMessageToContent('prepareDocuments', {});
+ const docsData = await getDocuments();
+ if (!docsData) {
+ showMessage('Ошибка загрузки документов', 'error');
+ console.error('Нет данных документов');
+ return
+ };
- if (response.success) {
- deliveryTypeSettings = response.data.deliveryType;
- createDocumentsTable(response.data.singings);
+ if (docsData.success) {
+ deliveryTypeSettings = docsData.data.deliveryType;
+ createDocumentsTable(docsData.data.singings);
} else {
- showMessage('Ошибка загрузки документов: ' + (response.message || 'Неизвестная ошибка'), 'error');
+ showMessage('Ошибка загрузки документов: ' + (docsData.message || 'Неизвестная ошибка'), 'error');
}
} catch (error) {
console.error('Ошибка подготовки документов:', error);
@@ -955,6 +968,145 @@
}
}
+ async function handleDocsStatuses() {
+ try {
+ const statusesData = await getDocuments();
+ if (statusesData && statusesData.success) {
+ const singings = statusesData.data.singings || [];
+
+ // Получаем таблицу и все строки
+ const table = document.querySelector('.m-table.m-table-generator.m-si-generator__table');
+ if (!table) {
+ console.error('Таблица не найдена');
+ return;
+ }
+
+ const tableRows = table.querySelectorAll('.m-table-row:not(.m-table__header)'); // Исключаем заголовок
+
+ singings.forEach(singing => {
+ if (singing.statuses && singing.statuses.length > 0) {
+ const commonStatuses = singing.statuses.filter(s => s.idPatientMis === null);
+ const lastStatus = commonStatuses.reduce((max, status) =>
+ status.id > max.id ? status : max
+ , commonStatuses[0] || singing.statuses[0]);
+
+ singing.documents.forEach(doc => {
+ const isCompleted = lastStatus.category === 'completed';
+
+ // Ищем строку таблицы с соответствующим номером документа
+ const targetRow = Array.from(tableRows).find(row => {
+ const numberCell = row.querySelector('.col__number');
+ if (numberCell) {
+ const numberText = numberCell.textContent.trim();
+ return numberText === doc.number.toString();
+ }
+ return false;
+ });
+
+ if (targetRow) {
+ // Находим ячейку с заголовком
+ const titleCell = targetRow.querySelector('.col__title');
+
+ if (titleCell) {
+ // Находим span с текстом заголовка
+ const titleSpan = titleCell.querySelector('.m-table-row-cell__struct');
+
+ if (titleSpan) {
+ // Создаем контейнер для кнопок и текста
+ const container = document.createElement('div');
+ container.style.display = 'flex';
+ container.style.alignItems = 'center';
+ container.style.gap = '8px';
+
+ // Сохраняем текст заголовка
+ const titleText = titleSpan.cloneNode(true);
+
+ // Очищаем ячейку
+ titleCell.innerHTML = '';
+
+ if (isCompleted) {
+ // Для завершенных документов - создаем кнопки по количеству файлов в storagePath
+ if (singing.storagePath && singing.storagePath.length > 0) {
+ singing.storagePath.forEach((path, index) => {
+ const statusButton = document.createElement('span');
+ statusButton.className = 'status-button';
+ statusButton.style.display = 'inline-flex';
+ statusButton.style.alignItems = 'center';
+ statusButton.style.justifyContent = 'center';
+ statusButton.style.cursor = 'pointer';
+ statusButton.style.marginRight = index < singing.storagePath.length - 1 ? '4px' : '0';
+
+ // Добавляем номер документа, если их больше одного
+ const showNumber = singing.storagePath.length > 1;
+ statusButton.innerHTML = `${showNumber ? `${index + 1}` : ''}`;
+
+ // Добавляем обработчик клика для просмотра конкретного документа
+ statusButton.addEventListener('click', async (e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ await viewDocument(path);
+ });
+
+ container.appendChild(statusButton);
+ });
+ } else {
+ // Если storagePath пустой, создаем одну кнопку как запасной вариант
+ const statusButton = document.createElement('span');
+ statusButton.className = 'status-button';
+ statusButton.style.display = 'inline-flex';
+ statusButton.style.alignItems = 'center';
+ statusButton.style.justifyContent = 'center';
+ statusButton.style.cursor = 'pointer';
+ statusButton.style.marginRight = '4px';
+ statusButton.innerHTML = ``;
+
+ container.appendChild(statusButton);
+ }
+ } else {
+ // Для незавершенных документов - одна кнопка с часами
+ const statusButton = document.createElement('span');
+ statusButton.className = 'status-button';
+ statusButton.style.display = 'inline-flex';
+ statusButton.style.alignItems = 'center';
+ statusButton.style.justifyContent = 'center';
+ statusButton.style.cursor = 'pointer';
+ statusButton.style.marginRight = '4px';
+ statusButton.innerHTML = ``;
+
+ // Добавляем обработчик клика для открытия модального окна со статусами
+ statusButton.addEventListener('click', function (e) {
+ e.stopPropagation();
+ e.preventDefault();
+ createStatusesModal(singing);
+ });
+
+ container.appendChild(statusButton);
+ }
+
+ // Добавляем текст заголовка
+ container.appendChild(titleText);
+
+ // Добавляем контейнер в ячейку
+ titleCell.appendChild(container);
+ }
+ } else {
+ console.log(`Не найдена ячейка заголовка для документа №${doc.number}`);
+ }
+ } else {
+ console.log(`Строка для документа №${doc.number} не найдена в таблице`);
+ }
+ });
+ }
+ });
+ } else {
+ showMessage('Ошибка загрузки статусов документов: ' + (statusesData.message || 'Неизвестная ошибка'), 'error');
+ }
+ } catch (error) {
+ console.error('Ошибка получения статусов документов:', error);
+ showMessage('Ошибка загрузки статусов документов', 'error');
+ }
+ }
+
// Добавляем стили для статусов
const style = document.createElement('style');
style.textContent = `
@@ -977,7 +1129,8 @@
document.head.appendChild(style);
// Запуск
- setTimeout(() => {
+ setTimeout(async () => {
addDocsBtn();
+ await handleDocsStatuses();
}, 500);
})();
\ No newline at end of file