epgu-api 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.
epgu/models.py ADDED
@@ -0,0 +1,433 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2025 yellow444 <yellow444@gmail.com>
3
+ """Typed, forward-compatible models for the EPGU API.
4
+
5
+ EPGU responses contain a large number of service-specific and undocumented
6
+ fields. The models below expose the stable fields from API specification 1.14
7
+ and retain the complete source object in ``raw`` so callers do not lose data
8
+ when the service adds another field.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import re
15
+ from collections.abc import Iterator, Mapping, Sequence
16
+ from dataclasses import dataclass, field
17
+ from typing import Any, Dict, List, Optional, Union, overload
18
+ from urllib.parse import unquote, urlparse
19
+
20
+
21
+ def _to_int(value: Any) -> Optional[int]:
22
+ """Convert an API scalar to ``int`` without treating ``0`` as missing."""
23
+ try:
24
+ return int(value)
25
+ except (TypeError, ValueError):
26
+ return None
27
+
28
+
29
+ def _as_dict(value: Any) -> Dict[str, Any]:
30
+ return dict(value) if isinstance(value, Mapping) else {}
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class OrderResult:
35
+ """Result of a v2 submission, with an optional service warning."""
36
+
37
+ order_id: int
38
+ message: str = ""
39
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
40
+
41
+ @classmethod
42
+ def from_response(cls, data: Dict[str, Any]) -> OrderResult:
43
+ order_id = int(data["orderId"])
44
+ message = data.get("message")
45
+ return cls(order_id, message if isinstance(message, str) else "", data)
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class OrderMeta:
50
+ """Metadata required to create an application.
51
+
52
+ Args:
53
+ region: applicant/service region code.
54
+ service_code: EPGU service code (``serviceCode`` on the wire).
55
+ target_code: service target code (``targetCode`` on the wire).
56
+ """
57
+
58
+ region: str
59
+ service_code: str
60
+ target_code: str
61
+
62
+ def __post_init__(self) -> None:
63
+ for name in ("service_code", "target_code"):
64
+ if not getattr(self, name):
65
+ raise ValueError(f"{name} must not be empty")
66
+ if re.fullmatch(r"\d{2,11}", self.region) is None:
67
+ raise ValueError("region must be a 2..11 digit OKATO code")
68
+
69
+ def to_payload(self) -> Dict[str, str]:
70
+ """Return the exact JSON object expected by EPGU."""
71
+ return {
72
+ "region": self.region,
73
+ "serviceCode": self.service_code,
74
+ "targetCode": self.target_code,
75
+ }
76
+
77
+
78
+ @dataclass
79
+ class OrderFile:
80
+ """A request or response attachment from application details."""
81
+
82
+ file_name: str
83
+ link: str
84
+ file_id: str = ""
85
+ file_size: Optional[int] = None
86
+ mime_type: str = ""
87
+ has_digital_signature: bool = False
88
+ file_type: str = ""
89
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
90
+
91
+ @property
92
+ def mnemonic(self) -> str:
93
+ """Filename encoded in a ``terrabyte://`` attachment link."""
94
+ parts = self._terrabyte_parts()
95
+ return parts[-2] if parts else ""
96
+
97
+ @property
98
+ def object_type(self) -> str:
99
+ """Object type encoded in a ``terrabyte://`` attachment link."""
100
+ parts = self._terrabyte_parts()
101
+ if parts:
102
+ return parts[-1]
103
+ # Compatibility with old responses containing an ordinary URL/path.
104
+ return self.link.rstrip("/").split("/")[-1] if self.link else ""
105
+
106
+ def _terrabyte_parts(self) -> List[str]:
107
+ parsed = urlparse(self.link)
108
+ if parsed.scheme.lower() != "terrabyte":
109
+ return []
110
+ parts = parsed.path.strip("/").split("/")
111
+ if len(parts) < 2 or not parts[-2] or not parts[-1]:
112
+ return []
113
+ return [unquote(part) for part in parts]
114
+
115
+ @classmethod
116
+ def from_dict(cls, data: Mapping[str, Any]) -> "OrderFile":
117
+ """Create an attachment model from a wire response object."""
118
+ return cls(
119
+ file_name=str(data.get("fileName") or ""),
120
+ link=str(data.get("link") or ""),
121
+ file_id=str(data.get("id") or ""),
122
+ file_size=_to_int(data.get("fileSize")),
123
+ mime_type=str(data.get("mimeType") or ""),
124
+ has_digital_signature=bool(data.get("hasDigitalSignature", False)),
125
+ file_type=str(data.get("type") or ""),
126
+ raw=dict(data),
127
+ )
128
+
129
+
130
+ @dataclass
131
+ class Order:
132
+ """Application details returned by ``POST /api/gusmev/order/{id}``.
133
+
134
+ ``code``, ``message`` and ``message_id`` come from the response envelope;
135
+ the remaining attributes are parsed from its JSON-encoded ``order`` field.
136
+ All request and response attachments are available through ``files`` and
137
+ separately through ``attachment_files`` / ``response_files``.
138
+ """
139
+
140
+ order_id: int
141
+ status_code: Optional[int] = None
142
+ status_name: Optional[str] = None
143
+ status_history_id: Optional[int] = None
144
+ cancel_allowed: bool = False
145
+ final_status: bool = False
146
+ closed: bool = False
147
+ updated: Optional[str] = None
148
+ code: Optional[str] = None
149
+ message: Optional[str] = None
150
+ message_id: Optional[str] = None
151
+ files: List[OrderFile] = field(default_factory=list)
152
+ attachment_files: List[OrderFile] = field(default_factory=list)
153
+ response_files: List[OrderFile] = field(default_factory=list)
154
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
155
+
156
+ @classmethod
157
+ def from_response(cls, data: Mapping[str, Any]) -> "Order":
158
+ """Parse an EPGU response, including its JSON-encoded ``order`` field.
159
+
160
+ Raises:
161
+ ValueError: if ``data`` or a non-empty ``order`` value has an
162
+ unsupported shape. Silently accepting malformed payloads
163
+ would otherwise turn real application IDs into ``0``.
164
+ """
165
+ if not isinstance(data, Mapping):
166
+ raise ValueError("order response must be a JSON object")
167
+
168
+ nested = data.get("order")
169
+ if isinstance(nested, str):
170
+ if not nested.strip():
171
+ order_obj: Dict[str, Any] = {}
172
+ else:
173
+ try:
174
+ decoded = json.loads(nested)
175
+ except json.JSONDecodeError as exc:
176
+ raise ValueError("the 'order' field is not valid JSON") from exc
177
+ if not isinstance(decoded, Mapping):
178
+ raise ValueError("the decoded 'order' field must be a JSON object")
179
+ order_obj = dict(decoded)
180
+ elif isinstance(nested, Mapping):
181
+ order_obj = dict(nested)
182
+ elif nested is None:
183
+ # Some mocks/older gateways return the details object directly.
184
+ order_obj = dict(data)
185
+ else:
186
+ raise ValueError("the 'order' field must be a JSON string or object")
187
+
188
+ attachment_files = [
189
+ OrderFile.from_dict(item)
190
+ for item in order_obj.get("orderAttachmentFiles", []) or []
191
+ if isinstance(item, Mapping)
192
+ ]
193
+ response_files = [
194
+ OrderFile.from_dict(item)
195
+ for item in order_obj.get("orderResponseFiles", []) or []
196
+ if isinstance(item, Mapping)
197
+ ]
198
+ current_status = _as_dict(order_obj.get("currentStatusHistory"))
199
+
200
+ order_id = _to_int(order_obj.get("id"))
201
+ if order_id is None:
202
+ order_id = _to_int(order_obj.get("orderId"))
203
+ if order_id is None:
204
+ order_id = _to_int(data.get("orderId"))
205
+ if order_id is None or order_id <= 0:
206
+ raise ValueError("order response does not contain a positive application id")
207
+
208
+ status_code = _to_int(order_obj.get("orderStatusId"))
209
+ if status_code is None:
210
+ status_code = _to_int(current_status.get("statusId"))
211
+
212
+ status_history_id = _to_int(order_obj.get("currentStatusHistoryId"))
213
+ if status_history_id is None:
214
+ status_history_id = _to_int(current_status.get("id"))
215
+
216
+ return cls(
217
+ order_id=order_id,
218
+ status_code=status_code,
219
+ status_name=(
220
+ str(order_obj.get("orderStatusName"))
221
+ if order_obj.get("orderStatusName") is not None
222
+ else (str(current_status.get("title")) if current_status.get("title") else None)
223
+ ),
224
+ status_history_id=status_history_id,
225
+ cancel_allowed=bool(current_status.get("cancelAllowed", False)),
226
+ final_status=bool(current_status.get("finalStatus", False)),
227
+ closed=bool(order_obj.get("closed", False)),
228
+ updated=str(order_obj.get("updated")) if order_obj.get("updated") else None,
229
+ code=str(data.get("code")) if data.get("code") is not None else None,
230
+ message=str(data.get("message")) if data.get("message") is not None else None,
231
+ message_id=(
232
+ str(data.get("messageId") or data.get("message_id"))
233
+ if data.get("messageId") or data.get("message_id")
234
+ else None
235
+ ),
236
+ files=[*attachment_files, *response_files],
237
+ attachment_files=attachment_files,
238
+ response_files=response_files,
239
+ raw=order_obj,
240
+ )
241
+
242
+ def file(self, file_name: str) -> Optional[OrderFile]:
243
+ """Return the first attachment with ``file_name``, or ``None``."""
244
+ return next((item for item in self.files if item.file_name == file_name), None)
245
+
246
+
247
+ @dataclass
248
+ class OrderStatus:
249
+ """Application status from ``getOrdersStatus`` / ``getUpdatedAfter``."""
250
+
251
+ order_id: int
252
+ status_code: Optional[int] = None
253
+ status_name: Optional[str] = None
254
+ updated: Optional[str] = None
255
+ search_status: Optional[str] = None
256
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
257
+
258
+ @classmethod
259
+ def from_dict(cls, data: Mapping[str, Any]) -> "OrderStatus":
260
+ """Parse both specification 1.14 and legacy flattened responses."""
261
+ status = _as_dict(data.get("status"))
262
+ status_code = _to_int(status.get("statusId"))
263
+ if status_code is None:
264
+ status_code = _to_int(data.get("orderStatusId"))
265
+ if status_code is None:
266
+ status_code = _to_int(data.get("statusId"))
267
+
268
+ status_name = status.get("statusName")
269
+ if status_name is None:
270
+ status_name = data.get("statusName")
271
+
272
+ updated = status.get("updated")
273
+ if updated is None:
274
+ updated = data.get("updated")
275
+
276
+ return cls(
277
+ order_id=_to_int(data.get("orderId")) or 0,
278
+ status_code=status_code,
279
+ status_name=str(status_name) if status_name is not None else None,
280
+ updated=str(updated) if updated is not None else None,
281
+ search_status=(
282
+ str(data.get("orderSearchStatus"))
283
+ if data.get("orderSearchStatus") is not None
284
+ else None
285
+ ),
286
+ raw=dict(data),
287
+ )
288
+
289
+
290
+ @dataclass
291
+ class OrdersPage:
292
+ """Paginated status response while remaining convenient to iterate/index."""
293
+
294
+ items: List[OrderStatus] = field(default_factory=list)
295
+ count: int = 0
296
+ total_count: int = 0
297
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
298
+
299
+ @property
300
+ def content(self) -> List[OrderStatus]:
301
+ """Alias matching the EPGU wire field name."""
302
+ return self.items
303
+
304
+ def __len__(self) -> int:
305
+ return len(self.items)
306
+
307
+ def __iter__(self) -> Iterator[OrderStatus]:
308
+ return iter(self.items)
309
+
310
+ @overload
311
+ def __getitem__(self, index: int) -> OrderStatus: ...
312
+
313
+ @overload
314
+ def __getitem__(self, index: slice) -> List[OrderStatus]: ...
315
+
316
+ def __getitem__(self, index: Union[int, slice]) -> Union[OrderStatus, List[OrderStatus]]:
317
+ return self.items[index]
318
+
319
+ @classmethod
320
+ def from_response(cls, data: Any) -> "OrdersPage":
321
+ """Parse the documented envelope plus known legacy list envelopes."""
322
+ items_data: Any
323
+ if isinstance(data, list):
324
+ items_data = data
325
+ raw: Dict[str, Any] = {"content": data}
326
+ count = total_count = len(data)
327
+ elif isinstance(data, Mapping):
328
+ raw = dict(data)
329
+ items_data = data.get("content")
330
+ if not isinstance(items_data, list):
331
+ for key in ("orders", "items", "data"):
332
+ if isinstance(data.get(key), list):
333
+ items_data = data[key]
334
+ break
335
+ if not isinstance(items_data, list):
336
+ items_data = []
337
+ parsed_count = _to_int(data.get("count"))
338
+ parsed_total_count = _to_int(data.get("totalCount"))
339
+ count = len(items_data) if parsed_count is None else parsed_count
340
+ total_count = count if parsed_total_count is None else parsed_total_count
341
+ else:
342
+ raise ValueError("status response must be a JSON object or array")
343
+
344
+ items = [OrderStatus.from_dict(item) for item in items_data if isinstance(item, Mapping)]
345
+ return cls(items=items, count=count, total_count=total_count, raw=raw)
346
+
347
+
348
+ @dataclass
349
+ class DictionaryItem:
350
+ """One NSI dictionary item from ``/api/nsi/v1/dictionary/{code}``."""
351
+
352
+ value: str
353
+ title: str
354
+ parent_value: Optional[str] = None
355
+ is_leaf: bool = False
356
+ children: List[Dict[str, Any]] = field(default_factory=list)
357
+ attributes: List[Dict[str, Any]] = field(default_factory=list)
358
+ attribute_values: Dict[str, Any] = field(default_factory=dict)
359
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
360
+
361
+ @classmethod
362
+ def from_dict(cls, data: Mapping[str, Any]) -> "DictionaryItem":
363
+ """Построить типизированный элемент из JSON-объекта НСИ."""
364
+ return cls(
365
+ value=str(data.get("value") or ""),
366
+ title=str(data.get("title") or ""),
367
+ parent_value=(
368
+ str(data.get("parentValue")) if data.get("parentValue") is not None else None
369
+ ),
370
+ is_leaf=bool(data.get("isLeaf", False)),
371
+ children=[
372
+ dict(item) for item in data.get("children", []) or [] if isinstance(item, Mapping)
373
+ ],
374
+ attributes=[
375
+ dict(item) for item in data.get("attributes", []) or [] if isinstance(item, Mapping)
376
+ ],
377
+ attribute_values=_as_dict(data.get("attributeValues")),
378
+ raw=dict(data),
379
+ )
380
+
381
+
382
+ @dataclass
383
+ class DictionaryResult(Sequence[DictionaryItem]):
384
+ """Typed NSI result with operation status and total item count."""
385
+
386
+ items: List[DictionaryItem] = field(default_factory=list)
387
+ total: int = 0
388
+ error_code: int = 0
389
+ error_message: str = ""
390
+ field_errors: List[Dict[str, Any]] = field(default_factory=list)
391
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
392
+
393
+ def __len__(self) -> int:
394
+ return len(self.items)
395
+
396
+ def __iter__(self) -> Iterator[DictionaryItem]:
397
+ return iter(self.items)
398
+
399
+ @overload
400
+ def __getitem__(self, index: int) -> DictionaryItem: ...
401
+
402
+ @overload
403
+ def __getitem__(self, index: slice) -> List[DictionaryItem]: ...
404
+
405
+ def __getitem__(self, index: Union[int, slice]) -> Union[DictionaryItem, List[DictionaryItem]]:
406
+ return self.items[index]
407
+
408
+ @classmethod
409
+ def from_response(cls, data: Any) -> "DictionaryResult":
410
+ """Разобрать документированный конверт ответа справочника НСИ."""
411
+ if not isinstance(data, Mapping):
412
+ raise ValueError("dictionary response must be a JSON object")
413
+ error = _as_dict(data.get("error"))
414
+ item_values = data.get("items")
415
+ if item_values is None:
416
+ item_values = []
417
+ if not isinstance(item_values, list):
418
+ raise ValueError("dictionary 'items' field must be an array")
419
+ field_values = data.get("fieldErrors")
420
+ if field_values is None:
421
+ field_values = []
422
+ if not isinstance(field_values, list):
423
+ raise ValueError("dictionary 'fieldErrors' field must be an array")
424
+ return cls(
425
+ items=[
426
+ DictionaryItem.from_dict(item) for item in item_values if isinstance(item, Mapping)
427
+ ],
428
+ total=_to_int(data.get("total")) or 0,
429
+ error_code=_to_int(error.get("code")) or 0,
430
+ error_message=str(error.get("message") or ""),
431
+ field_errors=[dict(item) for item in field_values if isinstance(item, Mapping)],
432
+ raw=dict(data),
433
+ )
epgu/py.typed ADDED
File without changes
@@ -0,0 +1,20 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2025 yellow444 <yellow444@gmail.com>
3
+ """Высокоуровневые сценарии поверх :class:`~epgu.client.EpguClient`.
4
+
5
+ Здесь собран типовой жизненный цикл подачи заявления, чтобы прикладной код
6
+ не повторял одну и ту же последовательность «создать заявление затем собрать архив ->
7
+ загрузить затем дождаться статуса».
8
+ """
9
+
10
+ from . import fssp, goskey
11
+ from .submit import GoskeySubmitResult, SubmitResult, submit_application, submit_goskey
12
+
13
+ __all__ = [
14
+ "fssp",
15
+ "goskey",
16
+ "submit_application",
17
+ "submit_goskey",
18
+ "SubmitResult",
19
+ "GoskeySubmitResult",
20
+ ]