2026-11-19 12:26:35 +01:00
|
|
|
"""Small shared helpers (pure functions, no state).
|
|
|
|
|
|
|
|
|
|
- ``to_int`` / ``is_active_flag`` / ``is_filled`` — safe parsing of LS values
|
|
|
|
|
- ``parse_responses_json`` / ``decode_export_json`` — decode a JSON responses export
|
|
|
|
|
- ``summary_counts`` — completed/total counts from a get_summary result
|
PyLimeRPC 0.2.0 — prompts.md Prompt 1-4
- responses.py: get_summary() (raw RPC get_summary), count_responses() ->
frozen ResponseCounts(completed, incomplete, total), export_responses_auto()
with automatic format fallback (xlsx -> xls -> csv) on IWriter errors
- utils.py: summary_counts_full() -> (completed, incomplete, total) with
per-LS-version key fallbacks; summary_counts left untouched
- surveys.py: get_survey_by_sid() (dict | None), get_survey_info() ->
frozen SurveyInfo(sid, title, active)
- tokens.py: documented that extra/custom token attributes (attribute_1, ...)
pass through unchanged in add_participants/list_participants
- LsClient: get_summary, count_responses, get_survey_by_sid, get_survey_info,
export_responses_auto; __all__ + re-exports updated
- README: new "Response counts & summary" section + usage examples
- .gitignore: prompts.md added (local-only docs, like werkdocument.md)
- version 0.1.0 -> 0.2.0 (__init__.py + pyproject.toml)
- tests: +27 FakeRpc unit tests (96 passed, 2 deselected)
Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-20 11:56:03 +01:00
|
|
|
- ``summary_counts_full`` — (completed, incomplete, total) from a get_summary result
|
2026-11-19 12:26:35 +01:00
|
|
|
- ``raise_for_status`` — LimeSurvey sometimes puts ``{"status": "..."}`` in the
|
|
|
|
|
*result* (instead of ``error``); this detects that and raises an
|
|
|
|
|
``LsApiError`` (or ``LsAuthError`` for session/auth texts).
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import base64
|
|
|
|
|
import json
|
|
|
|
|
from typing import Any
|
|
|
|
|
|
|
|
|
|
from .errors import LsApiError, LsAuthError
|
|
|
|
|
|
|
|
|
|
_AUTH_STATUS_HINTS = (
|
|
|
|
|
"session key",
|
|
|
|
|
"invalid user",
|
|
|
|
|
"password",
|
|
|
|
|
"permission",
|
|
|
|
|
"unauthorized",
|
|
|
|
|
"not authorized",
|
|
|
|
|
"login",
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def to_int(value: Any) -> int | None:
|
|
|
|
|
"""Safe conversion to int; ``None`` for empty/invalid values."""
|
|
|
|
|
if value is None:
|
|
|
|
|
return None
|
|
|
|
|
text = str(value).strip()
|
|
|
|
|
if not text:
|
|
|
|
|
return None
|
|
|
|
|
try:
|
|
|
|
|
return int(text)
|
|
|
|
|
except ValueError:
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def is_active_flag(value: Any) -> bool:
|
|
|
|
|
"""LS ``active`` field: ``"Y"`` / ``"1"`` / ``"true"`` → True."""
|
|
|
|
|
return str(value).strip().upper() in {"Y", "1", "TRUE"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def is_filled(value: Any) -> bool:
|
|
|
|
|
"""Is an answer value filled (not None, empty string or ``"[]"``)?"""
|
|
|
|
|
if value is None:
|
|
|
|
|
return False
|
|
|
|
|
if isinstance(value, str) and value.strip() == "":
|
|
|
|
|
return False
|
|
|
|
|
if value == "[]":
|
|
|
|
|
return False
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def parse_responses_json(text: str) -> list[dict[str, Any]]:
|
|
|
|
|
"""Parse a JSON responses export (already base64-decoded) into ``list[dict]``."""
|
|
|
|
|
parsed = json.loads(text)
|
|
|
|
|
if isinstance(parsed, dict) and isinstance(parsed.get("responses"), list):
|
|
|
|
|
return parsed["responses"]
|
|
|
|
|
if isinstance(parsed, list):
|
|
|
|
|
return parsed
|
|
|
|
|
if isinstance(parsed, dict):
|
|
|
|
|
return [parsed]
|
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def decode_export_json(result: Any) -> list[dict[str, Any]]:
|
|
|
|
|
"""Decode a base64 JSON ``export_responses`` result into ``list[dict]``."""
|
|
|
|
|
if not isinstance(result, str) or not result:
|
|
|
|
|
return []
|
|
|
|
|
decoded = base64.b64decode(result)
|
|
|
|
|
return parse_responses_json(decoded.decode("utf-8"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def normalize_sid(sid: Any) -> Any:
|
|
|
|
|
"""Numeric sid strings → int (LS expects ``iSurveyID`` as int)."""
|
|
|
|
|
as_int = to_int(sid)
|
|
|
|
|
return as_int if as_int is not None else sid
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def summary_counts(summary: dict[str, Any]) -> tuple[int | None, int | None]:
|
|
|
|
|
"""Extract (completed, total) response counts from a ``get_summary`` result.
|
|
|
|
|
|
|
|
|
|
Key names differ per LS version; the first match wins.
|
|
|
|
|
"""
|
|
|
|
|
completed = None
|
|
|
|
|
total = None
|
|
|
|
|
for key in ("completed_responses", "responses_completed", "completed"):
|
|
|
|
|
if key in summary:
|
|
|
|
|
completed = to_int(summary.get(key))
|
|
|
|
|
break
|
|
|
|
|
for key in ("responses", "full_responses", "responses_total", "all_responses"):
|
|
|
|
|
if key in summary:
|
|
|
|
|
total = to_int(summary.get(key))
|
|
|
|
|
break
|
|
|
|
|
return completed, total
|
|
|
|
|
|
|
|
|
|
|
PyLimeRPC 0.2.0 — prompts.md Prompt 1-4
- responses.py: get_summary() (raw RPC get_summary), count_responses() ->
frozen ResponseCounts(completed, incomplete, total), export_responses_auto()
with automatic format fallback (xlsx -> xls -> csv) on IWriter errors
- utils.py: summary_counts_full() -> (completed, incomplete, total) with
per-LS-version key fallbacks; summary_counts left untouched
- surveys.py: get_survey_by_sid() (dict | None), get_survey_info() ->
frozen SurveyInfo(sid, title, active)
- tokens.py: documented that extra/custom token attributes (attribute_1, ...)
pass through unchanged in add_participants/list_participants
- LsClient: get_summary, count_responses, get_survey_by_sid, get_survey_info,
export_responses_auto; __all__ + re-exports updated
- README: new "Response counts & summary" section + usage examples
- .gitignore: prompts.md added (local-only docs, like werkdocument.md)
- version 0.1.0 -> 0.2.0 (__init__.py + pyproject.toml)
- tests: +27 FakeRpc unit tests (96 passed, 2 deselected)
Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-20 11:56:03 +01:00
|
|
|
def _summary_int(summary: dict[str, Any], keys: tuple[str, ...]) -> int:
|
|
|
|
|
"""First present key of ``keys`` as int; missing/invalid → 0."""
|
|
|
|
|
for key in keys:
|
|
|
|
|
if key in summary:
|
|
|
|
|
value = to_int(summary[key])
|
|
|
|
|
return value if value is not None else 0
|
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def summary_counts_full(summary: dict[str, Any]) -> tuple[int, int, int]:
|
|
|
|
|
"""Extract (completed, incomplete, total) from a ``get_summary`` result.
|
|
|
|
|
|
|
|
|
|
Key names differ per LS version; the first present key wins:
|
|
|
|
|
``completed_responses`` (fallback ``responses_completed`` / ``completed``) and
|
|
|
|
|
``incomplete_responses`` (fallback ``in_progress_responses``). ``total`` is
|
|
|
|
|
``full_responses`` when present, else ``completed + incomplete``.
|
|
|
|
|
Missing or invalid values count as 0.
|
|
|
|
|
"""
|
|
|
|
|
completed = _summary_int(summary, ("completed_responses", "responses_completed", "completed"))
|
|
|
|
|
incomplete = _summary_int(summary, ("incomplete_responses", "in_progress_responses"))
|
|
|
|
|
full = to_int(summary["full_responses"]) if "full_responses" in summary else None
|
|
|
|
|
total = full if full is not None else completed + incomplete
|
|
|
|
|
return completed, incomplete, total
|
|
|
|
|
|
|
|
|
|
|
2026-11-19 12:26:35 +01:00
|
|
|
def is_status_error(result: Any) -> bool:
|
|
|
|
|
"""True if ``result`` is an LS error dict: ``{"status": "..."}`` or
|
|
|
|
|
``{"status": "...", "error_code": "..."}``.
|
|
|
|
|
|
|
|
|
|
A survey-properties dict has a ``status`` key among many other keys and
|
|
|
|
|
must therefore NOT be treated as an error.
|
|
|
|
|
"""
|
|
|
|
|
return (
|
|
|
|
|
isinstance(result, dict)
|
|
|
|
|
and "status" in result
|
|
|
|
|
and set(result.keys()) <= {"status", "error_code", "error"}
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def raise_for_status(result: Any, method: str) -> Any:
|
|
|
|
|
"""Raise LsApiError/LsAuthError if ``result`` is a ``{"status": ...}`` error dict.
|
|
|
|
|
|
|
|
|
|
Returns ``result`` unchanged otherwise.
|
|
|
|
|
"""
|
|
|
|
|
if is_status_error(result):
|
|
|
|
|
status = str(result["status"])
|
|
|
|
|
low = status.lower()
|
|
|
|
|
exc_cls = LsAuthError if any(h in low for h in _AUTH_STATUS_HINTS) else LsApiError
|
|
|
|
|
raise exc_cls(
|
|
|
|
|
f"RPC {method!r} returned a status error: {status!r}",
|
|
|
|
|
method=method,
|
|
|
|
|
rpc_message=status,
|
|
|
|
|
raw=result,
|
|
|
|
|
)
|
|
|
|
|
return result
|