anaplan-sdk 0.4.5__py3-none-any.whl → 0.5.0__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.
anaplan_sdk/__init__.py CHANGED
@@ -2,6 +2,7 @@ from ._async_clients import AsyncClient
2
2
  from ._auth import AnaplanLocalOAuth, AnaplanRefreshTokenAuth
3
3
  from ._clients import Client
4
4
  from ._oauth import AsyncOauth, Oauth
5
+ from .models.scim import field
5
6
 
6
7
  __all__ = [
7
8
  "AsyncClient",
@@ -12,4 +13,5 @@ __all__ = [
12
13
  "Oauth",
13
14
  "models",
14
15
  "exceptions",
16
+ "field",
15
17
  ]
@@ -2,6 +2,8 @@ from ._alm import _AsyncAlmClient
2
2
  from ._audit import _AsyncAuditClient
3
3
  from ._bulk import AsyncClient
4
4
  from ._cloud_works import _AsyncCloudWorksClient
5
+ from ._cw_flow import _AsyncFlowClient
6
+ from ._scim import _AsyncScimClient
5
7
  from ._transactional import _AsyncTransactionalClient
6
8
 
7
9
  __all__ = [
@@ -9,5 +11,7 @@ __all__ = [
9
11
  "_AsyncAlmClient",
10
12
  "_AsyncAuditClient",
11
13
  "_AsyncCloudWorksClient",
14
+ "_AsyncFlowClient",
12
15
  "_AsyncTransactionalClient",
16
+ "_AsyncScimClient",
13
17
  ]
@@ -1,13 +1,62 @@
1
- import httpx
1
+ import logging
2
+ from typing import Literal, overload
2
3
 
3
- from anaplan_sdk._base import _AsyncBaseClient
4
- from anaplan_sdk.models import ModelRevision, Revision, SyncTask
4
+ from anaplan_sdk._services import _AsyncHttpService
5
+ from anaplan_sdk._utils import sort_params
6
+ from anaplan_sdk.exceptions import AnaplanActionError
7
+ from anaplan_sdk.models import (
8
+ ModelRevision,
9
+ ReportTask,
10
+ Revision,
11
+ SummaryReport,
12
+ SyncTask,
13
+ TaskSummary,
14
+ )
5
15
 
16
+ logger = logging.getLogger("anaplan_sdk")
6
17
 
7
- class _AsyncAlmClient(_AsyncBaseClient):
8
- def __init__(self, client: httpx.AsyncClient, model_id: str, retry_count: int) -> None:
9
- self._url = f"https://api.anaplan.com/2/0/models/{model_id}/alm"
10
- super().__init__(retry_count, client)
18
+
19
+ class _AsyncAlmClient:
20
+ def __init__(self, http: _AsyncHttpService, model_id: str) -> None:
21
+ self._http = http
22
+ self._model_id = model_id
23
+ self._url = f"https://api.anaplan.com/2/0/models/{model_id}"
24
+
25
+ async def change_model_status(self, status: Literal["online", "offline"]) -> None:
26
+ """
27
+ Use this call to change the status of a model.
28
+ :param status: The status of the model. Can be either "online" or "offline".
29
+ """
30
+ logger.info(f"Changed model status to '{status}' for model {self._model_id}.")
31
+ await self._http.put(f"{self._url}/onlineStatus", json={"status": status})
32
+
33
+ async def get_revisions(
34
+ self,
35
+ sort_by: Literal["id", "name", "applied_on", "created_on"] | None = None,
36
+ descending: bool = False,
37
+ ) -> list[Revision]:
38
+ """
39
+ Use this call to return a list of revisions for a specific model.
40
+ :param sort_by: The field to sort the results by.
41
+ :param descending: If True, the results will be sorted in descending order.
42
+ :return: A list of revisions for a specific model.
43
+ """
44
+ res = await self._http.get_paginated(
45
+ f"{self._url}/alm/revisions", "revisions", params=sort_params(sort_by, descending)
46
+ )
47
+ return [Revision.model_validate(e) for e in res]
48
+
49
+ async def get_latest_revision(self) -> Revision | None:
50
+ """
51
+ Use this call to return the latest revision for a specific model. The response is in the
52
+ same format as in Getting a list of syncable revisions between two models.
53
+
54
+ If a revision exists, the return list should contain one element only which is the
55
+ latest revision.
56
+ :return: The latest revision for a specific model, or None if no revisions exist.
57
+ """
58
+ res = (await self._http.get(f"{self._url}/alm/latestRevision")).get("revisions")
59
+ return Revision.model_validate(res[0]) if res else None
11
60
 
12
61
  async def get_syncable_revisions(self, source_model_id: str) -> list[Revision]:
13
62
  """
@@ -19,47 +68,81 @@ class _AsyncAlmClient(_AsyncBaseClient):
19
68
  :param source_model_id: The ID of the source model.
20
69
  :return: A list of revisions that can be synchronized to the target model.
21
70
  """
22
- revs = (
23
- await self._get(f"{self._url}/syncableRevisions?sourceModelId={source_model_id}")
24
- ).get("revisions", [])
25
- return [Revision.model_validate(e) for e in revs] if revs else []
71
+ res = await self._http.get(
72
+ f"{self._url}/alm/syncableRevisions?sourceModelId={source_model_id}"
73
+ )
74
+ return [Revision.model_validate(e) for e in res.get("revisions", [])]
26
75
 
27
- async def get_latest_revision(self) -> list[Revision]:
76
+ async def create_revision(self, name: str, description: str) -> Revision:
28
77
  """
29
- Use this call to return the latest revision for a specific model. The response is in the
30
- same format as in Getting a list of syncable revisions between two models.
31
-
32
- If a revision exists, the return list should contain one element only which is the
33
- latest revision.
34
- :return: The latest revision for a specific model.
78
+ Create a new revision for the model.
79
+ :param name: The name (title) of the revision.
80
+ :param description: The description of the revision.
81
+ :return: The created Revision Info.
35
82
  """
36
- return [
37
- Revision.model_validate(e)
38
- for e in (await self._get(f"{self._url}/latestRevision")).get("revisions", [])
39
- ]
83
+ res = await self._http.post(
84
+ f"{self._url}/alm/revisions", json={"name": name, "description": description}
85
+ )
86
+ rev = Revision.model_validate(res["revision"])
87
+ logger.info(f"Created revision '{name} ({rev.id})'for model {self._model_id}.")
88
+ return rev
40
89
 
41
- async def get_sync_tasks(self) -> list[SyncTask]:
90
+ async def get_sync_tasks(self) -> list[TaskSummary]:
42
91
  """
43
- Use this endpoint to return a list of sync tasks for a target model, where the tasks are
44
- either in progress, or they were completed within the last 48 hours.
92
+ List the sync tasks for a target mode. The returned the tasks are either in progress, or
93
+ they completed within the last 48 hours.
94
+ :return: A list of sync tasks in descending order of creation time.
95
+ """
96
+ res = await self._http.get(f"{self._url}/alm/syncTasks")
97
+ return [TaskSummary.model_validate(e) for e in res.get("tasks", [])]
45
98
 
46
- The list is in descending order of when the tasks were created.
47
- :return: A list of sync tasks for a target model.
99
+ async def get_sync_task(self, task_id: str) -> SyncTask:
100
+ """
101
+ Get the information for a specific sync task.
102
+ :param task_id: The ID of the sync task.
103
+ :return: The sync task information.
48
104
  """
49
- return [
50
- SyncTask.model_validate(e)
51
- for e in (await self._get(f"{self._url}/syncTasks")).get("tasks", [])
52
- ]
105
+ res = await self._http.get(f"{self._url}/alm/syncTasks/{task_id}")
106
+ return SyncTask.model_validate(res["task"])
53
107
 
54
- async def get_revisions(self) -> list[Revision]:
108
+ async def sync_models(
109
+ self,
110
+ source_revision_id: str,
111
+ source_model_id: str,
112
+ target_revision_id: str,
113
+ wait_for_completion: bool = True,
114
+ ) -> SyncTask:
55
115
  """
56
- Use this call to return a list of revisions for a specific model.
57
- :return: A list of revisions for a specific model.
116
+ Create a synchronization task between two revisions. This will synchronize the
117
+ source revision of the source model to the target revision of the target model. This will
118
+ fail if the source revision is incompatible with the target revision.
119
+ :param source_revision_id: The ID of the source revision.
120
+ :param source_model_id: The ID of the source model.
121
+ :param target_revision_id: The ID of the target revision.
122
+ :param wait_for_completion: If True, the method will poll the task status and not return
123
+ until the task is complete. If False, it will spawn the task and return immediately.
124
+ :return: The created sync task.
58
125
  """
59
- return [
60
- Revision.model_validate(e)
61
- for e in (await self._get(f"{self._url}/revisions")).get("revisions", [])
62
- ]
126
+ payload = {
127
+ "sourceRevisionId": source_revision_id,
128
+ "sourceModelId": source_model_id,
129
+ "targetRevisionId": target_revision_id,
130
+ }
131
+ res = await self._http.post(f"{self._url}/alm/syncTasks", json=payload)
132
+ task = await self.get_sync_task(res["task"]["taskId"])
133
+ logger.info(
134
+ f"Started sync task '{task.id}' from Model '{source_model_id}' "
135
+ f"(Revision '{source_revision_id}') to Model '{self._model_id}'."
136
+ )
137
+ if not wait_for_completion:
138
+ return task
139
+ task = await self._http.poll_task(self.get_sync_task, task.id)
140
+ if not task.result.successful:
141
+ msg = f"Sync task {task.id} completed with errors: {task.result.error}."
142
+ logger.error(msg)
143
+ raise AnaplanActionError(msg)
144
+ logger.info(f"Sync task {task.id} completed successfully.")
145
+ return task
63
146
 
64
147
  async def get_models_for_revision(self, revision_id: str) -> list[ModelRevision]:
65
148
  """
@@ -68,9 +151,139 @@ class _AsyncAlmClient(_AsyncBaseClient):
68
151
  :param revision_id: The ID of the revision.
69
152
  :return: A list of models that had a specific revision applied to them.
70
153
  """
71
- return [
72
- ModelRevision.model_validate(e)
73
- for e in (await self._get(f"{self._url}/revisions/{revision_id}/appliedToModels")).get(
74
- "appliedToModels", []
75
- )
76
- ]
154
+ res = await self._http.get(f"{self._url}/alm/revisions/{revision_id}/appliedToModels")
155
+ return [ModelRevision.model_validate(e) for e in res.get("appliedToModels", [])]
156
+
157
+ async def create_comparison_report(
158
+ self,
159
+ source_revision_id: str,
160
+ source_model_id: str,
161
+ target_revision_id: str,
162
+ wait_for_completion: bool = True,
163
+ ) -> ReportTask:
164
+ """
165
+ Generate a full comparison report between two revisions. This will list all the changes made
166
+ to the source revision compared to the target revision.
167
+ :param source_revision_id: The ID of the source revision.
168
+ :param source_model_id: The ID of the source model.
169
+ :param target_revision_id: The ID of the target revision.
170
+ :param wait_for_completion: If True, the method will poll the task status and not return
171
+ until the task is complete. If False, it will spawn the task and return immediately.
172
+ :return: The created report task summary.
173
+ """
174
+ payload = {
175
+ "sourceRevisionId": source_revision_id,
176
+ "sourceModelId": source_model_id,
177
+ "targetRevisionId": target_revision_id,
178
+ }
179
+ res = await self._http.post(f"{self._url}/alm/comparisonReportTasks", json=payload)
180
+ task = await self.get_comparison_report_task(res["task"]["taskId"])
181
+ logger.info(
182
+ f"Started Comparison Report task '{task.id}' between Model '{source_model_id}' "
183
+ f"(Revision '{source_revision_id}') and Model '{self._model_id}'."
184
+ )
185
+ if not wait_for_completion:
186
+ return task
187
+ task = await self._http.poll_task(self.get_comparison_report_task, task.id)
188
+ if not task.result.successful:
189
+ msg = f"Comparison Report task {task.id} completed with errors: {task.result.error}."
190
+ logger.error(msg)
191
+ raise AnaplanActionError(msg)
192
+ logger.info(f"Comparison Report task {task.id} completed successfully.")
193
+ return task
194
+
195
+ async def get_comparison_report_task(self, task_id: str) -> ReportTask:
196
+ """
197
+ Get the task information for a comparison report task.
198
+ :param task_id: The ID of the comparison report task.
199
+ :return: The report task information.
200
+ """
201
+ res = await self._http.get(f"{self._url}/alm/comparisonReportTasks/{task_id}")
202
+ return ReportTask.model_validate(res["task"])
203
+
204
+ async def get_comparison_report(self, task: ReportTask) -> bytes:
205
+ """
206
+ Get the report for a specific task.
207
+ :param task: The report task object containing the task ID.
208
+ :return: The binary content of the comparison report.
209
+ """
210
+ return await self._http.get_binary(
211
+ f"{self._url}/alm/comparisonReports/"
212
+ f"{task.result.target_revision_id}/{task.result.source_revision_id}"
213
+ )
214
+
215
+ @overload
216
+ async def create_comparison_summary(
217
+ self,
218
+ source_revision_id: str,
219
+ source_model_id: str,
220
+ target_revision_id: str,
221
+ wait_for_completion: Literal[True] = True,
222
+ ) -> SummaryReport: ...
223
+
224
+ @overload
225
+ async def create_comparison_summary(
226
+ self,
227
+ source_revision_id: str,
228
+ source_model_id: str,
229
+ target_revision_id: str,
230
+ wait_for_completion: Literal[False] = False,
231
+ ) -> ReportTask: ...
232
+
233
+ async def create_comparison_summary(
234
+ self,
235
+ source_revision_id: str,
236
+ source_model_id: str,
237
+ target_revision_id: str,
238
+ wait_for_completion: bool = True,
239
+ ) -> ReportTask | SummaryReport:
240
+ """
241
+ Generate a comparison summary between two revisions.
242
+ :param source_revision_id: The ID of the source revision.
243
+ :param source_model_id: The ID of the source model.
244
+ :param target_revision_id: The ID of the target revision.
245
+ :param wait_for_completion: If True, the method will poll the task status and not return
246
+ until the task is complete. If False, it will spawn the task and return immediately.
247
+ :return: The created summary task or the summary report, if `wait_for_completion` is True.
248
+ """
249
+ payload = {
250
+ "sourceRevisionId": source_revision_id,
251
+ "sourceModelId": source_model_id,
252
+ "targetRevisionId": target_revision_id,
253
+ }
254
+ res = await self._http.post(f"{self._url}/alm/summaryReportTasks", json=payload)
255
+ task = await self.get_comparison_summary_task(res["task"]["taskId"])
256
+ logger.info(
257
+ f"Started Comparison Summary task '{task.id}' between Model '{source_model_id}' "
258
+ f"(Revision '{source_revision_id}') and Model '{self._model_id}'."
259
+ )
260
+ if not wait_for_completion:
261
+ return task
262
+ task = await self._http.poll_task(self.get_comparison_summary_task, task.id)
263
+ if not task.result.successful:
264
+ msg = f"Comparison Summary task {task.id} completed with errors: {task.result.error}."
265
+ logger.error(msg)
266
+ raise AnaplanActionError(msg)
267
+ logger.info(f"Comparison Summary task {task.id} completed successfully.")
268
+ return await self.get_comparison_summary(task)
269
+
270
+ async def get_comparison_summary_task(self, task_id: str) -> ReportTask:
271
+ """
272
+ Get the task information for a comparison summary task.
273
+ :param task_id: The ID of the comparison summary task.
274
+ :return: The report task information.
275
+ """
276
+ res = await self._http.get(f"{self._url}/alm/summaryReportTasks/{task_id}")
277
+ return ReportTask.model_validate(res["task"])
278
+
279
+ async def get_comparison_summary(self, task: ReportTask) -> SummaryReport:
280
+ """
281
+ Get the comparison summary for a specific task.
282
+ :param task: The summary task object containing the task ID.
283
+ :return: The binary content of the comparison summary.
284
+ """
285
+ res = await self._http.get(
286
+ f"{self._url}/alm/summaryReports/"
287
+ f"{task.result.target_revision_id}/{task.result.source_revision_id}"
288
+ )
289
+ return SummaryReport.model_validate(res["summaryReport"])
@@ -1,35 +1,43 @@
1
- from typing import Literal
1
+ from typing import Any, Literal
2
2
 
3
- import httpx
4
-
5
- from anaplan_sdk._base import _AsyncBaseClient
3
+ from anaplan_sdk._services import _AsyncHttpService
4
+ from anaplan_sdk._utils import sort_params
6
5
  from anaplan_sdk.models import User
7
6
 
8
7
  Event = Literal["all", "byok", "user_activity"]
8
+ UserSortBy = Literal["first_name", "last_name", "email", "active", "last_login_date"] | None
9
9
 
10
10
 
11
- class _AsyncAuditClient(_AsyncBaseClient):
12
- def __init__(self, client: httpx.AsyncClient, retry_count: int) -> None:
13
- self._limit = 10_000
11
+ class _AsyncAuditClient:
12
+ def __init__(self, http: _AsyncHttpService) -> None:
13
+ self._http = http
14
14
  self._url = "https://audit.anaplan.com/audit/api/1/events"
15
- super().__init__(retry_count, client)
16
15
 
17
- async def list_users(self, search_pattern: str | None = None) -> list[User]:
16
+ async def get_users(
17
+ self,
18
+ search_pattern: str | None = None,
19
+ sort_by: UserSortBy = None,
20
+ descending: bool = False,
21
+ ) -> list[User]:
18
22
  """
19
23
  Lists all the Users in the authenticated users default tenant.
20
- :param search_pattern: Optionally filter for specific users. When provided,
24
+ :param search_pattern: **Caution: This is an undocumented Feature and may behave
25
+ unpredictably. It requires the Tenant Admin role. For non-admin users, it is
26
+ ignored.** Optionally filter for specific users. When provided,
21
27
  case-insensitive matches users with emails or names containing this string.
22
28
  You can use the wildcards `%` for 0-n characters, and `_` for exactly 1 character.
23
29
  When None (default), returns all users.
30
+ :param sort_by: The field to sort the results by.
31
+ :param descending: If True, the results will be sorted in descending order.
24
32
  :return: The List of Users.
25
33
  """
26
- params = {"s": search_pattern} if search_pattern else None
27
- return [
28
- User.model_validate(e)
29
- for e in await self._get_paginated(
30
- "https://api.anaplan.com/2/0/users", "users", params=params
31
- )
32
- ]
34
+ params = sort_params(sort_by, descending)
35
+ if search_pattern:
36
+ params["s"] = search_pattern
37
+ res = await self._http.get_paginated(
38
+ "https://api.anaplan.com/2/0/users", "users", params=params
39
+ )
40
+ return [User.model_validate(e) for e in res]
33
41
 
34
42
  async def get_user(self, user_id: str = "me") -> User:
35
43
  """
@@ -37,19 +45,21 @@ class _AsyncAuditClient(_AsyncBaseClient):
37
45
  :return: The requested or currently authenticated User.
38
46
  """
39
47
  return User.model_validate(
40
- (await self._get(f"https://api.anaplan.com/2/0/users/{user_id}")).get("user")
48
+ (await self._http.get(f"https://api.anaplan.com/2/0/users/{user_id}")).get("user")
41
49
  )
42
50
 
43
- async def get_events(self, days_into_past: int = 30, event_type: Event = "all") -> list:
51
+ async def get_events(
52
+ self, days_into_past: int = 30, event_type: Event = "all"
53
+ ) -> list[dict[str, Any]]:
44
54
  """
45
55
  Get audit events from Anaplan Audit API.
46
56
  :param days_into_past: The nuber of days into the past to get events for. The API provides
47
57
  data for up to 30 days.
48
58
  :param event_type: The type of events to get.
49
- :return: A list of audit events.
59
+ :return: A list of log entries, each containing a dictionary with event details.
50
60
  """
51
61
  return list(
52
- await self._get_paginated(
62
+ await self._http.get_paginated(
53
63
  self._url,
54
64
  "response",
55
65
  params={"type": event_type, "intervalInHours": days_into_past * 24},