ITK-dev-shared-components 1.0.0__tar.gz → 1.2.0__tar.gz

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.
Files changed (35) hide show
  1. itk_dev_shared_components-1.2.0/PKG-INFO +66 -0
  2. itk_dev_shared_components-1.2.0/README.md +47 -0
  3. {itk_dev_shared_components-1.0.0 → itk_dev_shared_components-1.2.0}/itk_dev_shared_components/graph/authentication.py +2 -1
  4. {itk_dev_shared_components-1.0.0 → itk_dev_shared_components-1.2.0}/itk_dev_shared_components/graph/mail.py +6 -6
  5. itk_dev_shared_components-1.2.0/itk_dev_shared_components/kmd_nova/__init__.py +3 -0
  6. itk_dev_shared_components-1.2.0/itk_dev_shared_components/kmd_nova/authentication.py +59 -0
  7. itk_dev_shared_components-1.2.0/itk_dev_shared_components/kmd_nova/cpr.py +36 -0
  8. itk_dev_shared_components-1.2.0/itk_dev_shared_components/kmd_nova/nova_cases.py +228 -0
  9. itk_dev_shared_components-1.2.0/itk_dev_shared_components/kmd_nova/nova_documents.py +189 -0
  10. itk_dev_shared_components-1.2.0/itk_dev_shared_components/kmd_nova/nova_objects.py +77 -0
  11. itk_dev_shared_components-1.2.0/itk_dev_shared_components/kmd_nova/nova_tasks.py +138 -0
  12. itk_dev_shared_components-1.2.0/itk_dev_shared_components/kmd_nova/util.py +36 -0
  13. itk_dev_shared_components-1.2.0/itk_dev_shared_components/misc/cpr_util.py +58 -0
  14. itk_dev_shared_components-1.2.0/itk_dev_shared_components/sap/__init__.py +0 -0
  15. {itk_dev_shared_components-1.0.0 → itk_dev_shared_components-1.2.0}/itk_dev_shared_components/sap/gridview_util.py +7 -5
  16. {itk_dev_shared_components-1.0.0 → itk_dev_shared_components-1.2.0}/itk_dev_shared_components/sap/multi_session.py +44 -25
  17. itk_dev_shared_components-1.2.0/itk_dev_shared_components/sap/opret_kundekontakt.py +107 -0
  18. {itk_dev_shared_components-1.0.0 → itk_dev_shared_components-1.2.0}/itk_dev_shared_components/sap/sap_login.py +11 -12
  19. {itk_dev_shared_components-1.0.0 → itk_dev_shared_components-1.2.0}/itk_dev_shared_components/sap/sap_util.py +6 -4
  20. {itk_dev_shared_components-1.0.0 → itk_dev_shared_components-1.2.0}/itk_dev_shared_components/sap/tree_util.py +5 -4
  21. itk_dev_shared_components-1.2.0/itk_dev_shared_components.egg-info/PKG-INFO +66 -0
  22. {itk_dev_shared_components-1.0.0 → itk_dev_shared_components-1.2.0}/itk_dev_shared_components.egg-info/SOURCES.txt +10 -0
  23. {itk_dev_shared_components-1.0.0 → itk_dev_shared_components-1.2.0}/pyproject.toml +1 -1
  24. itk_dev_shared_components-1.0.0/PKG-INFO +0 -24
  25. itk_dev_shared_components-1.0.0/README.md +0 -5
  26. itk_dev_shared_components-1.0.0/itk_dev_shared_components/sap/opret_kundekontakt.py +0 -65
  27. itk_dev_shared_components-1.0.0/itk_dev_shared_components.egg-info/PKG-INFO +0 -24
  28. {itk_dev_shared_components-1.0.0 → itk_dev_shared_components-1.2.0}/LICENSE +0 -0
  29. {itk_dev_shared_components-1.0.0 → itk_dev_shared_components-1.2.0}/itk_dev_shared_components/__init__.py +0 -0
  30. {itk_dev_shared_components-1.0.0 → itk_dev_shared_components-1.2.0}/itk_dev_shared_components/graph/__init__.py +0 -0
  31. {itk_dev_shared_components-1.0.0/itk_dev_shared_components/sap → itk_dev_shared_components-1.2.0/itk_dev_shared_components/misc}/__init__.py +0 -0
  32. {itk_dev_shared_components-1.0.0 → itk_dev_shared_components-1.2.0}/itk_dev_shared_components.egg-info/dependency_links.txt +0 -0
  33. {itk_dev_shared_components-1.0.0 → itk_dev_shared_components-1.2.0}/itk_dev_shared_components.egg-info/requires.txt +0 -0
  34. {itk_dev_shared_components-1.0.0 → itk_dev_shared_components-1.2.0}/itk_dev_shared_components.egg-info/top_level.txt +0 -0
  35. {itk_dev_shared_components-1.0.0 → itk_dev_shared_components-1.2.0}/setup.cfg +0 -0
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.1
2
+ Name: itk_dev_shared_components
3
+ Version: 1.2.0
4
+ Summary: Shared components to use in RPA projects
5
+ Author-email: ITK Development <itk-rpa@mkb.aarhus.dk>
6
+ Project-URL: Homepage, https://github.com/itk-dev-rpa/itk-dev-shared-components
7
+ Project-URL: Bug Tracker, https://github.com/itk-dev-rpa/itk-dev-shared-components/issues
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: Microsoft :: Windows
11
+ Requires-Python: >=3.7
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: pywin32>=306
15
+ Requires-Dist: selenium>=4.10.0
16
+ Requires-Dist: msal>=1.24.1
17
+ Requires-Dist: requests>=2.31.0
18
+ Requires-Dist: beautifulsoup4>=4.12.2
19
+
20
+ # itk-dev-shared-components
21
+
22
+ ## Links
23
+
24
+ [Documentation](https://itk-dev-rpa.github.io/itk-dev-shared-components-docs/)
25
+
26
+ [Pypi](https://pypi.org/project/ITK-dev-shared-components/)
27
+
28
+ ## Installation
29
+
30
+ ```
31
+ pip install itk-dev-shared-components
32
+ ```
33
+
34
+ ## Intro
35
+
36
+ This python library contains helper modules for RPA development.
37
+ It's based on the need of [ITK Dev](https://itk.aarhus.dk/), but it has been
38
+ generalized to be useful for others as well.
39
+
40
+ ## Integrations
41
+
42
+ ### SAP Gui
43
+
44
+ Helper functions for using SAP Gui. A few examples include:
45
+
46
+ - Login to SAP.
47
+ - Handling multiple sessions in multiple threads.
48
+ - Convenience functions for gridviews and trees.
49
+
50
+ ### Microsoft Graph
51
+
52
+ Helper functions for using Microsoft Graph to read emails from shared inboxes.
53
+ Some examples are:
54
+
55
+ - Authentication using username and password.
56
+ - List and get emails.
57
+ - Get attachment data.
58
+ - Move and delete emails.
59
+
60
+ ### KMD Nova
61
+
62
+ Helper functions for using the KMD Nova api.
63
+ Some examples are:
64
+
65
+ - Get cases and documents.
66
+ - Create cases, documents and tasks.
@@ -0,0 +1,47 @@
1
+ # itk-dev-shared-components
2
+
3
+ ## Links
4
+
5
+ [Documentation](https://itk-dev-rpa.github.io/itk-dev-shared-components-docs/)
6
+
7
+ [Pypi](https://pypi.org/project/ITK-dev-shared-components/)
8
+
9
+ ## Installation
10
+
11
+ ```
12
+ pip install itk-dev-shared-components
13
+ ```
14
+
15
+ ## Intro
16
+
17
+ This python library contains helper modules for RPA development.
18
+ It's based on the need of [ITK Dev](https://itk.aarhus.dk/), but it has been
19
+ generalized to be useful for others as well.
20
+
21
+ ## Integrations
22
+
23
+ ### SAP Gui
24
+
25
+ Helper functions for using SAP Gui. A few examples include:
26
+
27
+ - Login to SAP.
28
+ - Handling multiple sessions in multiple threads.
29
+ - Convenience functions for gridviews and trees.
30
+
31
+ ### Microsoft Graph
32
+
33
+ Helper functions for using Microsoft Graph to read emails from shared inboxes.
34
+ Some examples are:
35
+
36
+ - Authentication using username and password.
37
+ - List and get emails.
38
+ - Get attachment data.
39
+ - Move and delete emails.
40
+
41
+ ### KMD Nova
42
+
43
+ Helper functions for using the KMD Nova api.
44
+ Some examples are:
45
+
46
+ - Get cases and documents.
47
+ - Create cases, documents and tasks.
@@ -3,6 +3,7 @@ connection."""
3
3
 
4
4
  import msal
5
5
 
6
+
6
7
  # pylint: disable-next=too-few-public-methods
7
8
  class GraphAccess:
8
9
  """An object that handles access to the Graph api.
@@ -45,7 +46,7 @@ def authorize_by_username_password(username: str, password: str, *, client_id: s
45
46
  password: The password of the user.
46
47
  client_id: The Graph API client id in 8-4-4-12 format.
47
48
  tenant_id: The Graph API tenant id in 8-4-4-12 format.
48
-
49
+
49
50
  Returns:
50
51
  GraphAccess: The GraphAccess object used to authorize Graph access.
51
52
  """
@@ -162,15 +162,15 @@ def get_attachment_data(attachment: Attachment, graph_access: GraphAccess) -> io
162
162
  """
163
163
  email = attachment.email
164
164
  endpoint = f"https://graph.microsoft.com/v1.0/users/{email.user}/messages/{email.id}/attachments/{attachment.id}/$value"
165
- response = _get_request(endpoint, graph_access)
165
+ response = _get_request(endpoint, graph_access)
166
166
  data_bytes = response.content
167
167
  return io.BytesIO(data_bytes)
168
168
 
169
169
 
170
- def move_email(email: Email, folder_path: str, graph_access: GraphAccess, *, well_known_folder: bool=False) -> None:
170
+ def move_email(email: Email, folder_path: str, graph_access: GraphAccess, *, well_known_folder: bool = False) -> None:
171
171
  """Move an email to another folder under the same user.
172
172
  If well_known_folder is true, the folder path is assumed to be a well defined folder.
173
- See https://learn.microsoft.com/en-us/graph/api/resources/mailfolder?view=graph-rest-1.0
173
+ See https://learn.microsoft.com/en-us/graph/api/resources/mailfolder?view=graph-rest-1.0
174
174
  for a list of well defined folder names.
175
175
 
176
176
  Args:
@@ -208,7 +208,7 @@ def move_email(email: Email, folder_path: str, graph_access: GraphAccess, *, wel
208
208
  email.id = new_id
209
209
 
210
210
 
211
- def delete_email(email: Email, graph_access: GraphAccess, *, permanent: bool=False) -> None:
211
+ def delete_email(email: Email, graph_access: GraphAccess, *, permanent: bool = False) -> None:
212
212
  """Delete an email from the mailbox.
213
213
  If permanent is true the email is completely removed from the user's mailbox.
214
214
  If permanent is false the email is instead moved to the Deleted Items folder.
@@ -235,7 +235,7 @@ def delete_email(email: Email, graph_access: GraphAccess, *, permanent: bool=Fal
235
235
 
236
236
 
237
237
  def _find_folder(response: dict, target_folder: str) -> str:
238
- """Find the target folder in
238
+ """Find the target folder in
239
239
 
240
240
  Args:
241
241
  response: The json dict of the HTTP response.
@@ -300,7 +300,7 @@ def _get_request(endpoint: str, graph_access: GraphAccess) -> requests.models.Re
300
300
 
301
301
  Returns:
302
302
  Response: The response object of the GET request.
303
-
303
+
304
304
  Raises:
305
305
  HTTPError: Any errors raised while performing GET request.
306
306
  """
@@ -0,0 +1,3 @@
1
+ """This module provides helper functions to use the KMD Nova api.
2
+ The api is documented here: https://novaapi.kmd.dk/swagger/index.html
3
+ """
@@ -0,0 +1,59 @@
1
+ """This module contains functionality to authenticate against the KMD Nova api."""
2
+
3
+ from datetime import datetime, timedelta
4
+ import urllib
5
+
6
+ import requests
7
+
8
+
9
+ # pylint: disable-next=too-few-public-methods
10
+ class NovaAccess:
11
+ """An object that handles access to the KMD Nova api."""
12
+ def __init__(self, client_id: str, client_secret: str, domain: str = "https://cap-novaapi.kmd.dk") -> None:
13
+ self.client_id = client_id
14
+ self.client_secret = client_secret
15
+ self._bearer_token, self.token_expiry_date = self._get_new_token()
16
+ self.domain = domain
17
+
18
+ def _get_new_token(self) -> tuple[str, datetime]:
19
+ """
20
+ This method requests a new token from the API.
21
+ When the token expiry date is passed, requests with the token to the API will return HTTP 401 status code.
22
+
23
+ Returns:
24
+ tuple: token and expiry datetime
25
+
26
+ Raises:
27
+ requests.exceptions.HTTPError: If the request failed.
28
+ """
29
+
30
+ url = "https://novaauth.kmd.dk/realms/NovaIntegration/protocol/openid-connect/token"
31
+ payload = {
32
+ "client_secret": self.client_secret,
33
+ "grant_type": "client_credentials",
34
+ "client_id": self.client_id,
35
+ "scope": "client"
36
+ }
37
+ payload = urllib.parse.urlencode(payload)
38
+ headers = {'Content-Type': 'application/x-www-form-urlencoded'}
39
+
40
+ response = requests.post(url, headers=headers, data=payload, timeout=60)
41
+ response.raise_for_status()
42
+ response_json = response.json()
43
+ bearer_token = response_json['access_token']
44
+ token_life_seconds = response_json['expires_in']
45
+ token_expiry_date = datetime.now() + timedelta(seconds=int(token_life_seconds))
46
+ return bearer_token, token_expiry_date
47
+
48
+ def get_bearer_token(self) -> str:
49
+ """Return the bearer token. If the token is about to expire,
50
+ a new token is requested form the auth service.
51
+
52
+ Returns:
53
+ Bearer token
54
+ """
55
+
56
+ if self.token_expiry_date + timedelta(seconds=30) < datetime.now():
57
+ self._bearer_token, self.token_expiry_date = self._get_new_token()
58
+
59
+ return self._bearer_token
@@ -0,0 +1,36 @@
1
+ """This module has functions to do with cpr related calls
2
+ to the KMD Nova api."""
3
+
4
+ import uuid
5
+ import urllib.parse
6
+
7
+ import requests
8
+
9
+ from itk_dev_shared_components.kmd_nova.authentication import NovaAccess
10
+
11
+
12
+ def get_address_by_cpr(cpr: str, nova_access: NovaAccess) -> dict:
13
+ """Gets the street address of a citizen by their CPR number.
14
+
15
+ Args:
16
+ cpr: CPR number of the citizen.
17
+
18
+ Returns:
19
+ A dict with the address information.
20
+
21
+ Raises:
22
+ requests.exceptions.HTTPError: If the request failed.
23
+ """
24
+
25
+ url = urllib.parse.urljoin(nova_access.domain, "api/Cpr/GetAddressByCpr")
26
+ params = {
27
+ "TransactionId": str(uuid.uuid4()),
28
+ "Cpr": cpr,
29
+ "api-version": "1.0-Cpr"
30
+ }
31
+ headers = {'Authorization': f"Bearer {nova_access.get_bearer_token()}"}
32
+
33
+ response = requests.get(url, params=params, headers=headers, timeout=60)
34
+ response.raise_for_status()
35
+ address = response.json()
36
+ return address
@@ -0,0 +1,228 @@
1
+ """This module has functions to do with case related calls
2
+ to the KMD Nova api."""
3
+
4
+ import uuid
5
+ import base64
6
+ import urllib.parse
7
+
8
+ import requests
9
+
10
+ from itk_dev_shared_components.kmd_nova.authentication import NovaAccess
11
+ from itk_dev_shared_components.kmd_nova.nova_objects import NovaCase, CaseParty, JournalNote
12
+ from itk_dev_shared_components.kmd_nova.util import datetime_from_iso_string
13
+
14
+
15
+ def get_cases(nova_access: NovaAccess, cpr: str = None, case_number: str = None, case_title: str = None, limit: int = 100) -> list[NovaCase]:
16
+ """Search for cases on different search terms.
17
+ Currently supports search on cpr number, case number and case title. At least one search term must be given.
18
+
19
+ Args:
20
+ nova_access: The NovaAccess object used to authenticate.
21
+ cpr: The cpr number to search on. E.g. "0123456789"
22
+ case_number: The case number to search on. E.g. "S2022-12345"
23
+ case_title: The case title to search on.
24
+ limit: The maximum number of cases to find (1-500).
25
+
26
+ Returns:
27
+ A list of NovaCase objects.
28
+
29
+ Raises:
30
+ ValueError: If no search terms are given.
31
+ requests.exceptions.HTTPError: If the request failed.
32
+ """
33
+
34
+ if not any((cpr, case_number, case_title)):
35
+ raise ValueError("No search terms given.")
36
+
37
+ url = urllib.parse.urljoin(nova_access.domain, "api/Case/GetList")
38
+ params = {"api-version": "1.0-Case"}
39
+
40
+ payload = {
41
+ "common": {
42
+ "transactionId": str(uuid.uuid4())
43
+ },
44
+ "paging": {
45
+ "startRow": 1,
46
+ "numberOfRows": limit
47
+ },
48
+ "caseAttributes": {
49
+ "userFriendlyCaseNumber": case_number,
50
+ "title": case_title
51
+ },
52
+ "caseParty": {
53
+ "identificationType": "CprNummer",
54
+ "identification": cpr
55
+ },
56
+ "caseGetOutput": {
57
+ "numberOfSecondaryParties": True,
58
+ "caseParty": {
59
+ "identificationType": True,
60
+ "identification": True,
61
+ "participantRole": True,
62
+ "name": True,
63
+ "index": True
64
+ },
65
+ "caseAttributes": {
66
+ "title": True,
67
+ "userFriendlyCaseNumber": True,
68
+ "caseDate": True
69
+ },
70
+ "state": {
71
+ "activeCode": True,
72
+ "progressState": True
73
+ },
74
+ "numberOfDocuments": True,
75
+ "numberOfJournalNotes": True,
76
+ "caseClassification": {
77
+ "kleNumber": {
78
+ "code": True
79
+ },
80
+ "proceedingFacet": {
81
+ "code": True
82
+ }
83
+ },
84
+ "sensitivity": {
85
+ "sensitivity": True
86
+ }
87
+ }
88
+ }
89
+
90
+ headers = {'Content-Type': 'application/json', 'Authorization': f"Bearer {nova_access.get_bearer_token()}"}
91
+
92
+ response = requests.put(url, params=params, headers=headers, json=payload, timeout=60)
93
+ response.raise_for_status()
94
+
95
+ if response.json()['pagingInformation']['numberOfRows'] == 0:
96
+ return []
97
+
98
+ # Convert json to NovaCase objects
99
+ cases = []
100
+ for case_dict in response.json()['cases']:
101
+ case = NovaCase(
102
+ uuid = case_dict['common']['uuid'],
103
+ title = case_dict['caseAttributes']['title'],
104
+ case_date = datetime_from_iso_string(case_dict['caseAttributes']['caseDate']),
105
+ case_number = case_dict['caseAttributes']['userFriendlyCaseNumber'],
106
+ active_code = case_dict['state']['activeCode'],
107
+ progress_state = case_dict['state']['progressState'],
108
+ case_parties = _extract_case_parties(case_dict),
109
+ document_count = case_dict['numberOfDocuments'],
110
+ note_count = case_dict['numberOfJournalNotes'],
111
+ kle_number = case_dict['caseClassification']['kleNumber']['code'],
112
+ proceeding_facet = case_dict['caseClassification']['proceedingFacet']['code'],
113
+ sensitivity = case_dict["sensitivity"]["sensitivity"]
114
+ )
115
+
116
+ cases.append(case)
117
+
118
+ return cases
119
+
120
+
121
+ def _extract_case_parties(case_dict: dict) -> list[CaseParty]:
122
+ """Extract the case parties from a HTTP request response.
123
+
124
+ Args:
125
+ case_dict: The dictionary describing the case party.
126
+
127
+ Returns:
128
+ A case party object describing the case party.
129
+ """
130
+ parties = []
131
+ for party_dict in case_dict['caseParties']:
132
+ party = CaseParty(
133
+ uuid = party_dict['index'],
134
+ identification_type = party_dict['identificationType'],
135
+ identification = party_dict['identification'],
136
+ role = party_dict['participantRole'],
137
+ name = party_dict.get('name', None)
138
+ )
139
+ parties.append(party)
140
+
141
+ return parties
142
+
143
+
144
+ def _extract_journal_notes(case_dict: dict) -> list:
145
+ """Extract the journal notes from a HTTP request response.
146
+
147
+ Args:
148
+ case_dict: The dictionary describing the journal note.
149
+
150
+ Returns:
151
+ A journal note object describing the journal note.
152
+ """
153
+ notes = []
154
+ for note_dict in case_dict['journalNotes']['journalNotes']:
155
+ note = JournalNote(
156
+ uuid = note_dict['uuid'],
157
+ title = note_dict['journalNoteAttributes']['title'],
158
+ journal_date = note_dict['journalNoteAttributes']['journalNoteDate'],
159
+ note_format = note_dict['journalNoteAttributes']['format'],
160
+ note = base64.b64decode(note_dict['journalNoteAttributes']['note']),
161
+ approved = note_dict['journalNoteAttributes'].get('approved', False)
162
+ )
163
+ notes.append(note)
164
+ return notes
165
+
166
+
167
+ def add_case(case: NovaCase, nova_access: NovaAccess, security_unit_id: int = 818485, security_unit_name: str = "Borgerservice"):
168
+ """Add a case to KMD Nova. The case will be created as 'Active'.
169
+
170
+ Args:
171
+ case: The case object describing the case.
172
+ nova_access: The NovaAccess object used to authenticate.
173
+ security_unit_id: The id of the security unit that has access to the case. Defaults to 818485.
174
+ security_unit_name: The name of the security unit that has access to the case. Defaults to "Borgerservice".
175
+
176
+ Raises:
177
+ requests.exceptions.HTTPError: If the request failed.
178
+ """
179
+ url = urllib.parse.urljoin(nova_access.domain, "api/Case/Import")
180
+ params = {"api-version": "1.0-Case"}
181
+
182
+ payload = {
183
+ "common": {
184
+ "transactionId": str(uuid.uuid4()),
185
+ "uuid": case.uuid
186
+ },
187
+ "caseAttributes": {
188
+ "title": case.title,
189
+ "caseDate": case.case_date.isoformat()
190
+ },
191
+ "caseClassification": {
192
+ "kleNumber": {
193
+ "code": case.kle_number
194
+ },
195
+ "proceedingFacet": {
196
+ "code": case.proceeding_facet
197
+ }
198
+ },
199
+ "state": case.progress_state,
200
+ "sensitivity": case.sensitivity,
201
+ "caseParties": [
202
+ {
203
+ "name": party.name,
204
+ "identificationType": party.identification_type,
205
+ "identification": party.identification,
206
+ "participantRole": party.role
207
+ } for party in case.case_parties
208
+ ],
209
+ "securityUnit": {
210
+ "losIdentity": {
211
+ "administrativeUnitId": security_unit_id,
212
+ "fullName": security_unit_name,
213
+ }
214
+ },
215
+ "SensitivityCtrlBy": "Bruger",
216
+ "SecurityUnitCtrlBy": "Regler",
217
+ "ResponsibleDepartmentCtrlBy": "Regler",
218
+ "caseAvailability": {
219
+ "unit": "År",
220
+ "scale": 5
221
+ },
222
+ "AvailabilityCtrlBy": "Regler"
223
+ }
224
+
225
+ headers = {'Content-Type': 'application/json', 'Authorization': f"Bearer {nova_access.get_bearer_token()}"}
226
+
227
+ response = requests.post(url, params=params, headers=headers, json=payload, timeout=60)
228
+ response.raise_for_status()