feat: export filtered admin data to xlsx
This commit is contained in:
1 parent
ab3bbd6672
commit
00bbe66c77
8 files changed
+249
-11
No files matched your search
@@ -0,0 +1,49 @@
|
||||
"""Shared parsing and application of the administrative time filters."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
|
||||
PERIODS = {
|
||||
"all": None, "year": timedelta(days=365), "month": timedelta(days=30),
|
||||
"week": timedelta(days=7), "day": timedelta(days=1), "12h": timedelta(hours=12),
|
||||
"6h": timedelta(hours=6), "4h": timedelta(hours=4), "2h": timedelta(hours=2),
|
||||
"1h": timedelta(hours=1),
|
||||
}
|
||||
|
||||
|
||||
def parse_timestamp(value: str, *, end_of_day: bool = False) -> datetime:
|
||||
"""Parse an ISO date/time stored by either SQLite or PostgreSQL as UTC."""
|
||||
text = value.strip().replace("Z", "+00:00")
|
||||
if len(text) == 10:
|
||||
text += "T23:59:59.999999" if end_of_day else "T00:00:00"
|
||||
try:
|
||||
result = datetime.fromisoformat(text)
|
||||
except ValueError as exc:
|
||||
raise ValueError("Дата должна быть в формате ГГГГ-ММ-ДД") from exc
|
||||
return result.replace(tzinfo=result.tzinfo or timezone.utc).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]:
|
||||
"""Return inclusive UTC bounds for a named period or an explicit range."""
|
||||
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)
|
||||
if start > end:
|
||||
raise ValueError("Дата начала не может быть позже даты окончания")
|
||||
return start, end
|
||||
if period not in PERIODS:
|
||||
raise ValueError("Неизвестный период")
|
||||
duration = PERIODS[period]
|
||||
if duration is None:
|
||||
return None, None
|
||||
end = (now or datetime.now(timezone.utc)).astimezone(timezone.utc)
|
||||
return end - duration, end
|
||||
|
||||
|
||||
def matches_period(record: dict[str, Any], start: datetime | None, end: datetime | None) -> bool:
|
||||
"""Check a serialized store record against inclusive UTC bounds."""
|
||||
created = parse_timestamp(str(record["created_at"]))
|
||||
return (start is None or created >= start) and (end is None or created <= end)
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Minimal XLSX writer for administrative exports without a runtime dependency."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from io import BytesIO
|
||||
from xml.sax.saxutils import escape
|
||||
from zipfile import ZIP_DEFLATED, ZipFile
|
||||
|
||||
|
||||
def _cell(column: int, row: int, value: object, *, header: bool = False) -> str:
|
||||
name = ""
|
||||
number = column
|
||||
while number:
|
||||
number, remainder = divmod(number - 1, 26)
|
||||
name = chr(65 + remainder) + name
|
||||
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
|
||||
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."""
|
||||
sheet_rows = [
|
||||
'<row r="1" ht="24">' + ''.join(_cell(index, 1, value, header=True) 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,)
|
||||
)))
|
||||
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"?>'
|
||||
'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
|
||||
'<sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/></sheetView></sheetViews>'
|
||||
f'<cols>{widths}</cols><sheetData>{"".join(sheet_rows)}</sheetData><autoFilter ref="A1:{chr(64 + len(headers))}{len(rows) + 1}"/></worksheet>')
|
||||
buffer = BytesIO()
|
||||
with ZipFile(buffer, 'w', ZIP_DEFLATED) as archive:
|
||||
archive.writestr('[Content_Types].xml', '<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/></Types>')
|
||||
archive.writestr('_rels/.rels', '<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>')
|
||||
archive.writestr('xl/workbook.xml', f'<?xml version="1.0" encoding="UTF-8"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="{escape(sheet_name)}" sheetId="1" r:id="rId1"/></sheets></workbook>')
|
||||
archive.writestr('xl/_rels/workbook.xml.rels', '<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>')
|
||||
archive.writestr('xl/styles.xml', '<?xml version="1.0" encoding="UTF-8"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><numFmts count="1"><numFmt numFmtId="164" formatCode="dd.mm.yyyy hh:mm"/></numFmts><fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><color rgb="FFFFFFFF"/><sz val="11"/><name val="Calibri"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="solid"><fgColor rgb="FF9A542E"/><bgColor indexed="64"/></patternFill></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellXfs count="3"><xf fontId="0" fillId="0" borderId="0"/><xf fontId="1" fillId="1" borderId="0" applyFont="1" applyFill="1"/><xf fontId="0" fillId="0" borderId="0" numFmtId="164" applyNumberFormat="1"/></cellXfs></styleSheet>')
|
||||
archive.writestr('xl/worksheets/sheet1.xml', sheet)
|
||||
return buffer.getvalue()
|
||||
Reference in new issue
Block a user