Добавить отметку внесенных отчетов
This commit is contained in:
1 parent
623cf5ad3a
commit
e33de2114a
10 files changed
+76
-4
No files matched your search
@@ -20,6 +20,7 @@
|
|||||||
- For image/runtime changes, check the `Dockerfile`, Python entrypoint, static asset serving, and CI job together.
|
- For image/runtime changes, check the `Dockerfile`, Python entrypoint, static asset serving, and CI job together.
|
||||||
- For k3s changes, validate YAML and current cluster inventory first; keep `KUBE_CONFIG_B64` masked/protected in GitLab.
|
- For k3s changes, validate YAML and current cluster inventory first; keep `KUBE_CONFIG_B64` masked/protected in GitLab.
|
||||||
- Do not add unnecessary local build artifacts or temporary files to the repository.
|
- Do not add unnecessary local build artifacts or temporary files to the repository.
|
||||||
|
- Admin report UI changes should cover both the persisted history flag and browser behavior: run the focused history/admin filter tests, Python compilation, `git diff --check`, and a JavaScript syntax check for `web/admin.html`. The report list defaults to the calendar current month; do not silently replace the existing sort order.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
- VK scheduler lives in `app/belki/vk_scheduler.py`; use `BELKI_DATABASE_URL` in production and `BELKI_HISTORY_DB` for local SQLite checks. Keep mailing disabled until an administrator explicitly enables a conversation and schedule.
|
- VK scheduler lives in `app/belki/vk_scheduler.py`; use `BELKI_DATABASE_URL` in production and `BELKI_HISTORY_DB` for local SQLite checks. Keep mailing disabled until an administrator explicitly enables a conversation and schedule.
|
||||||
|
|||||||
@@ -91,3 +91,7 @@ Inspection results persist the base score for the number of inspections and each
|
|||||||
# 2026-09-26: explicit edible catch catalogue
|
# 2026-09-26: explicit edible catch catalogue
|
||||||
|
|
||||||
`app/belki/domain.py` keeps an explicit `EDIBLE_CATCHES` set for one-point inspection catches. `Ящерица` and `Летучая мышь` are included and covered by `tests/test_belki.py`; the Krylan memo lists them in the edible catch table.
|
`app/belki/domain.py` keeps an explicit `EDIBLE_CATCHES` set for one-point inspection catches. `Ящерица` and `Летучая мышь` are included and covered by `tests/test_belki.py`; the Krylan memo lists them in the edible catch table.
|
||||||
|
|
||||||
|
# 2026-10-07: entered report state
|
||||||
|
|
||||||
|
`app/belki/history.py` persists an administrative `entered` boolean with an idempotent SQLite/PostgreSQL schema migration. `/api/admin/calculations/{id}/entered` is session-protected and updates one report. `web/admin.html` defaults report history to the calendar current month, prepends an accessible checkbox/checkmark column, and dims rows after entry; sorting remains unchanged.
|
||||||
@@ -37,6 +37,10 @@ def period_bounds(period: str, date_from: str | None, date_to: str | None, *, no
|
|||||||
raise ValueError("Дата начала не может быть позже даты окончания")
|
raise ValueError("Дата начала не может быть позже даты окончания")
|
||||||
return start, end
|
return start, end
|
||||||
if period not in PERIODS:
|
if period not in PERIODS:
|
||||||
|
if period == "current_month":
|
||||||
|
current = (now or datetime.now(timezone.utc)).astimezone(WEB_TIMEZONE)
|
||||||
|
start = current.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
|
||||||
|
return start.astimezone(timezone.utc), current.astimezone(timezone.utc)
|
||||||
raise ValueError("Неизвестный период")
|
raise ValueError("Неизвестный период")
|
||||||
duration = PERIODS[period]
|
duration = PERIODS[period]
|
||||||
if duration is None:
|
if duration is None:
|
||||||
|
|||||||
+23
-2
@@ -92,6 +92,9 @@ class CalculationStore:
|
|||||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
)"""
|
)"""
|
||||||
)
|
)
|
||||||
|
columns = {row[1] for row in connection.execute("PRAGMA table_info(calculations)")}
|
||||||
|
if "entered" not in columns:
|
||||||
|
connection.execute("ALTER TABLE calculations ADD COLUMN entered INTEGER NOT NULL DEFAULT 0")
|
||||||
|
|
||||||
def _ensure_postgres_schema(self) -> None:
|
def _ensure_postgres_schema(self) -> None:
|
||||||
"""Создаёт таблицу belki_calculations в PostgreSQL, если её нет."""
|
"""Создаёт таблицу belki_calculations в PostgreSQL, если её нет."""
|
||||||
@@ -108,6 +111,7 @@ class CalculationStore:
|
|||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
)"""
|
)"""
|
||||||
)
|
)
|
||||||
|
connection.execute("ALTER TABLE belki_calculations ADD COLUMN IF NOT EXISTS entered BOOLEAN NOT NULL DEFAULT FALSE")
|
||||||
|
|
||||||
def save(self, *, actor_id: int | None, source: str, payload: dict[str, Any], response: dict[str, Any]) -> int:
|
def save(self, *, actor_id: int | None, source: str, payload: dict[str, Any], response: dict[str, Any]) -> int:
|
||||||
"""
|
"""
|
||||||
@@ -163,13 +167,13 @@ class CalculationStore:
|
|||||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||||
with self._psycopg.connect(self.database_url) as connection:
|
with self._psycopg.connect(self.database_url) as connection:
|
||||||
rows = connection.execute(
|
rows = connection.execute(
|
||||||
"""SELECT id, actor_id, source, mode, input_json, result_json, message, created_at
|
"""SELECT id, actor_id, source, mode, input_json, result_json, message, created_at, entered
|
||||||
FROM belki_calculations ORDER BY created_at DESC LIMIT %s""", (fetch_limit,)
|
FROM belki_calculations ORDER BY created_at DESC LIMIT %s""", (fetch_limit,)
|
||||||
).fetchall()
|
).fetchall()
|
||||||
else:
|
else:
|
||||||
with sqlite3.connect(self.sqlite_path) as connection:
|
with sqlite3.connect(self.sqlite_path) as connection:
|
||||||
rows = connection.execute(
|
rows = connection.execute(
|
||||||
"""SELECT id, actor_id, source, mode, input_json, result_json, message, created_at
|
"""SELECT id, actor_id, source, mode, input_json, result_json, message, created_at, entered
|
||||||
FROM calculations ORDER BY created_at DESC LIMIT ?""", (fetch_limit,)
|
FROM calculations ORDER BY created_at DESC LIMIT ?""", (fetch_limit,)
|
||||||
).fetchall()
|
).fetchall()
|
||||||
records = []
|
records = []
|
||||||
@@ -184,6 +188,7 @@ class CalculationStore:
|
|||||||
"id": row[0], "actor_id": row[1], "source": row[2], "mode": row[3],
|
"id": row[0], "actor_id": row[1], "source": row[2], "mode": row[3],
|
||||||
"input": input_data, "result": result_data, "message": message,
|
"input": input_data, "result": result_data, "message": message,
|
||||||
"created_at": row[7].isoformat() if hasattr(row[7], "isoformat") else row[7],
|
"created_at": row[7].isoformat() if hasattr(row[7], "isoformat") else row[7],
|
||||||
|
"entered": bool(row[8]),
|
||||||
})
|
})
|
||||||
if sort_by not in {"escort_id", "escort_name", "kitten_id", "kitten_name"}:
|
if sort_by not in {"escort_id", "escort_name", "kitten_id", "kitten_name"}:
|
||||||
sort_by = "escort_id"
|
sort_by = "escort_id"
|
||||||
@@ -210,6 +215,22 @@ class CalculationStore:
|
|||||||
records.sort(key=sort_value, reverse=descending)
|
records.sort(key=sort_value, reverse=descending)
|
||||||
return records[:limit]
|
return records[:limit]
|
||||||
|
|
||||||
|
def set_entered(self, calculation_id: int, entered: bool) -> dict[str, Any] | None:
|
||||||
|
"""Set the administrative entered flag and return the updated row."""
|
||||||
|
if isinstance(calculation_id, bool) or not isinstance(calculation_id, int) or calculation_id <= 0:
|
||||||
|
raise ValueError("ID записи должен быть положительным целым числом")
|
||||||
|
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||||
|
with self._psycopg.connect(self.database_url) as connection:
|
||||||
|
row = connection.execute("UPDATE belki_calculations SET entered=%s WHERE id=%s RETURNING id", (entered, calculation_id)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
with sqlite3.connect(self.sqlite_path) as connection:
|
||||||
|
cursor = connection.execute("UPDATE calculations SET entered=? WHERE id=?", (int(entered), calculation_id))
|
||||||
|
if cursor.rowcount == 0:
|
||||||
|
return None
|
||||||
|
return next((item for item in self.list_calculations(limit=500) if item["id"] == calculation_id), None)
|
||||||
|
|
||||||
def delete_calculation(self, calculation_id: int) -> bool:
|
def delete_calculation(self, calculation_id: int) -> bool:
|
||||||
"""Delete one history row and report whether it existed."""
|
"""Delete one history row and report whether it existed."""
|
||||||
if isinstance(calculation_id, bool) or not isinstance(calculation_id, int) or calculation_id <= 0:
|
if isinstance(calculation_id, bool) or not isinstance(calculation_id, int) or calculation_id <= 0:
|
||||||
|
|||||||
+15
@@ -669,6 +669,21 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
def do_PATCH(self) -> None: # noqa: N802
|
def do_PATCH(self) -> None: # noqa: N802
|
||||||
"""Меняет статус новой заявки через PATCH API."""
|
"""Меняет статус новой заявки через PATCH API."""
|
||||||
parsed = urlparse(self.path)
|
parsed = urlparse(self.path)
|
||||||
|
entered_prefix = "/api/admin/calculations/"
|
||||||
|
if parsed.path.startswith(entered_prefix) and parsed.path.endswith("/entered"):
|
||||||
|
if not self._admin_authorized(): return
|
||||||
|
try:
|
||||||
|
calculation_id = int(parsed.path[len(entered_prefix):-len("/entered")].strip("/"))
|
||||||
|
payload = self._read_json_body()
|
||||||
|
item = history_store().set_entered(calculation_id, bool(payload.get("entered")))
|
||||||
|
except (ApiError, ValueError) as exc:
|
||||||
|
self._json(400, {"error": str(exc)})
|
||||||
|
return
|
||||||
|
if item is None:
|
||||||
|
self._json(404, {"error": "Запись не найдена"})
|
||||||
|
else:
|
||||||
|
self._json(200, {"item": item})
|
||||||
|
return
|
||||||
if parsed.path.startswith("/api/admin/vk/conversations/") or parsed.path.startswith("/api/admin/vk/schedules/"):
|
if parsed.path.startswith("/api/admin/vk/conversations/") or parsed.path.startswith("/api/admin/vk/schedules/"):
|
||||||
if not self._admin_authorized(): return
|
if not self._admin_authorized(): return
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -40,6 +40,8 @@ mindmap
|
|||||||
Applications
|
Applications
|
||||||
web/admin.html
|
web/admin.html
|
||||||
Review and accept
|
Review and accept
|
||||||
|
Report entered checkbox
|
||||||
|
Current calendar month by default
|
||||||
web/applications.html
|
web/applications.html
|
||||||
VK bot
|
VK bot
|
||||||
vk_bot.py
|
vk_bot.py
|
||||||
@@ -61,11 +63,13 @@ mindmap
|
|||||||
Data
|
Data
|
||||||
PostgreSQL production
|
PostgreSQL production
|
||||||
calculations
|
calculations
|
||||||
|
calculations.entered admin flag
|
||||||
applications
|
applications
|
||||||
sudoku_games
|
sudoku_games
|
||||||
export outbox
|
export outbox
|
||||||
identities and profiles
|
identities and profiles
|
||||||
SQLite local fallback
|
SQLite local fallback
|
||||||
|
calculations.entered migration
|
||||||
Private MinIO image storage
|
Private MinIO image storage
|
||||||
belki-images bucket
|
belki-images bucket
|
||||||
HAProxy front door 10.43.30.146:9000
|
HAProxy front door 10.43.30.146:9000
|
||||||
|
|||||||
@@ -46,6 +46,7 @@
|
|||||||
- Typed flows are: feather donation (amount/color/source rows), kitten (activity screenshot), flying squirrel (past practice and a review link when applicable), and curator (LU screenshot with fraction). VK uses `/заявка`, `/перо`, `/бельчонок`, `/летяга`, and `/куратор`; its context keyboard drives every selectable application branch, while users type only free-form values. The bot polls accepted VK applications every 15 seconds and notifies the original peer; web applications have no inferred VK recipient.
|
- Typed flows are: feather donation (amount/color/source rows), kitten (activity screenshot), flying squirrel (past practice and a review link when applicable), and curator (LU screenshot with fraction). VK uses `/заявка`, `/перо`, `/бельчонок`, `/летяга`, and `/куратор`; its context keyboard drives every selectable application branch, while users type only free-form values. The bot polls accepted VK applications every 15 seconds and notifies the original peer; web applications have no inferred VK recipient.
|
||||||
- Google Sheets export is pre-wired but disabled by `BELKI_GOOGLE_EXPORT_ENABLED=0`. `ApplicationStore` records `application_created` and `application_accepted` snapshots in the PostgreSQL `belki_application_export_events` or SQLite `application_export_events` outbox. `GoogleSheetsExportService` sends FIFO JSON events only to an explicitly configured Google Apps Script Web App URL, retains failed events for retry, and is polled by the bot every 15 seconds when enabled.
|
- Google Sheets export is pre-wired but disabled by `BELKI_GOOGLE_EXPORT_ENABLED=0`. `ApplicationStore` records `application_created` and `application_accepted` snapshots in the PostgreSQL `belki_application_export_events` or SQLite `application_export_events` outbox. `GoogleSheetsExportService` sends FIFO JSON events only to an explicitly configured Google Apps Script Web App URL, retains failed events for retry, and is polled by the bot every 15 seconds when enabled.
|
||||||
- The admin page uses a restrained light editorial table layout with a separate password gate, category tabs (all, осмотры, ЛУ, ЗУ, ПУ/уроки), responsive filters, client-side sorting across every visible column, cat/kitten selectors, sticky headings, and a keyboard-navigable photo gallery; behavior remains backed by the existing history API.
|
- The admin page uses a restrained light editorial table layout with a separate password gate, category tabs (all, осмотры, ЛУ, ЗУ, ПУ/уроки), responsive filters, client-side sorting across every visible column, cat/kitten selectors, sticky headings, and a keyboard-navigable photo gallery; behavior remains backed by the existing history API.
|
||||||
|
- 2026-10-07: admin report history defaults to the calendar current month (`current_month`), with older reports still available through the existing period/date controls. Each report has a persisted `entered` flag in PostgreSQL/SQLite; the admin table exposes an accessible checkbox in the leftmost column, adds a checkmark, and dims entered rows. `PATCH /api/admin/calculations/{id}/entered` updates the flag without changing sort order.
|
||||||
- 2026-10-03: public calculator and `/admin` share an autumn visual layer: warm paper/ground tokens, amber-brown accents, subtle radial atmosphere, and seven CSS leaves with staggered fall motion. Leaves are decorative (`aria-hidden`, pointer-events disabled), stay behind content, and become static/faint under `prefers-reduced-motion`; no image or runtime dependency was added.
|
- 2026-10-03: public calculator and `/admin` share an autumn visual layer: warm paper/ground tokens, amber-brown accents, subtle radial atmosphere, and seven CSS leaves with staggered fall motion. Leaves are decorative (`aria-hidden`, pointer-events disabled), stay behind content, and become static/faint under `prefers-reduced-motion`; no image or runtime dependency was added.
|
||||||
- VK `messages.send` responses include a serialized context-aware keyboard; button payloads are translated back into the same dialog commands, while text commands remain supported.
|
- VK `messages.send` responses include a serialized context-aware keyboard; button payloads are translated back into the same dialog commands, while text commands remain supported.
|
||||||
- Production k3s deployment (2026-08-16): namespace `belki` runs the Belki web calculator, VK bot, PostgreSQL 16, and the migrated cwshed Nginx gateway. The gateway keeps MetalLB IP `10.12.0.204`, serves the legacy CatWar site, and routes `/belki`, `/admin`, and `/api/*` to Belki web on `10.12.0.212`. Belki images are `reg.nyan404.ru/cwshed-clone/belki` and `reg.nyan404.ru/cwshed`; PostgreSQL is mirrored as `reg.nyan404.ru/library/postgres:16-alpine-amd64` because cluster nodes cannot pull Docker Hub directly. Registry pull credentials and runtime secrets are created out-of-band in the `belki` namespace.
|
- Production k3s deployment (2026-08-16): namespace `belki` runs the Belki web calculator, VK bot, PostgreSQL 16, and the migrated cwshed Nginx gateway. The gateway keeps MetalLB IP `10.12.0.204`, serves the legacy CatWar site, and routes `/belki`, `/admin`, and `/api/*` to Belki web on `10.12.0.212`. Belki images are `reg.nyan404.ru/cwshed-clone/belki` and `reg.nyan404.ru/cwshed`; PostgreSQL is mirrored as `reg.nyan404.ru/library/postgres:16-alpine-amd64` because cluster nodes cannot pull Docker Hub directly. Registry pull credentials and runtime secrets are created out-of-band in the `belki` namespace.
|
||||||
|
|||||||
@@ -14,6 +14,12 @@ from app.main import BelkiHTTPServer, Handler
|
|||||||
|
|
||||||
|
|
||||||
class AdminFilterAndExportTests(unittest.TestCase):
|
class AdminFilterAndExportTests(unittest.TestCase):
|
||||||
|
def test_current_month_period_uses_calendar_month(self) -> None:
|
||||||
|
now = datetime(2026, 9, 1, 1, tzinfo=timezone.utc)
|
||||||
|
start, end = period_bounds("current_month", None, None, now=now)
|
||||||
|
self.assertEqual(start, datetime(2026, 8, 31, 21, tzinfo=timezone.utc))
|
||||||
|
self.assertEqual(end, now)
|
||||||
|
|
||||||
def test_named_and_custom_periods_filter_records(self) -> None:
|
def test_named_and_custom_periods_filter_records(self) -> None:
|
||||||
now = datetime(2026, 9, 1, 12, tzinfo=timezone.utc)
|
now = datetime(2026, 9, 1, 12, tzinfo=timezone.utc)
|
||||||
recent = {"created_at": "2026-09-01T11:30:00+00:00"}
|
recent = {"created_at": "2026-09-01T11:30:00+00:00"}
|
||||||
|
|||||||
@@ -70,6 +70,15 @@ class CalculationHistoryTests(unittest.TestCase):
|
|||||||
self.assertEqual(result["resource_points"][0]["points"], 7)
|
self.assertEqual(result["resource_points"][0]["points"], 7)
|
||||||
self.assertEqual(record["message"], "Баллы осмотра: 50 балла.")
|
self.assertEqual(record["message"], "Баллы осмотра: 50 балла.")
|
||||||
|
|
||||||
|
def test_admin_history_persists_entered_flag(self) -> None:
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
store = CalculationStore(sqlite_path=Path(directory) / "history.sqlite3")
|
||||||
|
record_id = store.save(actor_id=1, source="web", payload={"mode": "coaching"}, response={"message": "готово", "result": {}})
|
||||||
|
self.assertFalse(store.list_calculations()[0]["entered"])
|
||||||
|
updated = store.set_entered(record_id, True)
|
||||||
|
self.assertTrue(updated["entered"])
|
||||||
|
self.assertTrue(store.list_calculations()[0]["entered"])
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
+9
-2
@@ -73,6 +73,11 @@
|
|||||||
th { position: sticky; top: 0; z-index: 1; background: #f8f5f0; color: #69635d; font-size: .72rem; font-weight: 750; letter-spacing: .06em; text-transform: uppercase; white-space: nowrap; }
|
th { position: sticky; top: 0; z-index: 1; background: #f8f5f0; color: #69635d; font-size: .72rem; font-weight: 750; letter-spacing: .06em; text-transform: uppercase; white-space: nowrap; }
|
||||||
tbody tr:last-child td { border-bottom: 0; }
|
tbody tr:last-child td { border-bottom: 0; }
|
||||||
tbody tr:hover td { background: #fff8ef; }
|
tbody tr:hover td { background: #fff8ef; }
|
||||||
|
tbody tr.entered td { background: #f1eee8; color: #8a847d; }
|
||||||
|
tbody tr.entered:hover td { background: #ebe7df; }
|
||||||
|
.entered-marker { display: inline-flex; align-items: center; gap: 7px; color: #827a70; font-size: .82rem; white-space: nowrap; }
|
||||||
|
.entered-marker input { min-width: 18px; width: 18px; height: 18px; margin: 0; accent-color: #5d7650; }
|
||||||
|
.entered-marker span { font-size: 1rem; line-height: 1; }
|
||||||
td { color: #3d3935; font-size: .91rem; line-height: 1.45; }
|
td { color: #3d3935; font-size: .91rem; line-height: 1.45; }
|
||||||
.id-cell { color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
.id-cell { color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||||
.person { min-width: 155px; }
|
.person { min-width: 155px; }
|
||||||
@@ -143,14 +148,14 @@
|
|||||||
<label class="control-group">Порядок<select id="direction"><option value="asc">По возрастанию</option><option value="desc" selected>По убыванию</option></select></label>
|
<label class="control-group">Порядок<select id="direction"><option value="asc">По возрастанию</option><option value="desc" selected>По убыванию</option></select></label>
|
||||||
<label class="control-group">Кот<select id="catFilter"><option value="">Все коты</option></select></label>
|
<label class="control-group">Кот<select id="catFilter"><option value="">Все коты</option></select></label>
|
||||||
<label class="control-group">Котёнок<select id="kittenFilter"><option value="">Все котята</option></select></label>
|
<label class="control-group">Котёнок<select id="kittenFilter"><option value="">Все котята</option></select></label>
|
||||||
<label class="control-group">Период<select id="reportPeriod"><option value="all">Вся история</option><option value="year">Последний год</option><option value="month">Последний месяц</option><option value="week">Последняя неделя</option><option value="day">Последние сутки</option><option value="12h">Последние 12 часов</option><option value="6h">Последние 6 часов</option><option value="4h">Последние 4 часа</option><option value="2h">Последние 2 часа</option><option value="1h">Последний час</option></select></label>
|
<label class="control-group">Период<select id="reportPeriod"><option value="current_month" selected>Текущий месяц</option><option value="all">Вся история</option><option value="year">Последний год</option><option value="month">Последние 30 дней</option><option value="week">Последняя неделя</option><option value="day">Последние сутки</option><option value="12h">Последние 12 часов</option><option value="6h">Последние 6 часов</option><option value="4h">Последние 4 часа</option><option value="2h">Последние 2 часа</option><option value="1h">Последний час</option></select></label>
|
||||||
<label class="control-group">С даты<input id="reportDateFrom" type="date"></label>
|
<label class="control-group">С даты<input id="reportDateFrom" type="date"></label>
|
||||||
<label class="control-group">По дату<input id="reportDateTo" type="date"></label>
|
<label class="control-group">По дату<input id="reportDateTo" type="date"></label>
|
||||||
<button id="load" type="button">Обновить</button>
|
<button id="load" type="button">Обновить</button>
|
||||||
<a id="reportsExport" class="export-link" href="/api/admin/calculations.xlsx">Скачать XLSX</a>
|
<a id="reportsExport" class="export-link" href="/api/admin/calculations.xlsx">Скачать XLSX</a>
|
||||||
</section>
|
</section>
|
||||||
<p class="error" id="error" role="alert"></p>
|
<p class="error" id="error" role="alert"></p>
|
||||||
<div class="table-wrap"><table><thead><tr><th>Кот</th><th>Котята</th><th>Фото</th><th>Дата (UTC+3)</th><th>Баллы</th><th>Сообщение</th><th>Автор</th><th>ID</th><th></th></tr></thead><tbody id="rows"><tr><td class="empty" colspan="9">Загрузка истории…</td></tr></tbody></table></div>
|
<div class="table-wrap"><table><thead><tr><th>Внесено</th><th>Кот</th><th>Котята</th><th>Фото</th><th>Дата (UTC+3)</th><th>Баллы</th><th>Сообщение</th><th>Автор</th><th>ID</th><th></th></tr></thead><tbody id="rows"><tr><td class="empty" colspan="10">Загрузка истории…</td></tr></tbody></table></div>
|
||||||
</section>
|
</section>
|
||||||
<section id="applicationsView" class="admin-section applications hidden" aria-labelledby="applicationsTitle"><header class="topbar"><div><h2 id="applicationsTitle">Заявки</h2><p class="intro">Новые обращения из VK-бота и веб-формы.</p></div><div class="record-count" id="applicationCount">Заявки не загружены</div></header><nav class="tabs" aria-label="Статус заявок"><button class="application-tab tab" type="button" data-status="pending" aria-selected="true">Новые</button><button class="application-tab tab" type="button" data-status="accepted" aria-selected="false">Принятые</button><button class="application-tab tab" type="button" data-status="" aria-selected="false">Все</button></nav><section class="controls" aria-label="Фильтры заявок"><label class="control-group">Период<select id="applicationPeriod"><option value="all">Вся история</option><option value="year">Последний год</option><option value="month">Последний месяц</option><option value="week">Последняя неделя</option><option value="day">Последние сутки</option><option value="12h">Последние 12 часов</option><option value="6h">Последние 6 часов</option><option value="4h">Последние 4 часа</option><option value="2h">Последние 2 часа</option><option value="1h">Последний час</option></select></label><label class="control-group">С даты<input id="applicationDateFrom" type="date"></label><label class="control-group">По дату<input id="applicationDateTo" type="date"></label><button id="loadApplications" type="button">Обновить</button><a id="applicationsExport" class="export-link" href="/api/admin/applications.xlsx">Скачать XLSX</a></section><div class="application-layout"><div id="applicationList" class="application-list"><p class="empty">Загрузка заявок…</p></div><article id="applicationDetail" class="application-detail"><p class="empty">Выберите заявку слева.</p></article></div></section>
|
<section id="applicationsView" class="admin-section applications hidden" aria-labelledby="applicationsTitle"><header class="topbar"><div><h2 id="applicationsTitle">Заявки</h2><p class="intro">Новые обращения из VK-бота и веб-формы.</p></div><div class="record-count" id="applicationCount">Заявки не загружены</div></header><nav class="tabs" aria-label="Статус заявок"><button class="application-tab tab" type="button" data-status="pending" aria-selected="true">Новые</button><button class="application-tab tab" type="button" data-status="accepted" aria-selected="false">Принятые</button><button class="application-tab tab" type="button" data-status="" aria-selected="false">Все</button></nav><section class="controls" aria-label="Фильтры заявок"><label class="control-group">Период<select id="applicationPeriod"><option value="all">Вся история</option><option value="year">Последний год</option><option value="month">Последний месяц</option><option value="week">Последняя неделя</option><option value="day">Последние сутки</option><option value="12h">Последние 12 часов</option><option value="6h">Последние 6 часов</option><option value="4h">Последние 4 часа</option><option value="2h">Последние 2 часа</option><option value="1h">Последний час</option></select></label><label class="control-group">С даты<input id="applicationDateFrom" type="date"></label><label class="control-group">По дату<input id="applicationDateTo" type="date"></label><button id="loadApplications" type="button">Обновить</button><a id="applicationsExport" class="export-link" href="/api/admin/applications.xlsx">Скачать XLSX</a></section><div class="application-layout"><div id="applicationList" class="application-list"><p class="empty">Загрузка заявок…</p></div><article id="applicationDetail" class="application-detail"><p class="empty">Выберите заявку слева.</p></article></div></section>
|
||||||
<section id="vkView" class="admin-section hidden" aria-labelledby="vkTitle">
|
<section id="vkView" class="admin-section hidden" aria-labelledby="vkTitle">
|
||||||
@@ -262,6 +267,8 @@
|
|||||||
document.querySelector('#loadVk').addEventListener('click', loadVk); document.querySelector('#saveVkTemplate').addEventListener('click', createVkTemplate);
|
document.querySelector('#loadVk').addEventListener('click', loadVk); document.querySelector('#saveVkTemplate').addEventListener('click', createVkTemplate);
|
||||||
document.querySelector('#saveVkSchedule').addEventListener('click', createVkSchedule);
|
document.querySelector('#saveVkSchedule').addEventListener('click', createVkSchedule);
|
||||||
document.querySelector('#vkTemplate').addEventListener('change', updateVkTemplatePreview); document.querySelector('#vkTemplateText').addEventListener('input', updateVkTemplateCount);
|
document.querySelector('#vkTemplate').addEventListener('change', updateVkTemplatePreview); document.querySelector('#vkTemplateText').addEventListener('input', updateVkTemplateCount);
|
||||||
|
const reportRowsObserver = new MutationObserver(() => { rows.querySelectorAll('tr').forEach(row => { const empty = row.querySelector('.empty'); if (empty) { empty.colSpan = 10; return; } if (row.querySelector('.report-entered-cell')) return; const idCell = row.children[7]; if (!idCell) return; const item = items.find(entry => String(entry.id) === idCell.textContent.trim()); if (!item) return; if (item.entered) row.classList.add('entered'); const cell = document.createElement('td'); cell.className = 'report-entered-cell'; const label = document.createElement('label'); label.className = 'entered-marker'; const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.checked = Boolean(item.entered); checkbox.setAttribute('aria-label', `Отметить отчёт №${item.id} как внесённый`); const marker = document.createElement('span'); marker.textContent = item.entered ? '✓' : '—'; label.append(checkbox, marker); checkbox.addEventListener('change', async () => { const next = checkbox.checked; checkbox.disabled = true; try { const response = await fetch(`/api/admin/calculations/${encodeURIComponent(item.id)}/entered`, {method: 'PATCH', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({entered: next})}); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось изменить отметку'); item.entered = Boolean(data.item.entered); render(); } catch (err) { checkbox.checked = !next; error.textContent = err.message; checkbox.disabled = false; } }); cell.append(label); row.prepend(cell); }); });
|
||||||
|
reportRowsObserver.observe(rows, {childList: true});
|
||||||
restoreAdminSession();
|
restoreAdminSession();
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
Reference in new issue
Block a user