Skip to content

Commit 398303b

Browse files
authored
feat: opening balances (#260)
## Summary The regeneration for robosystems RoboFinSystems/robosystems#1852, opening balances, taken against the local stack running `main` at its merge. A ledger whose history does not come with it records the balance sheet it starts from as one `opening` entry dated the day before its first fiscal month, and the live statement now says which columns it left out because they reach back before the books begin. A client minor; the version moves at publish. The TypeScript twin is RoboFinSystems/robosystems-typescript-client#276. ## Changes - **Generated tier**: - The `record-opening-balance` operation and its models: `RecordOpeningBalanceRequest` and `OpeningBalanceInput`. - `omitted_periods` on `LiveFinancialStatementResponse`: the columns left out because they would show a partial figure, not the months before the books. - No other drift: the GraphQL schema is unchanged. - **Facade**: `LedgerClient.record_opening_balance(graph_id, balances=..., equity_element_id=..., entity_id=...)` beside the journal entries, returning the `JournalEntryResponse`, with a test. ## Breaking Changes None. Additive in both tiers. ## Testing 693 passed, 17 skipped; lint, format and typecheck clean. The operation exists on the server only from **robosystems v1.18.8**, the release carrying #1852 and migration 0054. Until that deploys, the new method gets a 404 from production. Nothing else changes, and the apps pin the client by lockfile. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01M6TRefZ8MTAxax6pMxer4q
2 parents f4389c4 + 7f81880 commit 398303b

7 files changed

Lines changed: 611 additions & 0 deletions

File tree

Lines changed: 294 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,294 @@
1+
from http import HTTPStatus
2+
from typing import Any
3+
from urllib.parse import quote
4+
5+
import httpx
6+
7+
from ... import errors
8+
from ...client import AuthenticatedClient, Client
9+
from ...models.error_response import ErrorResponse
10+
from ...models.operation_envelope_journal_entry_response import (
11+
OperationEnvelopeJournalEntryResponse,
12+
)
13+
from ...models.record_opening_balance_request import RecordOpeningBalanceRequest
14+
from ...types import UNSET, Response, Unset
15+
16+
17+
def _get_kwargs(
18+
graph_id: str,
19+
*,
20+
body: RecordOpeningBalanceRequest,
21+
idempotency_key: None | str | Unset = UNSET,
22+
) -> dict[str, Any]:
23+
headers: dict[str, Any] = {}
24+
if not isinstance(idempotency_key, Unset):
25+
headers["Idempotency-Key"] = idempotency_key
26+
27+
_kwargs: dict[str, Any] = {
28+
"method": "post",
29+
"url": "/extensions/roboledger/{graph_id}/operations/record-opening-balance".format(
30+
graph_id=quote(str(graph_id), safe=""),
31+
),
32+
}
33+
34+
_kwargs["json"] = body.to_dict()
35+
36+
headers["Content-Type"] = "application/json"
37+
38+
_kwargs["headers"] = headers
39+
return _kwargs
40+
41+
42+
def _parse_response(
43+
*, client: AuthenticatedClient | Client, response: httpx.Response
44+
) -> ErrorResponse | OperationEnvelopeJournalEntryResponse | None:
45+
if response.status_code == 200:
46+
response_200 = OperationEnvelopeJournalEntryResponse.from_dict(response.json())
47+
48+
return response_200
49+
50+
if response.status_code == 400:
51+
response_400 = ErrorResponse.from_dict(response.json())
52+
53+
return response_400
54+
55+
if response.status_code == 401:
56+
response_401 = ErrorResponse.from_dict(response.json())
57+
58+
return response_401
59+
60+
if response.status_code == 403:
61+
response_403 = ErrorResponse.from_dict(response.json())
62+
63+
return response_403
64+
65+
if response.status_code == 404:
66+
response_404 = ErrorResponse.from_dict(response.json())
67+
68+
return response_404
69+
70+
if response.status_code == 409:
71+
response_409 = ErrorResponse.from_dict(response.json())
72+
73+
return response_409
74+
75+
if response.status_code == 422:
76+
response_422 = ErrorResponse.from_dict(response.json())
77+
78+
return response_422
79+
80+
if response.status_code == 429:
81+
response_429 = ErrorResponse.from_dict(response.json())
82+
83+
return response_429
84+
85+
if response.status_code == 500:
86+
response_500 = ErrorResponse.from_dict(response.json())
87+
88+
return response_500
89+
90+
if client.raise_on_unexpected_status:
91+
raise errors.UnexpectedStatus(response.status_code, response.content)
92+
else:
93+
return None
94+
95+
96+
def _build_response(
97+
*, client: AuthenticatedClient | Client, response: httpx.Response
98+
) -> Response[ErrorResponse | OperationEnvelopeJournalEntryResponse]:
99+
return Response(
100+
status_code=HTTPStatus(response.status_code),
101+
content=response.content,
102+
headers=response.headers,
103+
parsed=_parse_response(client=client, response=response),
104+
)
105+
106+
107+
def sync_detailed(
108+
graph_id: str,
109+
*,
110+
client: AuthenticatedClient,
111+
body: RecordOpeningBalanceRequest,
112+
idempotency_key: None | str | Unset = UNSET,
113+
) -> Response[ErrorResponse | OperationEnvelopeJournalEntryResponse]:
114+
"""Record Opening Balance
115+
116+
Record the balance sheet an entity's books start from, when its history does not come with them: one
117+
balance per balance-sheet account (assets, liabilities, equity), in cents, debit or credit in the
118+
account's normal direction. It posts as one `opening` entry dated the day before the entity's first
119+
fiscal month, so every month's opening balances include it and no month's activity does: the cash
120+
flow and the equity statement start from it rather than counting it. Name the equity account that
121+
takes any difference between debits and credits (`equity_element_id`, usually Opening Balance
122+
Equity); unbalanced balances without one are refused, and an income or expense account is refused,
123+
since income before the books begin is in retained earnings. One per entity: recording it again
124+
replaces it, until the entity's first close, after which a correction is an adjusting entry in an
125+
open month. Set up the fiscal calendar first; moving its start (change-calendar-start) moves the
126+
opening with it.
127+
128+
**Idempotency**: supply an `Idempotency-Key` header to make safe retries; replays within 24 hours
129+
return the same envelope. Reusing the key with a different body returns HTTP 409 Conflict.
130+
131+
Args:
132+
graph_id (str):
133+
idempotency_key (None | str | Unset):
134+
body (RecordOpeningBalanceRequest): The balance sheet a ledger starts from.
135+
136+
Raises:
137+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
138+
httpx.TimeoutException: If the request takes longer than Client.timeout.
139+
140+
Returns:
141+
Response[ErrorResponse | OperationEnvelopeJournalEntryResponse]
142+
"""
143+
144+
kwargs = _get_kwargs(
145+
graph_id=graph_id,
146+
body=body,
147+
idempotency_key=idempotency_key,
148+
)
149+
150+
response = client.get_httpx_client().request(
151+
**kwargs,
152+
)
153+
154+
return _build_response(client=client, response=response)
155+
156+
157+
def sync(
158+
graph_id: str,
159+
*,
160+
client: AuthenticatedClient,
161+
body: RecordOpeningBalanceRequest,
162+
idempotency_key: None | str | Unset = UNSET,
163+
) -> ErrorResponse | OperationEnvelopeJournalEntryResponse | None:
164+
"""Record Opening Balance
165+
166+
Record the balance sheet an entity's books start from, when its history does not come with them: one
167+
balance per balance-sheet account (assets, liabilities, equity), in cents, debit or credit in the
168+
account's normal direction. It posts as one `opening` entry dated the day before the entity's first
169+
fiscal month, so every month's opening balances include it and no month's activity does: the cash
170+
flow and the equity statement start from it rather than counting it. Name the equity account that
171+
takes any difference between debits and credits (`equity_element_id`, usually Opening Balance
172+
Equity); unbalanced balances without one are refused, and an income or expense account is refused,
173+
since income before the books begin is in retained earnings. One per entity: recording it again
174+
replaces it, until the entity's first close, after which a correction is an adjusting entry in an
175+
open month. Set up the fiscal calendar first; moving its start (change-calendar-start) moves the
176+
opening with it.
177+
178+
**Idempotency**: supply an `Idempotency-Key` header to make safe retries; replays within 24 hours
179+
return the same envelope. Reusing the key with a different body returns HTTP 409 Conflict.
180+
181+
Args:
182+
graph_id (str):
183+
idempotency_key (None | str | Unset):
184+
body (RecordOpeningBalanceRequest): The balance sheet a ledger starts from.
185+
186+
Raises:
187+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
188+
httpx.TimeoutException: If the request takes longer than Client.timeout.
189+
190+
Returns:
191+
ErrorResponse | OperationEnvelopeJournalEntryResponse
192+
"""
193+
194+
return sync_detailed(
195+
graph_id=graph_id,
196+
client=client,
197+
body=body,
198+
idempotency_key=idempotency_key,
199+
).parsed
200+
201+
202+
async def asyncio_detailed(
203+
graph_id: str,
204+
*,
205+
client: AuthenticatedClient,
206+
body: RecordOpeningBalanceRequest,
207+
idempotency_key: None | str | Unset = UNSET,
208+
) -> Response[ErrorResponse | OperationEnvelopeJournalEntryResponse]:
209+
"""Record Opening Balance
210+
211+
Record the balance sheet an entity's books start from, when its history does not come with them: one
212+
balance per balance-sheet account (assets, liabilities, equity), in cents, debit or credit in the
213+
account's normal direction. It posts as one `opening` entry dated the day before the entity's first
214+
fiscal month, so every month's opening balances include it and no month's activity does: the cash
215+
flow and the equity statement start from it rather than counting it. Name the equity account that
216+
takes any difference between debits and credits (`equity_element_id`, usually Opening Balance
217+
Equity); unbalanced balances without one are refused, and an income or expense account is refused,
218+
since income before the books begin is in retained earnings. One per entity: recording it again
219+
replaces it, until the entity's first close, after which a correction is an adjusting entry in an
220+
open month. Set up the fiscal calendar first; moving its start (change-calendar-start) moves the
221+
opening with it.
222+
223+
**Idempotency**: supply an `Idempotency-Key` header to make safe retries; replays within 24 hours
224+
return the same envelope. Reusing the key with a different body returns HTTP 409 Conflict.
225+
226+
Args:
227+
graph_id (str):
228+
idempotency_key (None | str | Unset):
229+
body (RecordOpeningBalanceRequest): The balance sheet a ledger starts from.
230+
231+
Raises:
232+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
233+
httpx.TimeoutException: If the request takes longer than Client.timeout.
234+
235+
Returns:
236+
Response[ErrorResponse | OperationEnvelopeJournalEntryResponse]
237+
"""
238+
239+
kwargs = _get_kwargs(
240+
graph_id=graph_id,
241+
body=body,
242+
idempotency_key=idempotency_key,
243+
)
244+
245+
response = await client.get_async_httpx_client().request(**kwargs)
246+
247+
return _build_response(client=client, response=response)
248+
249+
250+
async def asyncio(
251+
graph_id: str,
252+
*,
253+
client: AuthenticatedClient,
254+
body: RecordOpeningBalanceRequest,
255+
idempotency_key: None | str | Unset = UNSET,
256+
) -> ErrorResponse | OperationEnvelopeJournalEntryResponse | None:
257+
"""Record Opening Balance
258+
259+
Record the balance sheet an entity's books start from, when its history does not come with them: one
260+
balance per balance-sheet account (assets, liabilities, equity), in cents, debit or credit in the
261+
account's normal direction. It posts as one `opening` entry dated the day before the entity's first
262+
fiscal month, so every month's opening balances include it and no month's activity does: the cash
263+
flow and the equity statement start from it rather than counting it. Name the equity account that
264+
takes any difference between debits and credits (`equity_element_id`, usually Opening Balance
265+
Equity); unbalanced balances without one are refused, and an income or expense account is refused,
266+
since income before the books begin is in retained earnings. One per entity: recording it again
267+
replaces it, until the entity's first close, after which a correction is an adjusting entry in an
268+
open month. Set up the fiscal calendar first; moving its start (change-calendar-start) moves the
269+
opening with it.
270+
271+
**Idempotency**: supply an `Idempotency-Key` header to make safe retries; replays within 24 hours
272+
return the same envelope. Reusing the key with a different body returns HTTP 409 Conflict.
273+
274+
Args:
275+
graph_id (str):
276+
idempotency_key (None | str | Unset):
277+
body (RecordOpeningBalanceRequest): The balance sheet a ledger starts from.
278+
279+
Raises:
280+
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
281+
httpx.TimeoutException: If the request takes longer than Client.timeout.
282+
283+
Returns:
284+
ErrorResponse | OperationEnvelopeJournalEntryResponse
285+
"""
286+
287+
return (
288+
await asyncio_detailed(
289+
graph_id=graph_id,
290+
client=client,
291+
body=body,
292+
idempotency_key=idempotency_key,
293+
)
294+
).parsed

‎robosystems_client/clients/ledger_client.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,9 @@
5454
from ..api.robo_ledger_ledger_events.preview_reconciliations import (
5555
sync_detailed as op_preview_reconciliations,
5656
)
57+
from ..api.robo_ledger_ledger_events.record_opening_balance import (
58+
sync_detailed as op_record_opening_balance,
59+
)
5760
from ..api.robo_ledger_ledger_events.record_statement_balance import (
5861
sync_detailed as op_record_statement_balance,
5962
)
@@ -545,6 +548,8 @@
545548
from ..models.update_rollforward_arm import UpdateRollforwardArm
546549
from ..models.link_entity_taxonomy_request import LinkEntityTaxonomyRequest
547550
from ..models.update_journal_entry_request import UpdateJournalEntryRequest
551+
from ..models.opening_balance_input import OpeningBalanceInput
552+
from ..models.record_opening_balance_request import RecordOpeningBalanceRequest
548553
from ..models.update_schedule_arm import UpdateScheduleArm
549554
from ..models.update_schedule_request import UpdateScheduleRequest
550555
from ..models.close_period_operation import ClosePeriodOperation
@@ -2136,6 +2141,39 @@ def reverse_journal_entry(
21362141
envelope = self._call_op("Reverse journal entry", response)
21372142
return self._typed_result("Reverse journal entry", envelope, EventBlockEnvelope)
21382143

2144+
def record_opening_balance(
2145+
self,
2146+
graph_id: str,
2147+
*,
2148+
balances: list[dict[str, Any]],
2149+
equity_element_id: str | None = None,
2150+
memo: str | None = None,
2151+
entity_id: str | None = None,
2152+
) -> JournalEntryResponse:
2153+
"""Record the balance sheet an entity's books start from.
2154+
2155+
``balances`` is one ``{"element_id", "debit_amount", "credit_amount"}``
2156+
per balance-sheet account, in cents, in the account's normal direction.
2157+
It posts as one ``opening`` entry dated the day before the first fiscal
2158+
month, so every month's opening balances include it and no month's
2159+
activity does. ``equity_element_id`` (usually Opening Balance Equity)
2160+
takes any difference between debits and credits; unbalanced balances
2161+
without one are refused. Recording again replaces the entry until the
2162+
entity's first close. ``entity_id`` names the entity; omitted, the group
2163+
parent.
2164+
"""
2165+
body = RecordOpeningBalanceRequest(
2166+
balances=[OpeningBalanceInput.from_dict(b) for b in balances],
2167+
entity_id=entity_id if entity_id is not None else UNSET,
2168+
equity_element_id=(equity_element_id if equity_element_id is not None else UNSET),
2169+
memo=memo if memo is not None else UNSET,
2170+
)
2171+
response = op_record_opening_balance(
2172+
graph_id=graph_id, body=body, client=self._get_client()
2173+
)
2174+
envelope = self._call_op("Record opening balance", response)
2175+
return self._typed_result("Record opening balance", envelope, JournalEntryResponse)
2176+
21392177
# ── Event blocks (generic preview + status transitions) ──────────────
21402178

21412179
def create_event_block(

‎robosystems_client/models/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,7 @@
459459
OfferingRepositoryPlanRateLimitsType0,
460460
)
461461
from .oidc_provider_info import OIDCProviderInfo
462+
from .opening_balance_input import OpeningBalanceInput
462463
from .operation_costs import OperationCosts
463464
from .operation_costs_ai_operations import OperationCostsAiOperations
464465
from .operation_costs_token_pricing import OperationCostsTokenPricing
@@ -914,6 +915,7 @@
914915
ReconcilingItemPlanDefaultDisposition,
915916
)
916917
from .reconciling_item_regenerated import ReconcilingItemRegenerated
918+
from .record_opening_balance_request import RecordOpeningBalanceRequest
917919
from .record_statement_balance_request import RecordStatementBalanceRequest
918920
from .recovery_codes_request import RecoveryCodesRequest
919921
from .recovery_codes_request_assertion_type_0 import RecoveryCodesRequestAssertionType0
@@ -1551,6 +1553,7 @@
15511553
"OfferingRepositoryPlan",
15521554
"OfferingRepositoryPlanRateLimitsType0",
15531555
"OIDCProviderInfo",
1556+
"OpeningBalanceInput",
15541557
"OperationCosts",
15551558
"OperationCostsAiOperations",
15561559
"OperationCostsTokenPricing",
@@ -1774,6 +1777,7 @@
17741777
"ReconcilingItemPlan",
17751778
"ReconcilingItemPlanDefaultDisposition",
17761779
"ReconcilingItemRegenerated",
1780+
"RecordOpeningBalanceRequest",
17771781
"RecordStatementBalanceRequest",
17781782
"RecoveryCodesRequest",
17791783
"RecoveryCodesRequestAssertionType0",

0 commit comments

Comments
 (0)