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