"""Query surveys via the RemoteControl API. - ``list_surveys(client, session_key, owner_id=None, group_id=None)`` — list of survey dicts (``owner_id`` is sent as the 2nd RPC param ``iUserID``; ``group_id`` filters client-side on ``group_id``/``gsid`` when present) - ``get_survey_properties(client, session_key, sid, properties=None)`` — properties dict of a single survey - ``filter_active(surveys)`` — only active surveys (``active == "Y"``) """ from __future__ import annotations from typing import Any, Iterable from .errors import LsApiError from .rpc import RpcClient from .utils import is_active_flag, raise_for_status, to_int _GROUP_KEYS = ("group_id", "gsid", "group") def _survey_group_id(survey: dict[str, Any]) -> Any: for key in _GROUP_KEYS: if key in survey: return survey[key] return None def list_surveys( client: RpcClient, session_key: str, owner_id: int | str | None = None, group_id: int | str | None = None, ) -> list[dict[str, Any]]: """List all surveys the session key has access to. Args: client: an ``RpcClient``. session_key: a valid session key. owner_id: optional, sent as the 2nd RPC parameter (``iUserID``). group_id: optional, client-side filter on a group field in the result. Returns: List of survey dicts (``sid``, ``surveyls_title``, ``active``, ...). Raises: LsAuthError: invalid session key; LsApiError: other API errors. """ params: list[Any] = [session_key] if owner_id is not None: as_int = to_int(owner_id) params.append(as_int if as_int is not None else owner_id) result = client.call("list_surveys", params) raise_for_status(result, "list_surveys") if not isinstance(result, list): raise LsApiError( f"list_surveys did not return a list: {result!r}", method="list_surveys", raw=result, ) surveys = [s for s in result if isinstance(s, dict)] if group_id is not None: surveys = [s for s in surveys if str(_survey_group_id(s)) == str(group_id)] return surveys def get_survey_properties( client: RpcClient, session_key: str, sid: int | str, properties: Iterable[str] | None = None, ) -> dict[str, Any]: """Get the properties of a single survey. Args: client: an ``RpcClient``. session_key: a valid session key. sid: survey ID (numeric strings are converted to int). properties: optional list of property names; None = all. Returns: Dict with survey properties (contains e.g. ``sid``, ``surveyls_title``, ``active``). """ sid_int = to_int(sid) params: list[Any] = [session_key, sid_int if sid_int is not None else sid] if properties: params.append(list(properties)) result = client.call("get_survey_properties", params) raise_for_status(result, "get_survey_properties") if not isinstance(result, dict): raise LsApiError( f"get_survey_properties did not return a dict: {result!r}", method="get_survey_properties", raw=result, ) return result def filter_active(surveys: Iterable[dict[str, Any]]) -> list[dict[str, Any]]: """Filter a survey list to active surveys only (``active == "Y"``).""" return [s for s in surveys if is_active_flag(s.get("active"))]