Skip to content

Commit 093eb32

Browse files
committed
Enhance InvestorClient and LedgerClient with improved response handling and new functionality
- Updated the `InvestorClient` to strip `None` values from GraphQL query variables before execution, ensuring proper handling of optional parameters. - Modified the `delete_portfolio`, `delete_security`, and `delete_position` methods to return a default response only when the server response is `None`, preventing overwriting of valid server responses. - Introduced the `build_fact_grid` method in `LedgerClient` for generating multi-dimensional fact grids, along with a corresponding request model. - Enhanced the `camel_to_snake` function to correctly handle acronyms during conversion, improving the handling of GraphQL field names. These changes improve the robustness and usability of the client interfaces for investment and ledger operations.
1 parent dcaeb36 commit 093eb32

7 files changed

Lines changed: 326 additions & 13 deletions

File tree

‎robosystems_client/extensions/investor_client.py‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
sync_detailed as op_update_security,
4646
)
4747
from ..client import AuthenticatedClient
48-
from ..graphql.client import GraphQLClient
48+
from ..graphql.client import GraphQLClient, strip_none_vars
4949
from ..graphql.queries.investor import (
5050
GET_HOLDINGS_QUERY,
5151
GET_PORTFOLIO_QUERY,
@@ -111,7 +111,13 @@ def _query(
111111
query: str,
112112
variables: dict[str, Any] | None = None,
113113
) -> dict[str, Any]:
114-
return self._get_graphql_client().execute(graph_id, query, variables)
114+
"""Execute a read against the per-graph GraphQL endpoint.
115+
116+
``None`` values in ``variables`` are stripped before sending — see
117+
the ``LedgerClient._query`` docstring for the rationale.
118+
"""
119+
cleaned = strip_none_vars(variables) if variables else None
120+
return self._get_graphql_client().execute(graph_id, query, cleaned)
115121

116122
def _call_op(self, label: str, response: Any) -> OperationEnvelope:
117123
if response.status_code not in (HTTPStatus.OK, HTTPStatus.ACCEPTED):
@@ -170,7 +176,7 @@ def delete_portfolio(self, graph_id: str, portfolio_id: str) -> dict[str, Any]:
170176
graph_id=graph_id, body=body, client=self._get_client()
171177
)
172178
envelope = self._call_op("Delete portfolio", response)
173-
return envelope.result or {"deleted": True}
179+
return envelope.result if envelope.result is not None else {"deleted": True}
174180

175181
# ── Securities ──────────────────────────────────────────────────────
176182

@@ -233,7 +239,7 @@ def delete_security(self, graph_id: str, security_id: str) -> dict[str, Any]:
233239
graph_id=graph_id, body=body, client=self._get_client()
234240
)
235241
envelope = self._call_op("Delete security", response)
236-
return envelope.result or {"deleted": True}
242+
return envelope.result if envelope.result is not None else {"deleted": True}
237243

238244
# ── Positions ───────────────────────────────────────────────────────
239245

@@ -296,7 +302,7 @@ def delete_position(self, graph_id: str, position_id: str) -> dict[str, Any]:
296302
graph_id=graph_id, body=body, client=self._get_client()
297303
)
298304
envelope = self._call_op("Delete position", response)
299-
return envelope.result or {"deleted": True}
305+
return envelope.result if envelope.result is not None else {"deleted": True}
300306

301307
# ── Holdings (aggregation) ─────────────────────────────────────────
302308

‎robosystems_client/extensions/ledger_client.py‎

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@
2929
from ..api.extensions_robo_ledger.op_auto_map_elements import (
3030
sync_detailed as op_auto_map_elements,
3131
)
32+
from ..api.extensions_robo_ledger.op_build_fact_grid import (
33+
sync_detailed as op_build_fact_grid,
34+
)
3235
from ..api.extensions_robo_ledger.op_close_period import (
3336
sync_detailed as op_close_period,
3437
)
@@ -69,7 +72,7 @@
6972
sync_detailed as op_update_entity,
7073
)
7174
from ..client import AuthenticatedClient
72-
from ..graphql.client import GraphQLClient
75+
from ..graphql.client import GraphQLClient, strip_none_vars
7376
from ..graphql.queries.ledger import (
7477
GET_ACCOUNT_ROLLUPS_QUERY,
7578
GET_ACCOUNT_TREE_QUERY,
@@ -123,6 +126,7 @@
123126
from ..models.auto_map_elements_operation import AutoMapElementsOperation
124127
from ..models.close_period_operation import ClosePeriodOperation
125128
from ..models.create_closing_entry_operation import CreateClosingEntryOperation
129+
from ..models.create_view_request import CreateViewRequest
126130
from ..models.create_manual_closing_entry_request import CreateManualClosingEntryRequest
127131
from ..models.create_manual_closing_entry_request_entry_type import (
128132
CreateManualClosingEntryRequestEntryType,
@@ -204,8 +208,15 @@ def _query(
204208
query: str,
205209
variables: dict[str, Any] | None = None,
206210
) -> dict[str, Any]:
207-
"""Execute a read against the per-graph GraphQL endpoint."""
208-
return self._get_graphql_client().execute(graph_id, query, variables)
211+
"""Execute a read against the per-graph GraphQL endpoint.
212+
213+
``None`` values in ``variables`` are stripped before sending — the
214+
facade takes ``None`` to mean "not provided", and some Strawberry
215+
resolvers treat an explicit ``null`` differently from an unset arg.
216+
See ``strip_none_vars`` in ``graphql/client.py``.
217+
"""
218+
cleaned = strip_none_vars(variables) if variables else None
219+
return self._get_graphql_client().execute(graph_id, query, cleaned)
209220

210221
def _unwrap(self, label: str, envelope: OperationEnvelope | Any) -> Any:
211222
"""Unwrap an operation envelope and return `result` (None on failure)."""
@@ -515,7 +526,7 @@ def delete_mapping_association(
515526
graph_id=graph_id, body=body, client=self._get_client()
516527
)
517528
envelope = self._call_op("Delete mapping association", response)
518-
return envelope.result or {"deleted": True}
529+
return envelope.result if envelope.result is not None else {"deleted": True}
519530

520531
def auto_map_elements(self, graph_id: str, mapping_id: str) -> dict[str, Any]:
521532
"""Trigger the AI MappingAgent (async). Returns an operation ack."""
@@ -714,6 +725,33 @@ def create_manual_closing_entry(
714725
envelope = self._call_op("Create manual closing entry", response)
715726
return envelope.result or {}
716727

728+
# ── Fact grid (graph-backed analytical query) ─────────────────────
729+
730+
def build_fact_grid(self, graph_id: str, request: dict[str, Any]) -> dict[str, Any]:
731+
"""Build a multi-dimensional fact grid against the graph schema.
732+
733+
This is a graph-database *read* dispatched through the operation
734+
surface — it runs against LadybugDB (not the extensions OLTP
735+
database) and returns a deduplicated pivot table of XBRL facts.
736+
The same operation works for roboledger tenant graphs (after
737+
materialization) and for the SEC shared repository, which uses the
738+
same hypercube schema.
739+
740+
``request`` accepts any fields of
741+
``robosystems_client.models.create_view_request.CreateViewRequest``:
742+
``elements`` (qnames), ``canonical_concepts``, ``periods``,
743+
``entities``, ``form``, ``fiscal_year``, ``fiscal_period``,
744+
``period_type``, ``include_summary``, ``view_config``. The legacy
745+
model name ``CreateViewRequest`` is a holdover from when fact grids
746+
were exposed under a ``/views`` route; the shape is unchanged.
747+
"""
748+
body = CreateViewRequest.from_dict(request)
749+
response = op_build_fact_grid(
750+
graph_id=graph_id, body=body, client=self._get_client()
751+
)
752+
envelope = self._call_op("Build fact grid", response)
753+
return envelope.result or {}
754+
717755
# ── Closing book ───────────────────────────────────────────────────
718756

719757
def get_closing_book_structures(self, graph_id: str) -> dict[str, Any] | None:

‎robosystems_client/extensions/report_client.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,4 +296,4 @@ def remove_member(
296296
graph_id=graph_id, body=body, client=self._get_client()
297297
)
298298
envelope = self._call_op("Remove publish list member", response)
299-
return envelope.result or {"deleted": True}
299+
return envelope.result if envelope.result is not None else {"deleted": True}

‎robosystems_client/graphql/client.py‎

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -124,12 +124,46 @@ def execute(
124124

125125
# ── Shared helpers for query parsers ──────────────────────────────────
126126

127-
_CAMEL_TO_SNAKE = re.compile(r"(?<!^)(?=[A-Z])")
127+
# Two-group pattern that correctly handles consecutive uppercase letters
128+
# (acronyms). A naive `(?<!^)(?=[A-Z])` pattern explodes things like
129+
# "getCIK" into "get_c_i_k"; this one produces "get_cik". The first
130+
# alternative `([A-Z]+)(?=[A-Z][a-z])` matches a run of caps followed by
131+
# an acronym boundary (e.g. "XMLData" → "XML|Data"). The second
132+
# `([a-z\d])([A-Z])` matches the usual camelCase boundary.
133+
_CAMEL_TO_SNAKE = re.compile(r"([A-Z]+)(?=[A-Z][a-z])|([a-z\d])([A-Z])")
128134

129135

130136
def camel_to_snake(name: str) -> str:
131-
"""Convert a camelCase field name to snake_case."""
132-
return _CAMEL_TO_SNAKE.sub("_", name).lower()
137+
"""Convert a camelCase field name to snake_case.
138+
139+
Handles acronyms correctly: ``getCIK`` → ``get_cik``, ``XMLData`` →
140+
``xml_data``, ``parentSIC`` → ``parent_sic``. Without acronym-aware
141+
splitting, each uppercase letter in an acronym would become its own
142+
underscore-separated token, producing garbled keys at the GraphQL →
143+
Pydantic boundary.
144+
"""
145+
146+
def _sub(match: re.Match[str]) -> str:
147+
# Group 1 matches acronym runs like "XML" in "XMLData". Groups 2+3
148+
# match a lowercase/digit followed by an uppercase letter.
149+
if match.group(1) is not None:
150+
return match.group(1) + "_"
151+
return match.group(2) + "_" + match.group(3)
152+
153+
return _CAMEL_TO_SNAKE.sub(_sub, name).lower()
154+
155+
156+
def strip_none_vars(variables: dict[str, Any]) -> dict[str, Any]:
157+
"""Drop ``None`` values from a GraphQL variables dict.
158+
159+
Strawberry distinguishes between an argument being *unset* and being
160+
explicitly ``null`` — some resolvers treat ``isActive: null`` as
161+
"filter for inactive" rather than "don't filter". The facade takes
162+
``None`` to mean "not provided", so strip those keys before sending
163+
the request instead of letting JSON serialization turn them into
164+
explicit GraphQL ``null`` literals.
165+
"""
166+
return {k: v for k, v in variables.items() if v is not None}
133167

134168

135169
def keys_to_snake(value: Any) -> Any:

‎tests/test_graphql_helpers.py‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
"""Unit tests for ``robosystems_client.graphql.client`` module-level helpers.
2+
3+
These helpers sit on the GraphQL → Pydantic boundary. ``camel_to_snake``
4+
and ``keys_to_snake`` normalize the camelCase field names Strawberry
5+
emits into the snake_case shape the generated ``from_dict`` helpers
6+
expect. ``strip_none_vars`` drops ``None`` variables so the facade's
7+
"``None`` means not provided" convention doesn't accidentally surface as
8+
explicit GraphQL ``null`` in resolvers that distinguish the two.
9+
"""
10+
11+
from __future__ import annotations
12+
13+
import pytest
14+
15+
from robosystems_client.graphql.client import (
16+
camel_to_snake,
17+
keys_to_snake,
18+
strip_none_vars,
19+
)
20+
21+
22+
@pytest.mark.unit
23+
class TestCamelToSnake:
24+
"""``camel_to_snake`` must handle acronyms without shredding them.
25+
26+
A naive regex like ``(?<!^)(?=[A-Z])`` would turn ``getCIK`` into
27+
``get_c_i_k``. The acronym-aware two-group pattern handles CIK / URI /
28+
XML / SIC / LEI cases that appear in the real backend schema.
29+
"""
30+
31+
def test_simple_camel_case(self):
32+
assert camel_to_snake("fooBar") == "foo_bar"
33+
assert camel_to_snake("legalName") == "legal_name"
34+
assert camel_to_snake("isActive") == "is_active"
35+
36+
def test_already_snake_case(self):
37+
assert camel_to_snake("already_snake") == "already_snake"
38+
assert camel_to_snake("id") == "id"
39+
40+
def test_trailing_acronym(self):
41+
assert camel_to_snake("getCIK") == "get_cik"
42+
assert camel_to_snake("parentLEI") == "parent_lei"
43+
assert camel_to_snake("parentSIC") == "parent_sic"
44+
45+
def test_leading_acronym(self):
46+
assert camel_to_snake("XMLData") == "xml_data"
47+
assert camel_to_snake("URIPath") == "uri_path"
48+
49+
def test_middle_acronym(self):
50+
assert camel_to_snake("parseXMLData") == "parse_xml_data"
51+
assert camel_to_snake("fetchJSONResponse") == "fetch_json_response"
52+
53+
def test_single_letter_words(self):
54+
assert camel_to_snake("aB") == "a_b"
55+
assert camel_to_snake("xYZ") == "x_yz"
56+
57+
58+
@pytest.mark.unit
59+
class TestKeysToSnake:
60+
def test_flat_dict(self):
61+
assert keys_to_snake({"legalName": "ACME", "entityId": "ent_1"}) == {
62+
"legal_name": "ACME",
63+
"entity_id": "ent_1",
64+
}
65+
66+
def test_nested_dict(self):
67+
result = keys_to_snake(
68+
{
69+
"entityId": "ent_1",
70+
"metadata": {"sourceGraphId": "kg_1", "parentCIK": "0001234567"},
71+
}
72+
)
73+
assert result == {
74+
"entity_id": "ent_1",
75+
"metadata": {"source_graph_id": "kg_1", "parent_cik": "0001234567"},
76+
}
77+
78+
def test_list_of_dicts(self):
79+
result = keys_to_snake(
80+
[{"entityId": "ent_1"}, {"entityId": "ent_2", "isActive": True}]
81+
)
82+
assert result == [
83+
{"entity_id": "ent_1"},
84+
{"entity_id": "ent_2", "is_active": True},
85+
]
86+
87+
def test_preserves_scalars(self):
88+
assert keys_to_snake("unchanged") == "unchanged"
89+
assert keys_to_snake(42) == 42
90+
assert keys_to_snake(None) is None
91+
assert keys_to_snake(True) is True
92+
93+
94+
@pytest.mark.unit
95+
class TestStripNoneVars:
96+
def test_removes_none_values(self):
97+
assert strip_none_vars(
98+
{"entityId": None, "limit": 100, "offset": 0, "securityType": None}
99+
) == {"limit": 100, "offset": 0}
100+
101+
def test_keeps_falsy_but_not_none(self):
102+
# False, 0, "", and [] are all valid variable values that must not
103+
# be stripped — only None means "not provided".
104+
result = strip_none_vars({"isActive": False, "limit": 0, "search": "", "tags": []})
105+
assert result == {"isActive": False, "limit": 0, "search": "", "tags": []}
106+
107+
def test_all_none(self):
108+
assert strip_none_vars({"a": None, "b": None}) == {}
109+
110+
def test_empty(self):
111+
assert strip_none_vars({}) == {}

‎tests/test_investor_client.py‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,39 @@ def test_delete_portfolio(self, mock_op, mock_config, graph_id):
131131
result = client.delete_portfolio(graph_id, "port_1")
132132
assert result["deleted"] is True
133133

134+
@patch("robosystems_client.extensions.investor_client.op_delete_portfolio")
135+
def test_delete_portfolio_returns_server_response_when_present(
136+
self, mock_op, mock_config, graph_id
137+
):
138+
"""The facade must not overwrite a non-empty server response with the stub.
139+
140+
Before the ``is not None`` fix, an empty ``{}`` from the server would
141+
trip the ``or {...}`` fallback — but so would any falsy value. This
142+
exercises the happy path: a real response with fields carries through.
143+
"""
144+
envelope = _envelope(
145+
"delete-portfolio",
146+
{"id": "port_1", "deleted_at": "2026-04-14T12:00:00Z"},
147+
)
148+
mock_op.return_value = _mock_response(envelope)
149+
client = InvestorClient(mock_config)
150+
result = client.delete_portfolio(graph_id, "port_1")
151+
assert result["id"] == "port_1"
152+
assert result["deleted_at"] == "2026-04-14T12:00:00Z"
153+
assert "deleted" not in result # stub didn't fire
154+
155+
@patch("robosystems_client.extensions.investor_client.op_delete_portfolio")
156+
def test_delete_portfolio_stubs_when_result_is_none(
157+
self, mock_op, mock_config, graph_id
158+
):
159+
"""When the server returns an envelope with ``result: null`` the facade
160+
substitutes a ``{"deleted": True}`` stub so callers get a dict."""
161+
envelope = _envelope("delete-portfolio", None)
162+
mock_op.return_value = _mock_response(envelope)
163+
client = InvestorClient(mock_config)
164+
result = client.delete_portfolio(graph_id, "port_1")
165+
assert result == {"deleted": True}
166+
134167

135168
# ── Securities ─────────────────────────────────────────────────────────
136169

@@ -151,6 +184,25 @@ def test_list_securities_forwards_entity_filter(
151184
client.list_securities(graph_id, entity_id="ent_1")
152185
variables = mock_execute.call_args[0][2]
153186
assert variables["entityId"] == "ent_1"
187+
# None filters are stripped so Strawberry sees them as "not provided"
188+
assert "securityType" not in variables
189+
assert "isActive" not in variables
190+
191+
@patch("robosystems_client.graphql.client.GraphQLClient.execute")
192+
def test_list_securities_all_none_filters_stripped(
193+
self, mock_execute, mock_config, graph_id
194+
):
195+
mock_execute.return_value = {
196+
"securities": {
197+
"securities": [],
198+
"pagination": {"total": 0, "limit": 100, "offset": 0, "hasMore": False},
199+
}
200+
}
201+
client = InvestorClient(mock_config)
202+
client.list_securities(graph_id)
203+
variables = mock_execute.call_args[0][2]
204+
# Pagination defaults stay; every optional filter is gone.
205+
assert variables == {"limit": 100, "offset": 0}
154206

155207
@patch("robosystems_client.extensions.investor_client.op_create_security")
156208
def test_create_security(self, mock_op, mock_config, graph_id):

0 commit comments

Comments
 (0)