"""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 - ``summary_counts_full`` — (completed, incomplete, total) from a get_summary result - ``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 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 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