pepr-client 1.0.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.
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.3
2
+ Name: pepr-client
3
+ Version: 1.0.0
4
+ Summary: A simple python client for reading PEPR actions.
5
+ Author: Åsmund Våge Fannemel
6
+ Author-email: Åsmund Våge Fannemel <34712686+asmfstatoil@users.noreply.github.com>
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.10
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Requires-Dist: requests>=2.31.0,<3
14
+ Requires-Dist: msal-bearer>=1.4.3
15
+ Requires-Python: >=3.9.2, <4
16
+ Description-Content-Type: text/markdown
17
+
18
+ # pepr-python-client
19
+ A simple python client for reading PEPR actions from Public client api at https://api.gateway.equinor.com/pepr
20
+
21
+ # Try it out
22
+ See [demo.py](examples/demo.py)
23
+
24
+ ## Installing
25
+
26
+ Install package from git using `pip install git+https://github.com/equinor/pepr-client-python`
27
+
28
+
29
+ ## Developing / testing
30
+
31
+ Poetry is preferred for developers. Clone and install with required packages for testing and coverage:
32
+ `poetry install`
33
+
34
+ For testing with coverage run:
35
+ `poetry run pytest --cov --cov-report=html`
@@ -0,0 +1,18 @@
1
+ # pepr-python-client
2
+ A simple python client for reading PEPR actions from Public client api at https://api.gateway.equinor.com/pepr
3
+
4
+ # Try it out
5
+ See [demo.py](examples/demo.py)
6
+
7
+ ## Installing
8
+
9
+ Install package from git using `pip install git+https://github.com/equinor/pepr-client-python`
10
+
11
+
12
+ ## Developing / testing
13
+
14
+ Poetry is preferred for developers. Clone and install with required packages for testing and coverage:
15
+ `poetry install`
16
+
17
+ For testing with coverage run:
18
+ `poetry run pytest --cov --cov-report=html`
@@ -0,0 +1,5 @@
1
+ from .action import Action, get_action_ids, get_actions
2
+ from .facility import Facility
3
+ from .loss import Loss, get_loss_ids, get_losses
4
+
5
+ __all__ = ["Action", "Facility", "Loss"]
@@ -0,0 +1,470 @@
1
+ import logging
2
+ import json
3
+ import os
4
+ import pickle
5
+ from typing import List, Optional, Tuple, Union
6
+
7
+ from pepr_client.connector import _post
8
+
9
+ MIN_ACTION_ID = 80000000
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ def read_action(action_id: int) -> dict:
15
+ """Get data for a given PEPR action by ID as JSON.
16
+
17
+ Args:
18
+ action_id (int): ID of PEPR action to read
19
+
20
+ Returns:
21
+ str: Returned JSON data from query.
22
+ """
23
+ q = f"""
24
+ {{
25
+ action(id: {action_id}) {{
26
+ createdBy {{
27
+ displayName
28
+ }}
29
+ description
30
+ dueDate
31
+ id
32
+ plantNumber
33
+ tagNumber
34
+ status
35
+ keywords {{
36
+ keyword
37
+ }}
38
+ genericFlags {{
39
+ name
40
+ value
41
+ }}
42
+ title
43
+ sapNotifications
44
+ sapWorkOrders
45
+ serviceNowReferences
46
+ }}
47
+ }}"""
48
+
49
+ return _post(query=q)["data"]["action"]
50
+
51
+
52
+ def _get_action_ids(
53
+ sap_code: Union[str, int],
54
+ keyword: Optional[Union[str, List[str]]] = None,
55
+ status_code: str = "",
56
+ take: int = 50,
57
+ skip: int = 0,
58
+ ) -> List[int]:
59
+ """Get action ids for a specified asset.
60
+
61
+ Args:
62
+ sap_code (str, int): SAP code for a Plant.
63
+ keyword (str | List[str] | None, optional): Optional keyword filter. If None or empty, keyword is omitted.
64
+ status_code (str, optional): Currently not in use. Defaults to "".
65
+ take (int, optional): Number of ids to get. Defaults to 50.
66
+ skip (int, optional): Number of action ids to skip. Defaults to 0.
67
+
68
+
69
+ Raises:
70
+ ValueError: _description_
71
+
72
+ Returns:
73
+ List[int]: List of action ids.
74
+ """
75
+
76
+ if not isinstance(sap_code, int):
77
+ try:
78
+ sap_code = int(sap_code)
79
+ except:
80
+ sap_code = None
81
+
82
+ if (
83
+ sap_code is None
84
+ or isinstance(sap_code, int)
85
+ and (sap_code < 1000 or sap_code > 2000)
86
+ ):
87
+ raise ValueError("Input sap_code is required and must be a valid SAP code.")
88
+
89
+ if take > 50:
90
+ logger.warning("Take is limited to 50 actions per fetch. Set to 50.")
91
+ take = 50
92
+
93
+ if take < 0:
94
+ take = 50
95
+
96
+ query_filter_parts = [f"plantNumbers: {sap_code}"]
97
+
98
+ if isinstance(keyword, str):
99
+ keyword = keyword.strip()
100
+ if keyword:
101
+ query_filter_parts.append(f'keyword: "{keyword}"')
102
+ elif isinstance(keyword, list):
103
+ filtered_keywords = [
104
+ x.strip() for x in keyword if isinstance(x, str) and x.strip()
105
+ ]
106
+ if filtered_keywords:
107
+ formatted_keywords = ", ".join(f'"{x}"' for x in filtered_keywords)
108
+ query_filter_parts.append(f"keyword: [{formatted_keywords}]")
109
+
110
+ if status_code:
111
+ query_filter_parts.append(f'statusCodes: "{status_code}"')
112
+
113
+ query_filter = "{ " + ", ".join(query_filter_parts) + " }"
114
+
115
+ q = f"""
116
+ query {{
117
+ actions(input: {{ query: {query_filter} }}, take: {take}, skip: {skip}) {{
118
+ items {{
119
+ id
120
+ }}
121
+ }}
122
+ }}"""
123
+
124
+ ids = _post(query=q)
125
+ if ids is None:
126
+ return []
127
+
128
+ return [x["id"] for x in ids["data"]["actions"]["items"]]
129
+
130
+
131
+ def get_action_ids(
132
+ sap_code: Union[str, int],
133
+ keyword: Optional[Union[str, List[str]]] = None,
134
+ take: int = 150,
135
+ skip: int = 0,
136
+ ) -> List[int]:
137
+ """Get action ids for a Plant.
138
+
139
+ Args:
140
+ sap_code (str, int): SAP code to get pepr IDs for.
141
+ keyword (str | List[str] | None, optional): Optional keyword filter. If None or empty, keyword is omitted.
142
+ take (int, optional): Limit number of IDs to get. Defaults to 150. Set negative number to iterate through all IDs.
143
+ skip (int, optional): Number of IDs to skip. Defaults to 0.
144
+
145
+ Returns:
146
+ List[int]: List of action ids
147
+ """
148
+ results = []
149
+
150
+ while take < 0 or take > len(results):
151
+ new_ids = _get_action_ids(
152
+ sap_code,
153
+ keyword=keyword,
154
+ skip=skip + len(results),
155
+ take=take - len(results),
156
+ )
157
+ if len(new_ids) == 0:
158
+ break
159
+
160
+ results.extend(new_ids)
161
+
162
+ results.sort()
163
+ return results
164
+
165
+
166
+ def get_actions(
167
+ sap_code: Union[str, int],
168
+ keyword: Optional[Union[str, List[str]]] = None,
169
+ take: int = -1,
170
+ skip: int = 0,
171
+ ) -> List["Action"]:
172
+ """Get actions for a Plant.
173
+
174
+ Args:
175
+ sap_code (str): SAP code to get actions for.
176
+ keyword (str | List[str] | None, optional): Optional keyword filter. If None or empty, keyword is omitted.
177
+ take (int, optional): Limit number of IDs to get. Defaults to -1, which will return all Actions for the sap_code.
178
+ skip (int, optional): Number of Actions to skip. Defaults to 0, which will return all actions.
179
+
180
+ Returns:
181
+ List[Action]: List of Action objects.
182
+ """
183
+ ids = get_action_ids(sap_code, keyword=keyword, take=take, skip=skip)
184
+ if len(ids) == 0:
185
+ return []
186
+
187
+ return [Action(x) for x in ids]
188
+
189
+
190
+ class Action:
191
+ def __init__(self, id: int):
192
+ """Constructor for PEPR Action object.
193
+
194
+ Args:
195
+ id (int): Action ID.
196
+ """
197
+ self._data = read_action(id)
198
+
199
+ @property
200
+ def id(self):
201
+ return self._data.get("id", -1)
202
+
203
+ @property
204
+ def description(self) -> str:
205
+ return self._data.get("description", "")
206
+
207
+ @property
208
+ def sap_code(self) -> int:
209
+ return int(self._data.get("plantNumber", 0))
210
+
211
+ @property
212
+ def tag_number(self):
213
+ return self._data.get("tagNumber", "")
214
+
215
+ @property
216
+ def sap_notification(self) -> str:
217
+ return self._data.get("sapNotifications", "")
218
+
219
+ @property
220
+ def created_by_display_name(self):
221
+ return self._data["createdBy"]["displayName"]
222
+
223
+ @property
224
+ def status(self):
225
+ return self._data["status"]
226
+
227
+ @property
228
+ def title(self):
229
+ return self._data["title"]
230
+
231
+ @property
232
+ def due_date(self):
233
+ return self._data["dueDate"]
234
+
235
+ @staticmethod
236
+ def _normalize_string_list(value) -> List[str]:
237
+ if value is None:
238
+ return []
239
+ if isinstance(value, str):
240
+ return [value]
241
+ if isinstance(value, list):
242
+ return [x for x in value if isinstance(x, str)]
243
+ return []
244
+
245
+ @property
246
+ def keywords(self) -> List[str]:
247
+ raw_keywords = self._data.get("keywords", [])
248
+ if isinstance(raw_keywords, list):
249
+ return [
250
+ x.get("keyword", "")
251
+ for x in raw_keywords
252
+ if isinstance(x, dict) and isinstance(x.get("keyword"), str)
253
+ ]
254
+ return []
255
+
256
+ @property
257
+ def keyword(self) -> List[str]:
258
+ return self.keywords
259
+
260
+ @property
261
+ def generic_flags(self) -> List[Tuple[str, bool]]:
262
+ raw_flags = self._data.get("genericFlags", [])
263
+ if not isinstance(raw_flags, list):
264
+ return []
265
+
266
+ flags = []
267
+ for flag in raw_flags:
268
+ if not isinstance(flag, dict):
269
+ continue
270
+ name = flag.get("name")
271
+ value = flag.get("value")
272
+ if isinstance(name, str) and isinstance(value, bool):
273
+ flags.append((name, value))
274
+ return flags
275
+
276
+ @property
277
+ def genericflags(self) -> List[Tuple[str, bool]]:
278
+ return self.generic_flags
279
+
280
+ @property
281
+ def sap_work_orders(self) -> List[str]:
282
+ return self._normalize_string_list(self._data.get("sapWorkOrders", []))
283
+
284
+ @property
285
+ def sapworkorders(self) -> List[str]:
286
+ return self.sap_work_orders
287
+
288
+ @property
289
+ def service_now_references(self) -> List[str]:
290
+ return self._normalize_string_list(self._data.get("serviceNowReferences", []))
291
+
292
+ @property
293
+ def servicenowreferences(self) -> List[str]:
294
+ return self.service_now_references
295
+
296
+ def __str__(self):
297
+ return f"Task ID: {self.id}\nTitle: {self.title}\nDescription: {self.description}\nStatus: {self.status}\nCreated by: {self.created_by_display_name}\nPlant Numbers: {self.sap_code}\nSAP Notification Reference: {self.sap_notification}"
298
+
299
+ def to_json(self, indent: Optional[int] = None) -> str:
300
+ """Serialize Action object to a JSON formatted str.
301
+
302
+
303
+ Args:
304
+ indent (int, optional): Passed along to json.dumps. Defaults to None.
305
+
306
+ Returns:
307
+ str: JSON formatted str of Action object.
308
+ """
309
+ return json.dumps(self.__dict__, indent=indent)
310
+
311
+ def to_json_file(self, file_path: str = "", indent: Optional[int] = None) -> None:
312
+ """
313
+ Serializes the current instance and saves it as a JSON text file.
314
+
315
+ Args:
316
+ file_path (str, optional): The path to the text file where the object will be saved.
317
+ If not provided, the default file path is generated based on
318
+ the instance's `id` and `sap_code`. Can be a string or any
319
+ object that implements the `os.PathLike` interface.
320
+ indent (int, optional): Passed along to json.dumps. Defaults to None.
321
+
322
+
323
+ Raises:
324
+ OSError: If there is an issue creating the target directory or writing to the file.
325
+ pickle.PicklingError: If the object cannot be serialized properly.
326
+
327
+ Example:
328
+ action = Action(id=1234, sap_code="ABCD")
329
+ action.to_json_file("cache/ABCD/1234.txt")
330
+ # This will save the action instance to the specified text file.
331
+
332
+ Note:
333
+ - If the specified `file_path` already exists, it will be overwritten.
334
+ - The method automatically creates the necessary directories if they don't already exist.
335
+ """
336
+ if file_path is None or len(file_path) == 0:
337
+ file_path = Action.get_pickle_filename(id=self.id, sap_code=self.sap_code)
338
+ file_path = file_path.replace("pkl", "txt")
339
+
340
+ while len(os.path.dirname(file_path)) > 0 and not os.path.isdir(
341
+ os.path.dirname(file_path)
342
+ ):
343
+ dir_name = os.path.dirname(file_path)
344
+ while len(os.path.dirname(dir_name)) > 0 and not os.path.isdir(
345
+ os.path.dirname(dir_name)
346
+ ):
347
+ dir_name = os.path.dirname(dir_name)
348
+ if len(dir_name) > 0:
349
+ os.mkdir(dir_name)
350
+
351
+ with open(file_path, "wb") as file:
352
+ # A new file will be created or existing file will be overwritten
353
+ with open(file_path, "w", encoding="utf-8") as file:
354
+ json.dump(self.__dict__, file, indent=indent, ensure_ascii=False)
355
+
356
+ def to_pickle(self, file_path: str = "") -> None:
357
+ """
358
+ Serializes the current instance and saves it as a pickle file.
359
+
360
+ Args:
361
+ file_path (str, optional): The path to the pickle file where the object will be saved.
362
+ If not provided, the default file path is generated based on
363
+ the instance's `id` and `sap_code`. Can be a string or any
364
+ object that implements the `os.PathLike` interface.
365
+
366
+
367
+ Raises:
368
+ OSError: If there is an issue creating the target directory or writing to the file.
369
+ pickle.PicklingError: If the object cannot be serialized properly.
370
+
371
+ Example:
372
+ action = Action(id=1234, sap_code="ABCD")
373
+ action.to_pickle("cache/ABCD/1234.pkl")
374
+ # This will save the action instance to the specified pickle file.
375
+
376
+ Note:
377
+ - If the specified `file_path` already exists, it will be overwritten.
378
+ - The method automatically creates the necessary directories if they don't already exist.
379
+ """
380
+
381
+ if file_path is None or len(file_path) == 0:
382
+ file_path = Action.get_pickle_filename(id=self.id, sap_code=self.sap_code)
383
+
384
+ while len(os.path.dirname(file_path)) > 0 and not os.path.isdir(
385
+ os.path.dirname(file_path)
386
+ ):
387
+ dir_name = os.path.dirname(file_path)
388
+ while len(os.path.dirname(dir_name)) > 0 and not os.path.isdir(
389
+ os.path.dirname(dir_name)
390
+ ):
391
+ dir_name = os.path.dirname(dir_name)
392
+ if len(dir_name) > 0:
393
+ os.mkdir(dir_name)
394
+
395
+ with open(file_path, "wb") as file:
396
+ # A new file will be created or existing file will be overwritten
397
+ pickle.dump(self, file)
398
+
399
+ @staticmethod
400
+ def get_pickle_filename(id, sap_code: Optional[Union[List[str], str, int]] = None):
401
+ """
402
+ Generates the filename for a pickle file based on the given ID and SAP code.
403
+
404
+ Args:
405
+ id (str or int): The unique identifier used in the pickle filename.
406
+ sap_code (str, int, or list, optional): The SAP code that determines the
407
+ subdirectory in the cache folder. If a list is provided, only the first element is used. If no SAP code is provided, the method defaults to `None`.
408
+
409
+ Returns:
410
+ str: The generated file path for the pickle file in the format `cache/{sap_code}/{id}.pkl`.
411
+
412
+ Example:
413
+ filename = get_pickle_filename(1234, sap_code="ABCD")
414
+ # Returns: "cache/ABCD/1234.pkl"
415
+ """
416
+ if isinstance(sap_code, list):
417
+ sap_code = sap_code[0]
418
+
419
+ if not isinstance(sap_code, str):
420
+ sap_code = str(sap_code)
421
+
422
+ return f"cache/{sap_code}/{id}.pkl"
423
+
424
+ @staticmethod
425
+ def from_pickle(file_path: str):
426
+ """
427
+ Loads an Action object from a pickle file.
428
+
429
+ Args:
430
+ file_path (str): The path to the pickle file containing the serialized Action object.
431
+
432
+ Returns:
433
+ Action: The unpickled Action object.
434
+
435
+ Raises:
436
+ TypeError: If the unpickled object is not an instance of the Action class.
437
+ FileNotFoundError: If the specified file path does not exist.
438
+ pickle.UnpicklingError: If there is an error in unpickling the object.
439
+
440
+ Example:
441
+ action = Action.from_pickle("path_to_pickle_file.pkl")
442
+
443
+ Note:
444
+ Ensure the pickle file is from a trusted source, as unpickling can execute arbitrary code.
445
+ """
446
+ with open(file_path, "rb") as f:
447
+ saved_action = pickle.load(f)
448
+ if not isinstance(saved_action, Action):
449
+ raise TypeError("Unpickled object is not of type Action")
450
+
451
+ return saved_action
452
+
453
+ @staticmethod
454
+ def search_actions(
455
+ sap_code: Union[str, int],
456
+ keyword: Optional[Union[str, List[str]]] = None,
457
+ take: int = -1,
458
+ skip: int = 0,
459
+ ) -> List["Action"]:
460
+ """Search for actions based on SAP code and optional keyword.
461
+
462
+ Args:
463
+ sap_code (str, int): SAP code to search actions for.
464
+ keyword (str | List[str] | None, optional): Optional keyword filter. If None or empty, keyword is omitted.
465
+ take (int, optional): Limit number of IDs to get. Defaults to -1, which will return all Actions for the sap_code.
466
+ skip (int, optional): Number of Actions to skip. Defaults to 0, which will return all actions.
467
+ Returns:
468
+ List[Action]: List of Action objects matching the search criteria.
469
+ """
470
+ return get_actions(sap_code=sap_code, keyword=keyword, take=take, skip=skip)