отображение забронированных слотов и тестовые НУ

This commit is contained in:
emelianov
2026-05-25 21:02:50 +03:00
parent d48ddd2657
commit f549e15c63
19 changed files with 1319 additions and 9 deletions
@@ -0,0 +1,295 @@
(function () {
const state = {
satellites: [],
requests: [],
selectedSatelliteIds: new Set(),
bookings: []
};
const el = (id) => document.getElementById(id);
document.addEventListener('DOMContentLoaded', () => {
setDefaultInterval();
bindEvents();
loadOptions().then(() => loadBookings());
});
function bindEvents() {
el('bookings-refresh')?.addEventListener('click', () => loadBookings());
el('bookings-reset')?.addEventListener('click', resetFilters);
el('bookings-satellites-clear')?.addEventListener('click', () => {
selectVisibleSatellites();
});
el('bookings-satellite-search')?.addEventListener('input', renderSatellites);
el('bookings-request')?.addEventListener('change', () => loadBookings());
el('bookings-time-start')?.addEventListener('change', () => loadBookings());
el('bookings-time-stop')?.addEventListener('change', () => loadBookings());
}
function setDefaultInterval() {
const now = new Date();
now.setMinutes(0, 0, 0);
const stop = new Date(now.getTime());
stop.setDate(stop.getDate() + 7);
if (el('bookings-time-start')) el('bookings-time-start').value = toDateTimeLocal(now);
if (el('bookings-time-stop')) el('bookings-time-stop').value = toDateTimeLocal(stop);
}
function resetFilters() {
state.selectedSatelliteIds.clear();
if (el('bookings-request')) el('bookings-request').value = '';
if (el('bookings-satellite-search')) el('bookings-satellite-search').value = '';
setDefaultInterval();
renderSatellites();
loadBookings();
}
async function loadOptions() {
try {
const options = await fetchJson('/api/bookings/options');
state.satellites = Array.isArray(options.satellites) ? options.satellites : [];
state.requests = Array.isArray(options.requests) ? options.requests : [];
renderRequests();
renderSatellites();
} catch (error) {
showAlert(error.message || 'Не удалось загрузить справочники страницы бронирований.', 'danger');
}
}
async function loadBookings() {
setTableLoading();
const params = new URLSearchParams();
const timeStart = el('bookings-time-start')?.value;
const timeStop = el('bookings-time-stop')?.value;
const requestId = el('bookings-request')?.value;
if (timeStart) params.set('timeStart', toIsoLocal(timeStart));
if (timeStop) params.set('timeStop', toIsoLocal(timeStop));
if (requestId) params.set('requestId', requestId);
state.selectedSatelliteIds.forEach((id) => params.append('satelliteIds', id));
try {
const items = await fetchJson(`/api/bookings?${params.toString()}`);
state.bookings = Array.isArray(items) ? items : [];
renderBookings();
} catch (error) {
state.bookings = [];
renderBookings();
showAlert(error.message || 'Не удалось загрузить забронированные слоты.', 'danger');
}
}
function visibleSatellites() {
const query = (el('bookings-satellite-search')?.value || '').trim().toLowerCase();
return state.satellites.filter((satellite) => satelliteMatches(satellite, query));
}
function selectVisibleSatellites() {
const satellites = visibleSatellites();
satellites.forEach((satellite) => {
const id = Number(satellite.id);
if (!Number.isNaN(id)) {
state.selectedSatelliteIds.add(id);
}
});
renderSatellites();
loadBookings();
}
function renderRequests() {
const select = el('bookings-request');
if (!select) return;
const current = select.value;
select.innerHTML = '<option value="">Все заявки</option>' + state.requests.map((request) => {
const title = request.name ? `${request.name} / ${request.id}` : request.id;
return `<option value="${escapeHtml(request.id)}">${escapeHtml(title)}</option>`;
}).join('');
select.value = current;
}
function renderSatellites() {
const tbody = el('bookings-satellites-body');
if (!tbody) return;
const satellites = visibleSatellites();
if (!satellites.length) {
tbody.innerHTML = emptyRow(3, 'Спутники не найдены.');
return;
}
tbody.innerHTML = satellites.map((satellite) => {
const selected = state.selectedSatelliteIds.has(Number(satellite.id));
return `
<tr class="${selected ? 'bookings-selected-row' : ''}" data-satellite-id="${escapeHtml(satellite.id)}">
<td><input class="form-check-input" type="checkbox" ${selected ? 'checked' : ''} aria-label="Выбрать спутник"></td>
<td class="bookings-id">${escapeHtml(satellite.id ?? '—')}</td>
<td>
<div class="bookings-main-text">${escapeHtml(satellite.name || satellite.code || 'КА')}</div>
<div class="bookings-sub-text">${escapeHtml([satellite.code, satellite.typeCode, satellite.noradId ? `NORAD ${satellite.noradId}` : null].filter(Boolean).join(' / ') || '—')}</div>
</td>
</tr>`;
}).join('');
tbody.querySelectorAll('tr[data-satellite-id]').forEach((row) => {
row.addEventListener('click', (event) => {
event.preventDefault();
const id = Number(row.dataset.satelliteId);
if (state.selectedSatelliteIds.has(id)) {
state.selectedSatelliteIds.delete(id);
} else {
state.selectedSatelliteIds.add(id);
}
renderSatellites();
loadBookings();
});
});
}
function renderBookings() {
const tbody = el('bookings-body');
const empty = el('bookings-empty');
const wrap = el('bookings-table-wrap');
if (!tbody) return;
if (!state.bookings.length) {
tbody.innerHTML = '';
empty?.classList.remove('d-none');
wrap?.classList.add('d-none');
updateSummary();
return;
}
empty?.classList.add('d-none');
wrap?.classList.remove('d-none');
tbody.innerHTML = state.bookings.map((booking) => `
<tr>
<td class="bookings-id">${escapeHtml(booking.bookedSlotId ?? '—')}</td>
<td>
<div class="bookings-main-text">${escapeHtml(booking.satelliteName || booking.satelliteCode || `КА ${booking.satelliteId}`)}</div>
<div class="bookings-sub-text">ID ${escapeHtml(booking.satelliteId)}${booking.satelliteTypeCode ? ` / ${escapeHtml(booking.satelliteTypeCode)}` : ''}</div>
</td>
<td>
<div>Слот ${escapeHtml(booking.slotNum ?? '—')}</div>
<div class="bookings-sub-text">Цикл ${escapeHtml(booking.cycle ?? '—')}</div>
</td>
<td class="bookings-time-cell">
<div>${formatDateTime(booking.timeStart)}</div>
<div class="bookings-sub-text">${formatDateTime(booking.timeStop)}${booking.durationSeconds != null ? ` / ${formatNumber(booking.durationSeconds)} c` : ''}</div>
</td>
<td>
<div>${escapeHtml(booking.revolution ?? '—')}</div>
<div class="bookings-sub-text">${escapeHtml(booking.revolutionSign || '—')}</div>
</td>
<td>${formatNumber(booking.roll)}</td>
<td><span class="bookings-badge ${statusClass(booking.status)}">${escapeHtml(booking.status || '—')}</span></td>
<td>${formatRequestIds(booking.requestIds)}</td>
</tr>`).join('');
updateSummary();
}
function updateSummary() {
const summary = el('bookings-summary');
if (!summary) return;
const requestId = el('bookings-request')?.value;
const satellites = state.selectedSatelliteIds.size ? `, спутников: ${state.selectedSatelliteIds.size}` : '';
const request = requestId ? `, заявка: ${requestId}` : '';
summary.textContent = `Найдено бронирований: ${state.bookings.length}${satellites}${request}`;
}
function setTableLoading() {
el('bookings-empty')?.classList.add('d-none');
el('bookings-table-wrap')?.classList.remove('d-none');
const tbody = el('bookings-body');
if (tbody) tbody.innerHTML = emptyRow(8, 'Загрузка бронирований...');
const summary = el('bookings-summary');
if (summary) summary.textContent = 'Загрузка данных...';
}
async function fetchJson(url, options = {}) {
const response = await fetch(url, {
headers: { 'Accept': 'application/json', ...(options.headers || {}) },
...options
});
if (!response.ok) {
const text = await response.text();
throw new Error(extractError(text) || `HTTP ${response.status}`);
}
if (response.status === 204) return null;
return response.json();
}
function satelliteMatches(satellite, query) {
if (!query) return true;
return [satellite.id, satellite.noradId, satellite.code, satellite.name, satellite.typeCode]
.filter((value) => value !== undefined && value !== null)
.some((value) => String(value).toLowerCase().includes(query));
}
function emptyRow(colspan, text) {
return `<tr><td colspan="${colspan}" class="catalog-empty">${escapeHtml(text)}</td></tr>`;
}
function formatRequestIds(ids) {
if (!Array.isArray(ids) || !ids.length) return '—';
return ids.map((id) => `<span class="bookings-badge">${escapeHtml(id)}</span>`).join(' ');
}
function statusClass(status) {
if (!status) return '';
return `bookings-status-${String(status).toLowerCase()}`;
}
function formatDateTime(value) {
if (!value) return '—';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return escapeHtml(value);
return date.toLocaleString('ru-RU', {
year: '2-digit', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit'
});
}
function formatNumber(value) {
if (value === null || value === undefined || value === '') return '—';
const number = Number(value);
if (Number.isNaN(number)) return escapeHtml(value);
return number.toLocaleString('ru-RU', { maximumFractionDigits: 3 });
}
function toDateTimeLocal(date) {
const pad = (value) => String(value).padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
function toIsoLocal(value) {
return value && value.length === 16 ? `${value}:00` : value;
}
function showAlert(message, type = 'info') {
const box = el('bookings-alert');
if (!box) return;
box.innerHTML = `<div class="alert alert-${type} alert-dismissible fade show" role="alert">
${escapeHtml(message)}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Закрыть"></button>
</div>`;
}
function extractError(text) {
if (!text) return '';
try {
const json = JSON.parse(text);
return json.message || json.error || text;
} catch (_) {
return text;
}
}
function escapeHtml(value) {
return String(value ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
})();
@@ -0,0 +1,164 @@
.bookings-page {
height: calc(100vh - 4.25rem);
max-height: calc(100vh - 4.25rem);
min-height: 0;
overflow: hidden;
display: flex;
flex-direction: column;
padding-bottom: 0 !important;
}
.bookings-page > .d-flex:first-child,
#bookings-alert,
.bookings-filter-card {
flex: 0 0 auto;
}
.bookings-layout {
flex: 1 1 0;
min-height: 0;
overflow: hidden;
}
.bookings-layout > [class*="col-"] {
min-height: 0;
display: flex;
flex-direction: column;
}
.bookings-layout > [class*="col-"] > .catalog-card {
flex: 1 1 auto;
min-height: 0;
width: 100%;
}
.bookings-satellites-card,
.bookings-table-card {
overflow: hidden;
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
max-height: calc(100vh - 17rem);
}
.bookings-satellites-card .card-header,
.bookings-table-card .card-header {
flex: 0 0 auto;
}
.bookings-satellites-wrap,
.bookings-table-card .card-body {
flex: 1 1 auto;
min-height: 0;
overflow: auto;
}
.bookings-satellites-wrap {
height: calc(100vh - 23rem);
max-height: calc(100vh - 23rem);
overflow-y: auto;
overflow-x: hidden;
}
.bookings-table-card .card-body {
display: flex;
flex-direction: column;
}
.bookings-table-wrap {
flex: 1 1 auto;
min-height: 0;
height: calc(100vh - 21rem);
max-height: calc(100vh - 21rem);
overflow: auto;
}
.bookings-check-col {
width: 2rem;
}
.bookings-satellites-table tbody tr {
cursor: pointer;
}
.bookings-selected-row > td {
background: rgba(13, 110, 253, 0.12) !important;
}
.bookings-id {
font-family: var(--bs-font-monospace);
font-size: 0.82rem;
}
.bookings-main-text {
font-weight: 600;
}
.bookings-sub-text {
color: #6c757d;
font-size: 0.82rem;
}
.bookings-badge {
display: inline-flex;
align-items: center;
border: 1px solid rgba(108, 117, 125, 0.35);
border-radius: 999px;
padding: 0.1rem 0.45rem;
font-size: 0.78rem;
color: #495057;
background: rgba(248, 249, 250, 0.9);
}
.bookings-time-cell {
min-width: 15rem;
}
.bookings-status-booked {
border-color: rgba(13, 110, 253, 0.35);
color: #084298;
background: rgba(13, 110, 253, 0.12);
}
.bookings-status-processed,
.bookings-status-finished {
border-color: rgba(25, 135, 84, 0.4);
color: #0f5132;
background: rgba(25, 135, 84, 0.14);
}
.bookings-status-failed,
.bookings-status-canceled,
.bookings-status-cancelled {
border-color: rgba(220, 53, 69, 0.4);
color: #842029;
background: rgba(220, 53, 69, 0.14);
}
@media (max-width: 1199.98px) {
.bookings-page {
height: auto;
max-height: none;
overflow: visible;
padding-bottom: 1rem !important;
}
.bookings-layout,
.bookings-layout > [class*="col-"],
.bookings-layout > [class*="col-"] > .catalog-card,
.bookings-satellites-card,
.bookings-table-card,
.bookings-satellites-wrap,
.bookings-table-wrap,
.bookings-table-card .card-body {
overflow: visible;
height: auto;
max-height: none;
min-height: initial;
}
.bookings-layout > [class*="col-"] {
display: block;
}
}
@@ -11,6 +11,10 @@
min-height: 1.5rem;
}
.satellite-pdcm-send-time {
width: 15rem;
}
.satellite-pdcm-status {
display: inline-flex;
width: 0.75rem;
@@ -10,6 +10,7 @@
selectedSatelliteId: null,
details: null
};
const sendInitialConditionsDateTimePattern = /^(\d{2})\.(\d{2})\.(\d{4}) (\d{2}):(\d{2}):(\d{2})\.(\d{3})$/;
function showAlert(message, type = 'danger') {
const container = document.getElementById('satellite-pdcm-alert');
@@ -58,6 +59,57 @@
return value ? value.replace('T', ' ') : '-';
}
function pad(value, length = 2) {
return String(value).padStart(length, '0');
}
function currentDateTimeInputValue() {
const now = new Date();
return `${pad(now.getDate())}.${pad(now.getMonth() + 1)}.${now.getFullYear()} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}.${pad(now.getMilliseconds(), 3)}`;
}
function parseSendInitialConditionsTime() {
const input = document.getElementById('satellite-pdcm-send-ic-time');
const value = input?.value.trim() || '';
const match = value.match(sendInitialConditionsDateTimePattern);
if (!match) {
return {
valid: false,
message: 'Введите время НУ в формате dd.mm.yyyy hh:MM:ss.zzz'
};
}
const [, day, month, year, hour, minute, second, millisecond] = match;
const parsed = new Date(
Number(year),
Number(month) - 1,
Number(day),
Number(hour),
Number(minute),
Number(second),
Number(millisecond)
);
const validDate = parsed.getFullYear() === Number(year)
&& parsed.getMonth() === Number(month) - 1
&& parsed.getDate() === Number(day)
&& parsed.getHours() === Number(hour)
&& parsed.getMinutes() === Number(minute)
&& parsed.getSeconds() === Number(second)
&& parsed.getMilliseconds() === Number(millisecond);
if (!validDate) {
return {
valid: false,
message: 'Время НУ содержит некорректную дату или время'
};
}
return {
valid: true,
text: value
};
}
function formatNumber(value) {
return Number(value ?? 0).toFixed(3);
}
@@ -71,6 +123,25 @@
exportButton.disabled = !details || !details.ascNodes || !details.ascNodes.length;
}
function renderSendInitialConditionsState(details, loading = false) {
const button = document.getElementById('satellite-pdcm-send-ic');
if (!button) {
return;
}
const time = parseSendInitialConditionsTime();
const enabled = !!details && time.valid && !loading;
button.disabled = !enabled;
button.textContent = loading ? 'Передача...' : 'Передать НУ в slot-service';
if (!details) {
button.title = 'Выберите спутник';
} else if (!time.valid) {
button.title = time.message;
} else {
button.title = '';
}
}
function renderList() {
const tableBody = document.getElementById('satellite-pdcm-list');
tableBody.innerHTML = '';
@@ -110,6 +181,7 @@
if (!details) {
summary.innerHTML = '<div class="catalog-helper">Выберите спутник слева.</div>';
renderExportState(null);
renderSendInitialConditionsState(null);
return;
}
@@ -140,6 +212,7 @@
</div>
`;
renderExportState(details);
renderSendInitialConditionsState(details);
}
function renderTable(details) {
@@ -270,9 +343,32 @@
URL.revokeObjectURL(url);
}
async function sendInitialConditions() {
if (!state.selectedSatelliteId || !state.details) {
showAlert('Выберите спутник для передачи начальных условий');
return;
}
const time = parseSendInitialConditionsTime();
if (!time.valid) {
showAlert(time.message);
return;
}
renderSendInitialConditionsState(state.details, true);
showAlert('');
try {
await requestJson(`${apiBase}/${state.selectedSatelliteId}/send-ic?time=${encodeURIComponent(time.text)}`, {method: 'POST'});
showAlert('Начальные условия спутника переданы в slot-service', 'success');
} catch (error) {
showAlert(error.message || 'Не удалось передать начальные условия в slot-service');
} finally {
renderSendInitialConditionsState(state.details);
}
}
async function selectSatellite(satelliteId) {
state.selectedSatelliteId = satelliteId;
renderList();
renderSendInitialConditionsState(null);
showAlert('');
try {
@@ -317,6 +413,10 @@
loadSatellites();
});
document.getElementById('satellite-pdcm-export').addEventListener('click', exportCurrentCsv);
document.getElementById('satellite-pdcm-send-ic').addEventListener('click', sendInitialConditions);
const sendInitialConditionsTimeInput = document.getElementById('satellite-pdcm-send-ic-time');
sendInitialConditionsTimeInput.value = currentDateTimeInputValue();
sendInitialConditionsTimeInput.addEventListener('input', () => renderSendInitialConditionsState(state.details));
loadSatellites();
})();