From cffaaac75544f252647d931f966994bef2c3e5e7 Mon Sep 17 00:00:00 2001 From: Nyan404 Date: Tue, 1 Sep 2026 01:51:03 +0300 Subject: [PATCH] fix: present web timestamps in UTC+3 --- MEMORY.md | 1 + app/belki/admin_filters.py | 10 ++++++---- app/belki/xlsx_export.py | 14 +++++++------- app/main.py | 6 +++--- project_mind_map.md | 1 + structure_and_data.md | 1 + tests/test_admin_export.py | 6 ++++-- web/admin.html | 4 ++-- 8 files changed, 25 insertions(+), 18 deletions(-) diff --git a/MEMORY.md b/MEMORY.md index 0a3a5ba..6b06211 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -57,6 +57,7 @@ - 2026-08-25: application validation limits text, rows, per-row feather amounts, and attachments across web and VK. Persisted media/review links require HTTPS, and a profile link is accepted only for a VK host. - 2026-08-25: authenticated admin refresh WebSockets use a separate pool of eight slots so they cannot consume the bounded general HTTP worker pool. History sorting normalizes old string IDs with current numeric IDs. - 2026-09-01: admin XLSX downloads are session/password-protected routes. Keep report category/cat/kitten and application status plus period/date-range query parameters identical between the API list and export endpoint so the file matches the visible selection. +- 2026-09-01: all web-facing Belki dates are UTC+3. Never change persisted UTC moments to implement this; convert at the UI/XLSX boundary and interpret calendar inputs in UTC+3. # 2026-08-16 — несколько котят в прокачке `CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде. diff --git a/app/belki/admin_filters.py b/app/belki/admin_filters.py index 4f96acc..5823fc8 100644 --- a/app/belki/admin_filters.py +++ b/app/belki/admin_filters.py @@ -11,10 +11,11 @@ PERIODS = { "6h": timedelta(hours=6), "4h": timedelta(hours=4), "2h": timedelta(hours=2), "1h": timedelta(hours=1), } +WEB_TIMEZONE = timezone(timedelta(hours=3), name="UTC+3") -def parse_timestamp(value: str, *, end_of_day: bool = False) -> datetime: - """Parse an ISO date/time stored by either SQLite or PostgreSQL as UTC.""" +def parse_timestamp(value: str, *, end_of_day: bool = False, web_input: bool = False) -> datetime: + """Parse a stored UTC instant or a date entered in the UTC+3 web interface.""" text = value.strip().replace("Z", "+00:00") if len(text) == 10: text += "T23:59:59.999999" if end_of_day else "T00:00:00" @@ -22,7 +23,8 @@ def parse_timestamp(value: str, *, end_of_day: bool = False) -> datetime: result = datetime.fromisoformat(text) except ValueError as exc: raise ValueError("Дата должна быть в формате ГГГГ-ММ-ДД") from exc - return result.replace(tzinfo=result.tzinfo or timezone.utc).astimezone(timezone.utc) + assumed_timezone = WEB_TIMEZONE if web_input else timezone.utc + return result.replace(tzinfo=result.tzinfo or assumed_timezone).astimezone(timezone.utc) def period_bounds(period: str, date_from: str | None, date_to: str | None, *, now: datetime | None = None) -> tuple[datetime | None, datetime | None]: @@ -30,7 +32,7 @@ def period_bounds(period: str, date_from: str | None, date_to: str | None, *, no if date_from or date_to: if not date_from or not date_to: raise ValueError("Укажите обе даты диапазона") - start, end = parse_timestamp(date_from), parse_timestamp(date_to, end_of_day=True) + start, end = parse_timestamp(date_from, web_input=True), parse_timestamp(date_to, end_of_day=True, web_input=True) if start > end: raise ValueError("Дата начала не может быть позже даты окончания") return start, end diff --git a/app/belki/xlsx_export.py b/app/belki/xlsx_export.py index 9bb9d08..a4bbe90 100644 --- a/app/belki/xlsx_export.py +++ b/app/belki/xlsx_export.py @@ -7,7 +7,7 @@ from xml.sax.saxutils import escape from zipfile import ZIP_DEFLATED, ZipFile -def _cell(column: int, row: int, value: object, *, header: bool = False) -> str: +def _cell(column: int, row: int, value: object, *, header: bool = False, display_timezone: timezone = timezone.utc) -> str: name = "" number = column while number: @@ -16,22 +16,22 @@ def _cell(column: int, row: int, value: object, *, header: bool = False) -> str: reference = f"{name}{row}" style = ' s="1"' if header else '' if isinstance(value, datetime): - timestamp = value.replace(tzinfo=value.tzinfo or timezone.utc).astimezone(timezone.utc) - serial = (timestamp - datetime(1899, 12, 30, tzinfo=timezone.utc)).total_seconds() / 86400 + timestamp = value.replace(tzinfo=value.tzinfo or timezone.utc).astimezone(display_timezone) + serial = (timestamp.replace(tzinfo=None) - datetime(1899, 12, 30)).total_seconds() / 86400 return f'{serial:.10f}' if isinstance(value, (int, float)) and not isinstance(value, bool): return f'{value}' return f'{escape(str(value or ""))}' -def build_xlsx(*, sheet_name: str, headers: list[str], rows: list[list[object]]) -> bytes: - """Builds one readable XLSX worksheet with a frozen, styled header row.""" +def build_xlsx(*, sheet_name: str, headers: list[str], rows: list[list[object]], display_timezone: timezone = timezone.utc) -> bytes: + """Build a workbook with dates converted to its user-facing time zone.""" sheet_rows = [ - '' + ''.join(_cell(index, 1, value, header=True) for index, value in enumerate(headers, 1)) + '' + '' + ''.join(_cell(index, 1, value, header=True, display_timezone=display_timezone) for index, value in enumerate(headers, 1)) + '' ] for row_number, row in enumerate(rows, 2): sheet_rows.append('%s' % (row_number, ''.join( - _cell(index, value_row, value) for index, value in enumerate(row, 1) for value_row in (row_number,) + _cell(index, value_row, value, display_timezone=display_timezone) for index, value in enumerate(row, 1) for value_row in (row_number,) ))) widths = ''.join(f'' for index, header in enumerate(headers, 1)) sheet = ('' diff --git a/app/main.py b/app/main.py index bfd4971..35ac665 100644 --- a/app/main.py +++ b/app/main.py @@ -16,7 +16,7 @@ from urllib.parse import parse_qs, unquote, urlparse from .belki.api import ApiError, calculate_and_store, calculate_payload, inspect_bulk_payload, resolve_identity_payload from .belki.history import CalculationStore from .belki.applications import ApplicationError, ApplicationStore, validate_application -from .belki.admin_filters import matches_period, period_bounds +from .belki.admin_filters import WEB_TIMEZONE, matches_period, period_bounds from .belki.google_sheets_export import GoogleSheetsExportService from .belki.identity import IdentityDirectory from .belki.image_host import ImageHostClient, ImageHostError @@ -407,7 +407,7 @@ class Handler(BaseHTTPRequestHandler): return records = [item for item in history_store().list_calculations(sort_by="escort_id", descending=True, limit=500) if matches_period(item, *bounds) and report_matches_filters(item, query)] rows = [[item["id"], datetime.fromisoformat(str(item["created_at"]).replace("Z", "+00:00")), item["mode"], item["source"], item["actor_id"], item["message"]] for item in records] - self._xlsx("belki-reports.xlsx", build_xlsx(sheet_name="Отчёты", headers=["ID", "Создан", "Тип", "Источник", "Автор", "Отчёт"], rows=rows)) + self._xlsx("belki-reports.xlsx", build_xlsx(sheet_name="Отчёты", headers=["ID", "Создан (UTC+3)", "Тип", "Источник", "Автор", "Отчёт"], rows=rows, display_timezone=WEB_TIMEZONE)) return if path == "/api/admin/applications": if not self._admin_authorized(): @@ -429,7 +429,7 @@ class Handler(BaseHTTPRequestHandler): return records = [item for item in application_store().list(status=status) if matches_period(item, *bounds)] rows = [[item["id"], datetime.fromisoformat(str(item["created_at"]).replace("Z", "+00:00")), item["status"], item["source"], item["application"].get("type", ""), item["application"].get("name", ""), item["application"].get("character_id")] for item in records] - self._xlsx("belki-applications.xlsx", build_xlsx(sheet_name="Заявки", headers=["ID", "Создана", "Статус", "Источник", "Тип", "Имя", "ID персонажа"], rows=rows)) + self._xlsx("belki-applications.xlsx", build_xlsx(sheet_name="Заявки", headers=["ID", "Создана (UTC+3)", "Статус", "Источник", "Тип", "Имя", "ID персонажа"], rows=rows, display_timezone=WEB_TIMEZONE)) return requested = unquote(path).lstrip("/") candidate = (WEB_ROOT / requested).resolve() diff --git a/project_mind_map.md b/project_mind_map.md index 66322e3..e1bba20 100644 --- a/project_mind_map.md +++ b/project_mind_map.md @@ -117,6 +117,7 @@ flowchart LR Bot --> ImageHost Admin[Администратор] -->|session cookie| Web Admin -->|same filters| XLSX[Отчёты и заявки XLSX] + Web -->|UTC instants to UTC+3 display| Admin Web --> XLSX Web --> Admin Bot -. when enabled .-> Sheets[Google Apps Script] diff --git a/structure_and_data.md b/structure_and_data.md index 10c512a..068684c 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -110,6 +110,7 @@ - 2026-08-25: coaching reports allow an independence status for every kitten in both ЛУ and ЗУ. Natural input attaches `сам`/`не сам` written after a participant ID to that participant, and web ID fields use numeric-text input instead of spinner controls. - 2026-08-25: the earned-points calculator groups coaching start and end times in one responsive time-range row. - 2026-09-01: authenticated `/admin` report and application views share named (all/year/month/week/day/12–1 h) and explicit date-range filters with their XLSX links. `app/belki/admin_filters.py` is the single UTC-boundary parser; `xlsx_export.py` writes a styled one-sheet workbook with typed dates, column filters, and a frozen header. +- 2026-09-01: web-facing timestamps and calendar ranges use UTC+3. The database still stores UTC moments; `WEB_TIMEZONE` converts visible admin/XLSX dates, while date-only filters are converted from UTC+3 boundaries before querying records. - 2026-08-25: web reports use a two-step flow: `/api/calculate` prepares the message without saving it, then `/api/reports` stores it only after the user explicitly selects «Отправить отчёт». The UI disables that action while it is in progress and after success. - 2026-08-25: shared two-column form grids align controls at the start of their row, preventing a date field with its helper button from stretching the adjacent skill select. - 2026-08-25: mobile adaptation is a required acceptance criterion for all frontend changes; validate narrow-width layout, touch usability, focus/error states, and absence of horizontal overflow alongside desktop rendering. diff --git a/tests/test_admin_export.py b/tests/test_admin_export.py index 5674d78..f6dbfc5 100644 --- a/tests/test_admin_export.py +++ b/tests/test_admin_export.py @@ -8,7 +8,7 @@ from datetime import datetime, timezone from io import BytesIO from pathlib import Path -from app.belki.admin_filters import matches_period, period_bounds +from app.belki.admin_filters import WEB_TIMEZONE, matches_period, period_bounds from app.belki.xlsx_export import build_xlsx from app.main import BelkiHTTPServer, Handler @@ -21,9 +21,11 @@ class AdminFilterAndExportTests(unittest.TestCase): self.assertTrue(matches_period(recent, *period_bounds("2h", None, None, now=now))) self.assertFalse(matches_period(old, *period_bounds("2h", None, None, now=now))) self.assertTrue(matches_period(old, *period_bounds("all", "2026-08-30", "2026-08-30", now=now))) + start, _ = period_bounds("all", "2026-08-30", "2026-08-30", now=now) + self.assertEqual(start, datetime(2026, 8, 29, 21, tzinfo=timezone.utc)) def test_xlsx_is_a_valid_workbook_with_filters_and_typed_values(self) -> None: - content = build_xlsx(sheet_name="Отчёты", headers=["ID", "Создан", "Текст"], rows=[[7, datetime(2026, 9, 1, 12, 30, tzinfo=timezone.utc), "Только выбранная строка"]]) + content = build_xlsx(sheet_name="Отчёты", headers=["ID", "Создан", "Текст"], rows=[[7, datetime(2026, 9, 1, 12, 30, tzinfo=timezone.utc), "Только выбранная строка"]], display_timezone=WEB_TIMEZONE) with zipfile.ZipFile(BytesIO(content)) as archive: self.assertTrue(archive.testzip() is None) sheet = archive.read("xl/worksheets/sheet1.xml").decode() diff --git a/web/admin.html b/web/admin.html index 255bcaa..82e0cb2 100644 --- a/web/admin.html +++ b/web/admin.html @@ -116,7 +116,7 @@ Скачать XLSX -
КотКотятаФотоДатаСообщениеАвторID
Загрузка истории…
+
КотКотятаФотоДата (UTC+3)СообщениеАвторID
Загрузка истории…
@@ -170,7 +170,7 @@ if (gallery.childElementCount) node.append(gallery); else node.textContent = '—'; return node; } // Formats stored ISO timestamps for the Russian admin table without shifting their clock time. - function displayDate(value) { const match = String(value || '').match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}:\d{2}:\d{2})/); return match ? `${match[4]} ${match[3]}-${match[2]}-${match[1]}` : (value || '—'); } + function displayDate(value) { const text = String(value || ''); if (!text) return '—'; const normalized = text.includes('T') ? text : text.replace(' ', 'T'); const instant = new Date(/[zZ]|[+-]\d\d:\d\d$/.test(normalized) ? normalized : `${normalized}Z`); return Number.isNaN(instant.valueOf()) ? text : new Intl.DateTimeFormat('ru-RU', {timeZone: 'Europe/Moscow', dateStyle: 'short', timeStyle: 'medium'}).format(instant); } // Produces the normalized value used by the selected table sort column. function textForSort(item, field) { const input = item.input || {}; const person = personData(input); const kittens = kittenEntries(input); if (field === 'cat') return `${person.name} ${person.id}`.toLocaleLowerCase(); if (field === 'kitten') return kittens.map(item => `${item.name} ${item.id}`).join(',').toLocaleLowerCase(); if (field === 'photo') return (input.attachments || []).length; if (field === 'date') return item.created_at || ''; if (field === 'message') return item.message || ''; if (field === 'author') return String(item.actor_id || ''); return Number(item.id) || 0; } // Maps an input payload to the report category used by tabs and filters.