fix: present web timestamps in UTC+3
This commit is contained in:
1 parent
00bbe66c77
commit
cffaaac755
8 files changed
+25
-18
No files matched your search
@@ -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
|
||||
|
||||
@@ -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'<c r="{reference}" s="2"><v>{serial:.10f}</v></c>'
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
return f'<c r="{reference}"{style}><v>{value}</v></c>'
|
||||
return f'<c r="{reference}" t="inlineStr"{style}><is><t>{escape(str(value or ""))}</t></is></c>'
|
||||
|
||||
|
||||
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 = [
|
||||
'<row r="1" ht="24">' + ''.join(_cell(index, 1, value, header=True) for index, value in enumerate(headers, 1)) + '</row>'
|
||||
'<row r="1" ht="24">' + ''.join(_cell(index, 1, value, header=True, display_timezone=display_timezone) for index, value in enumerate(headers, 1)) + '</row>'
|
||||
]
|
||||
for row_number, row in enumerate(rows, 2):
|
||||
sheet_rows.append('<row r="%d">%s</row>' % (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'<col min="{index}" max="{index}" width="{min(max(max([len(header)] + [len(str(row[index - 1] or "")) for row in rows]) + 2, 14), 48)}" customWidth="1"/>' for index, header in enumerate(headers, 1))
|
||||
sheet = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||||
|
||||
+3
-3
@@ -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()
|
||||
|
||||
Reference in new issue
Block a user