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