anaplan-sdk 0.4.5__py3-none-any.whl → 0.5.0a2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,61 +1,120 @@
1
+ import logging
1
2
  from concurrent.futures import ThreadPoolExecutor
2
3
  from itertools import chain
3
- from typing import Any
4
+ from typing import Any, Literal, overload
4
5
 
5
- import httpx
6
-
7
- from anaplan_sdk._base import _BaseClient
6
+ from anaplan_sdk._services import (
7
+ _HttpService,
8
+ parse_calendar_response,
9
+ parse_insertion_response,
10
+ validate_dimension_id,
11
+ )
12
+ from anaplan_sdk.exceptions import InvalidIdentifierException
8
13
  from anaplan_sdk.models import (
14
+ CurrentPeriod,
15
+ Dimension,
16
+ DimensionWithCode,
17
+ FiscalYear,
9
18
  InsertionResult,
10
19
  LineItem,
11
20
  List,
21
+ ListDeletionResult,
12
22
  ListItem,
13
23
  ListMetadata,
24
+ Model,
25
+ ModelCalendar,
14
26
  ModelStatus,
15
27
  Module,
28
+ View,
29
+ ViewInfo,
16
30
  )
17
31
 
32
+ logger = logging.getLogger("anaplan_sdk")
33
+
18
34
 
19
- class _TransactionalClient(_BaseClient):
20
- def __init__(self, client: httpx.Client, model_id: str, retry_count: int) -> None:
35
+ class _TransactionalClient:
36
+ def __init__(self, http: _HttpService, model_id: str) -> None:
37
+ self._http = http
21
38
  self._url = f"https://api.anaplan.com/2/0/models/{model_id}"
22
- super().__init__(retry_count, client)
39
+ self._model_id = model_id
23
40
 
24
- def list_modules(self) -> list[Module]:
41
+ def get_model_details(self) -> Model:
42
+ """
43
+ Retrieves the Model details for the current Model.
44
+ :return: The Model details.
45
+ """
46
+ return Model.model_validate(
47
+ self._http.get(self._url, params={"modelDetails": "true"})["model"]
48
+ )
49
+
50
+ def get_model_status(self) -> ModelStatus:
51
+ """
52
+ Gets the current status of the Model.
53
+ :return: The current status of the Mode.
54
+ """
55
+ return ModelStatus.model_validate(
56
+ self._http.get(f"{self._url}/status").get("requestStatus")
57
+ )
58
+
59
+ def wake_model(self) -> None:
60
+ """Wake up the current model."""
61
+ self._http.post_empty(f"{self._url}/open", headers={"Content-Type": "application/text"})
62
+ logger.info(f"Woke up model '{self._model_id}'.")
63
+
64
+ def close_model(self) -> None:
65
+ """Close the current model."""
66
+ self._http.post_empty(f"{self._url}/close", headers={"Content-Type": "application/text"})
67
+ logger.info(f"Closed model '{self._model_id}'.")
68
+
69
+ def get_modules(self) -> list[Module]:
25
70
  """
26
71
  Lists all the Modules in the Model.
27
72
  :return: The List of Modules.
28
73
  """
29
74
  return [
30
- Module.model_validate(e) for e in self._get_paginated(f"{self._url}/modules", "modules")
75
+ Module.model_validate(e)
76
+ for e in self._http.get_paginated(f"{self._url}/modules", "modules")
31
77
  ]
32
78
 
33
- def get_model_status(self) -> ModelStatus:
79
+ def get_views(self) -> list[View]:
34
80
  """
35
- Gets the current status of the Model.
36
- :return: The current status of the Mode.
81
+ Lists all the Views in the Model. This will include all Modules and potentially other saved
82
+ views.
83
+ :return: The List of Views.
84
+ """
85
+ return [
86
+ View.model_validate(e) for e in self._http.get_paginated(f"{self._url}/views", "views")
87
+ ]
88
+
89
+ def get_view_info(self, view_id: int) -> ViewInfo:
37
90
  """
38
- return ModelStatus.model_validate(self._get(f"{self._url}/status").get("requestStatus"))
91
+ Gets the detailed information about a View.
92
+ :param view_id: The ID of the View.
93
+ :return: The information about the View.
94
+ """
95
+ return ViewInfo.model_validate(self._http.get(f"{self._url}/views/{view_id}"))
39
96
 
40
- def list_line_items(self, only_module_id: int | None = None) -> list[LineItem]:
97
+ def get_line_items(self, only_module_id: int | None = None) -> list[LineItem]:
41
98
  """
42
99
  Lists all the Line Items in the Model.
43
100
  :param only_module_id: If provided, only Line Items from this Module will be returned.
44
- :return: The List of Line Items.
101
+ :return: All Line Items on this Model or only from the specified Module.
45
102
  """
46
103
  url = (
47
104
  f"{self._url}/modules/{only_module_id}/lineItems?includeAll=true"
48
105
  if only_module_id
49
106
  else f"{self._url}/lineItems?includeAll=true"
50
107
  )
51
- return [LineItem.model_validate(e) for e in self._get(url).get("items", [])]
108
+ return [LineItem.model_validate(e) for e in self._http.get(url).get("items", [])]
52
109
 
53
- def list_lists(self) -> list[List]:
110
+ def get_lists(self) -> list[List]:
54
111
  """
55
112
  Lists all the Lists in the Model.
56
113
  :return: All Lists on this model.
57
114
  """
58
- return [List.model_validate(e) for e in self._get_paginated(f"{self._url}/lists", "lists")]
115
+ return [
116
+ List.model_validate(e) for e in self._http.get_paginated(f"{self._url}/lists", "lists")
117
+ ]
59
118
 
60
119
  def get_list_metadata(self, list_id: int) -> ListMetadata:
61
120
  """
@@ -64,21 +123,34 @@ class _TransactionalClient(_BaseClient):
64
123
  :return: The Metadata for the List.
65
124
  """
66
125
  return ListMetadata.model_validate(
67
- self._get(f"{self._url}/lists/{list_id}").get("metadata")
126
+ self._http.get(f"{self._url}/lists/{list_id}").get("metadata")
68
127
  )
69
128
 
70
- def get_list_items(self, list_id: int) -> list[ListItem]:
129
+ @overload
130
+ def get_list_items(
131
+ self, list_id: int, return_raw: Literal[False] = False
132
+ ) -> list[ListItem]: ...
133
+
134
+ @overload
135
+ def get_list_items(
136
+ self, list_id: int, return_raw: Literal[True] = True
137
+ ) -> list[dict[str, Any]]: ...
138
+
139
+ def get_list_items(
140
+ self, list_id: int, return_raw: bool = False
141
+ ) -> list[ListItem] | list[dict[str, Any]]:
71
142
  """
72
143
  Gets all the items in a List.
73
144
  :param list_id: The ID of the List.
74
- :return: The List of Items.
145
+ :param return_raw: If True, returns the items as a list of dictionaries instead of ListItem
146
+ objects. If you use the result of this call in a DataFrame or you simply pass on the
147
+ data, you will want to set this to avoid unnecessary (de-)serialization.
148
+ :return: All items in the List.
75
149
  """
76
- return [
77
- ListItem.model_validate(e)
78
- for e in self._get(f"{self._url}/lists/{list_id}/items?includeAll=true").get(
79
- "listItems", []
80
- )
81
- ]
150
+ res = self._http.get(f"{self._url}/lists/{list_id}/items?includeAll=true")
151
+ if return_raw:
152
+ return res.get("listItems", [])
153
+ return [ListItem.model_validate(e) for e in res.get("listItems", [])]
82
154
 
83
155
  def insert_list_items(
84
156
  self, list_id: int, items: list[dict[str, str | int | dict]]
@@ -100,33 +172,33 @@ class _TransactionalClient(_BaseClient):
100
172
  :return: The result of the insertion, indicating how many items were added,
101
173
  ignored or failed.
102
174
  """
175
+ if not items:
176
+ return InsertionResult(added=0, ignored=0, failures=[], total=0)
103
177
  if len(items) <= 100_000:
104
- return InsertionResult.model_validate(
105
- self._post(f"{self._url}/lists/{list_id}/items?action=add", json={"items": items})
178
+ result = InsertionResult.model_validate(
179
+ self._http.post(
180
+ f"{self._url}/lists/{list_id}/items?action=add", json={"items": items}
181
+ )
106
182
  )
183
+ logger.info(f"Inserted {result.added} items into list '{list_id}'.")
184
+ return result
107
185
 
108
186
  with ThreadPoolExecutor() as executor:
109
187
  responses = list(
110
188
  executor.map(
111
- lambda chunk: self._post(
189
+ lambda chunk: self._http.post(
112
190
  f"{self._url}/lists/{list_id}/items?action=add", json={"items": chunk}
113
191
  ),
114
192
  [items[i : i + 100_000] for i in range(0, len(items), 100_000)],
115
193
  )
116
194
  )
195
+ result = parse_insertion_response(responses)
196
+ logger.info(f"Inserted {result.added} items into list '{list_id}'.")
197
+ return result
117
198
 
118
- failures, added, ignored, total = [], 0, 0, 0
119
- for res in responses:
120
- failures.append(res.get("failures", []))
121
- added += res.get("added", 0)
122
- total += res.get("total", 0)
123
- ignored += res.get("ignored", 0)
124
-
125
- return InsertionResult(
126
- added=added, ignored=ignored, total=total, failures=list(chain.from_iterable(failures))
127
- )
128
-
129
- def delete_list_items(self, list_id: int, items: list[dict[str, str | int]]) -> int:
199
+ def delete_list_items(
200
+ self, list_id: int, items: list[dict[str, str | int]]
201
+ ) -> ListDeletionResult:
130
202
  """
131
203
  Deletes items from a List. If you pass a long list, it will be split into chunks of 100,000
132
204
  items, the maximum allowed by the API.
@@ -140,31 +212,42 @@ class _TransactionalClient(_BaseClient):
140
212
 
141
213
  :param list_id: The ID of the List.
142
214
  :param items: The items to delete from the List. Must be a dict with either `code` or `id`
143
- as the keys to identify the records to delete.
215
+ as the keys to identify the records to delete. Specifying both will error.
216
+ :return: The result of the deletion, indicating how many items were deleted or failed.
144
217
  """
218
+ if not items:
219
+ return ListDeletionResult(deleted=0, failures=[])
145
220
  if len(items) <= 100_000:
146
- return self._post(
221
+ res = self._http.post(
147
222
  f"{self._url}/lists/{list_id}/items?action=delete", json={"items": items}
148
- ).get("deleted", 0)
223
+ )
224
+ info = ListDeletionResult.model_validate(res)
225
+ logger.info(f"Deleted {info.deleted} items from list '{list_id}'.")
226
+ return info
149
227
 
150
228
  with ThreadPoolExecutor() as executor:
151
229
  responses = list(
152
230
  executor.map(
153
- lambda chunk: self._post(
231
+ lambda chunk: self._http.post(
154
232
  f"{self._url}/lists/{list_id}/items?action=delete", json={"items": chunk}
155
233
  ),
156
234
  [items[i : i + 100_000] for i in range(0, len(items), 100_000)],
157
235
  )
158
236
  )
159
-
160
- return sum(res.get("deleted", 0) for res in responses)
237
+ info = ListDeletionResult(
238
+ deleted=sum(res.get("deleted", 0) for res in responses),
239
+ failures=list(chain.from_iterable(res.get("failures", []) for res in responses)),
240
+ )
241
+ logger.info(f"Deleted {info} items from list '{list_id}'.")
242
+ return info
161
243
 
162
244
  def reset_list_index(self, list_id: int) -> None:
163
245
  """
164
246
  Resets the index of a List. The List must be empty to do so.
165
247
  :param list_id: The ID of the List.
166
248
  """
167
- self._post_empty(f"{self._url}/lists/{list_id}/resetIndex")
249
+ self._http.post_empty(f"{self._url}/lists/{list_id}/resetIndex")
250
+ logger.info(f"Reset index for list '{list_id}'.")
168
251
 
169
252
  def update_module_data(
170
253
  self, module_id: int, data: list[dict[str, Any]]
@@ -183,5 +266,118 @@ class _TransactionalClient(_BaseClient):
183
266
  :param data: The data to write to the Module.
184
267
  :return: The number of cells changed or the response with the according error details.
185
268
  """
186
- res = self._post(f"{self._url}/modules/{module_id}/data", json=data)
269
+ res = self._http.post(f"{self._url}/modules/{module_id}/data", json=data)
270
+ if "failures" not in res:
271
+ logger.info(f"Updated {res['numberOfCellsChanged']} cells in module '{module_id}'.")
187
272
  return res if "failures" in res else res["numberOfCellsChanged"]
273
+
274
+ def get_current_period(self) -> CurrentPeriod:
275
+ """
276
+ Gets the current period of the model.
277
+ :return: The current period of the model.
278
+ """
279
+ res = self._http.get(f"{self._url}/currentPeriod")
280
+ return CurrentPeriod.model_validate(res["currentPeriod"])
281
+
282
+ def set_current_period(self, date: str) -> CurrentPeriod:
283
+ """
284
+ Sets the current period of the model to the given date.
285
+ :param date: The date to set the current period to, in the format 'YYYY-MM-DD'.
286
+ :return: The updated current period of the model.
287
+ """
288
+ res = self._http.put(f"{self._url}/currentPeriod", {"date": date})
289
+ logger.info(f"Set current period to '{date}'.")
290
+ return CurrentPeriod.model_validate(res["currentPeriod"])
291
+
292
+ def set_current_fiscal_year(self, year: str) -> FiscalYear:
293
+ """
294
+ Sets the current fiscal year of the model.
295
+ :param year: The fiscal year to set, in the format specified in the model, e.g. FY24.
296
+ :return: The updated fiscal year of the model.
297
+ """
298
+ res = self._http.put(f"{self._url}/modelCalendar/fiscalYear", {"year": year})
299
+ logger.info(f"Set current fiscal year to '{year}'.")
300
+ return FiscalYear.model_validate(res["modelCalendar"]["fiscalYear"])
301
+
302
+ def get_model_calendar(self) -> ModelCalendar:
303
+ """
304
+ Get the calendar settings of the model.
305
+ :return: The calendar settings of the model.
306
+ """
307
+ return parse_calendar_response(self._http.get(f"{self._url}/modelCalendar"))
308
+
309
+ def get_dimension_items(self, dimension_id: int) -> list[DimensionWithCode]:
310
+ """
311
+ Get all items in a dimension. This will fail if the dimensions holds more than 1_000_000
312
+ items. Valid Dimensions are:
313
+
314
+ - Lists (101xxxxxxxxx)
315
+ - List Subsets (109xxxxxxxxx)
316
+ - Line Item Subsets (114xxxxxxxxx)
317
+ - Users (101999999999)
318
+ For lists and users, you should prefer using the `get_list_items` and `get_users` methods,
319
+ respectively, instead.
320
+ :param dimension_id: The ID of the dimension to list items for.
321
+ :return: A list of Dimension items.
322
+ """
323
+ res = self._http.get(f"{self._url}/dimensions/{validate_dimension_id(dimension_id)}/items")
324
+ return [DimensionWithCode.model_validate(e) for e in res.get("items", [])]
325
+
326
+ def lookup_dimension_items(
327
+ self, dimension_id: int, codes: list[str] = None, names: list[str] = None
328
+ ) -> list[DimensionWithCode]:
329
+ """
330
+ Looks up items in a dimension by their codes or names. If both are provided, both will be
331
+ searched for. You must provide at least one of `codes` or `names`. Valid Dimensions to
332
+ lookup are:
333
+
334
+ - Lists (101xxxxxxxxx)
335
+ - Time (20000000003)
336
+ - Version (20000000020)
337
+ - Users (101999999999)
338
+ :param dimension_id: The ID of the dimension to lookup items for.
339
+ :param codes: A list of codes to lookup in the dimension.
340
+ :param names: A list of names to lookup in the dimension.
341
+ :return: A list of Dimension items that match the provided codes or names.
342
+ """
343
+ if not codes and not names:
344
+ raise ValueError("At least one of 'codes' or 'names' must be provided.")
345
+ if not (
346
+ dimension_id == 101999999999
347
+ or 101000000000 <= dimension_id < 102000000000
348
+ or dimension_id == 20000000003
349
+ or dimension_id == 20000000020
350
+ ):
351
+ raise InvalidIdentifierException(
352
+ "Invalid dimension_id. Must be a List (101xxxxxxxxx), Time (20000000003), "
353
+ "Version (20000000020), or Users (101999999999)."
354
+ )
355
+ res = self._http.post(
356
+ f"{self._url}/dimensions/{dimension_id}/items", json={"codes": codes, "names": names}
357
+ )
358
+ return [DimensionWithCode.model_validate(e) for e in res.get("items", [])]
359
+
360
+ def get_view_dimension_items(self, view_id: int, dimension_id: int) -> list[Dimension]:
361
+ """
362
+ Get the members of a dimension that are part of the given View. This call returns data as
363
+ filtered by the page builder when they configure the view. This call respects hidden items,
364
+ filtering selections, and Selective Access. If the view contains hidden or filtered items,
365
+ these do not display in the response. This will fail if the dimensions holds more than
366
+ 1_000_000 items. The response returns Items within a flat list (no hierarchy) and order
367
+ is not guaranteed.
368
+ :param view_id: The ID of the View.
369
+ :param dimension_id: The ID of the Dimension to get items for.
370
+ :return: A list of Dimensions used in the View.
371
+ """
372
+ res = self._http.get(f"{self._url}/views/{view_id}/dimensions/{dimension_id}/items")
373
+ return [Dimension.model_validate(e) for e in res.get("items", [])]
374
+
375
+ def get_line_item_dimensions(self, line_item_id: int) -> list[Dimension]:
376
+ """
377
+ Get the dimensions of a Line Item. This will return all dimensions that are used in the
378
+ Line Item.
379
+ :param line_item_id: The ID of the Line Item.
380
+ :return: A list of Dimensions used in the Line Item.
381
+ """
382
+ res = self._http.get(f"{self._url}/lineItems/{line_item_id}/dimensions")
383
+ return [Dimension.model_validate(e) for e in res.get("dimensions", [])]