Pyiiko 0.4.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.
Pyiiko/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """pyiiko — Python library for iiko ERP API."""
2
+ from .exceptions import IikoAPIError, IikoAuthError, IikoError
3
+ from .iiko_web import IikoWeb
4
+ from .server import IikoServer
5
+ from .transport import Transport
6
+
7
+ __version__ = "0.4.0"
8
+ __all__ = [
9
+ "IikoServer",
10
+ "Transport",
11
+ "IikoWeb",
12
+ "IikoError",
13
+ "IikoAuthError",
14
+ "IikoAPIError",
15
+ ]
Pyiiko/_base.py ADDED
@@ -0,0 +1,83 @@
1
+ """Shared HTTP session, retry logic, and error handling for iiko API clients."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ from typing import Any
6
+
7
+ import requests
8
+ from requests.adapters import HTTPAdapter
9
+ from urllib3.util.retry import Retry
10
+
11
+ from .exceptions import IikoAPIError
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ DEFAULT_TIMEOUT = 10
16
+ _RETRY_TOTAL = 3
17
+ _RETRY_BACKOFF = 0.5
18
+ _RETRY_STATUS_CODES = (500, 502, 503, 504)
19
+
20
+
21
+ class BaseIikoClient:
22
+ """Base class for all iiko API clients.
23
+
24
+ Provides a shared requests.Session with automatic retries on transient
25
+ server errors, structured logging, and uniform HTTP error handling.
26
+
27
+ Supports use as a context manager::
28
+
29
+ with IikoServer(ip=..., login=..., password=...) as client:
30
+ data = client.departments()
31
+ """
32
+
33
+ def __init__(self, base_url: str, timeout: int = DEFAULT_TIMEOUT) -> None:
34
+ self._base_url = base_url.rstrip("/")
35
+ self._timeout = timeout
36
+ self._session = self._build_session()
37
+
38
+ @staticmethod
39
+ def _build_session() -> requests.Session:
40
+ session = requests.Session()
41
+ retry = Retry(
42
+ total=_RETRY_TOTAL,
43
+ backoff_factor=_RETRY_BACKOFF,
44
+ status_forcelist=list(_RETRY_STATUS_CODES),
45
+ allowed_methods=["GET", "POST"],
46
+ raise_on_status=False,
47
+ )
48
+ adapter = HTTPAdapter(max_retries=retry)
49
+ session.mount("https://", adapter)
50
+ session.mount("http://", adapter)
51
+ return session
52
+
53
+ def _request(self, method: str, path: str, **kwargs: Any) -> requests.Response:
54
+ url = f"{self._base_url}/{path.lstrip('/')}"
55
+ logger.debug("%s %s", method.upper(), url)
56
+ try:
57
+ response = self._session.request(
58
+ method, url, timeout=self._timeout, **kwargs
59
+ )
60
+ response.raise_for_status()
61
+ return response
62
+ except requests.HTTPError as exc:
63
+ status = exc.response.status_code if exc.response is not None else None
64
+ raise IikoAPIError(
65
+ f"HTTP {status} from {url}",
66
+ status_code=status,
67
+ ) from exc
68
+
69
+ def _get(self, path: str, **kwargs: Any) -> requests.Response:
70
+ return self._request("GET", path, **kwargs)
71
+
72
+ def _post(self, path: str, **kwargs: Any) -> requests.Response:
73
+ return self._request("POST", path, **kwargs)
74
+
75
+ def close(self) -> None:
76
+ """Close the underlying HTTP session."""
77
+ self._session.close()
78
+
79
+ def __enter__(self) -> BaseIikoClient:
80
+ return self
81
+
82
+ def __exit__(self, *args: Any) -> None:
83
+ self.close()
@@ -0,0 +1,288 @@
1
+ """Nomenclature v2 mixin for IikoServer — keeps server.py under 800 lines."""
2
+ from __future__ import annotations
3
+
4
+ from typing import TYPE_CHECKING, Any
5
+
6
+ if TYPE_CHECKING:
7
+ import requests
8
+
9
+
10
+ class _NomenclatureMixin:
11
+ """Mixin providing v2 nomenclature endpoints for IikoServer.
12
+
13
+ Endpoints are under ``/api/v2/entities/products/...`` and require the
14
+ user to have the **B_EN** ("Редактирование номенклатурных справочников")
15
+ permission.
16
+ """
17
+
18
+ if TYPE_CHECKING:
19
+ def _get(self, path: str, **kwargs: Any) -> requests.Response: ...
20
+ def _post(self, path: str, **kwargs: Any) -> requests.Response: ...
21
+
22
+ def _key(self, **extra: Any) -> dict[str, Any]: # satisfied by IikoServer
23
+ raise NotImplementedError
24
+
25
+ # ------------------------------------------------------------------
26
+ # Элементы номенклатуры
27
+ # ------------------------------------------------------------------
28
+
29
+ def nomenclature_list(
30
+ self,
31
+ include_deleted: bool = False,
32
+ revision_from: int = -1,
33
+ ids: list[str] | None = None,
34
+ nums: list[str] | None = None,
35
+ codes: list[str] | None = None,
36
+ types: list[str] | None = None,
37
+ category_ids: list[str] | None = None,
38
+ parent_ids: list[str] | None = None,
39
+ ) -> Any:
40
+ """Return the list of nomenclature elements (v2 API).
41
+
42
+ :param include_deleted: Include deleted items (default ``False``).
43
+ :param revision_from: Return only items with revision > this value
44
+ (default ``-1`` — no revision filter).
45
+ :param ids: Filter by element UUIDs (optional).
46
+ :param nums: Filter by article numbers (optional).
47
+ :param codes: Filter by fast-search codes (optional).
48
+ :param types: Filter by product types, e.g. ``["GOODS", "DISH"]``
49
+ (optional).
50
+ :param category_ids: Filter by user-category UUIDs (optional).
51
+ :param parent_ids: Filter by parent-group UUIDs (optional).
52
+ :returns: Parsed JSON list of ProductDto.
53
+ """
54
+ params: list[tuple[str, Any]] = [
55
+ ("key", self._key()["key"]),
56
+ ("includeDeleted", str(include_deleted).lower()),
57
+ ("revisionFrom", revision_from),
58
+ ]
59
+ for uid in ids or []:
60
+ params.append(("id", uid))
61
+ for num in nums or []:
62
+ params.append(("num", num))
63
+ for code in codes or []:
64
+ params.append(("code", code))
65
+ for t in types or []:
66
+ params.append(("type", t))
67
+ for cid in category_ids or []:
68
+ params.append(("categoryId", cid))
69
+ for pid in parent_ids or []:
70
+ params.append(("parentId", pid))
71
+ return self._get(
72
+ "api/v2/entities/products/list",
73
+ params=params,
74
+ ).json()
75
+
76
+ def nomenclature_save(
77
+ self,
78
+ payload: dict,
79
+ generate_nomenclature_code: bool = True,
80
+ generate_fast_code: bool = True,
81
+ ) -> Any:
82
+ """Create (import) a new nomenclature element.
83
+
84
+ :param payload: Product object dict. Required fields: ``name``,
85
+ ``type``, ``mainUnit``.
86
+ :param generate_nomenclature_code: Auto-generate article number
87
+ (default ``True``).
88
+ :param generate_fast_code: Auto-generate fast-search code
89
+ (default ``True``).
90
+ :returns: Parsed JSON with ``result``, ``errors``, ``response``.
91
+ """
92
+ return self._post(
93
+ "api/v2/entities/products/save",
94
+ params=self._key(
95
+ generateNomenclatureCode=str(generate_nomenclature_code).lower(),
96
+ generateFastCode=str(generate_fast_code).lower(),
97
+ ),
98
+ json=payload,
99
+ ).json()
100
+
101
+ def nomenclature_update(self, payload: dict) -> Any:
102
+ """Edit an existing nomenclature element.
103
+
104
+ :param payload: Product dict with ``id`` field and all fields to
105
+ update.
106
+ :returns: Parsed JSON with ``result``, ``errors``, ``response``.
107
+ """
108
+ return self._post(
109
+ "api/v2/entities/products/update",
110
+ params={"key": self._key()["key"]},
111
+ json=payload,
112
+ ).json()
113
+
114
+ def nomenclature_delete(self, ids: list[str]) -> Any:
115
+ """Delete nomenclature elements by UUID list.
116
+
117
+ :param ids: List of element UUIDs to delete.
118
+ :returns: Parsed JSON operation result.
119
+ """
120
+ return self._post(
121
+ "api/v2/entities/products/delete",
122
+ params={"key": self._key()["key"]},
123
+ json=ids,
124
+ ).json()
125
+
126
+ def nomenclature_restore(self, ids: list[str]) -> Any:
127
+ """Restore previously deleted nomenclature elements.
128
+
129
+ :param ids: List of element UUIDs to restore.
130
+ :returns: Parsed JSON operation result.
131
+ """
132
+ return self._post(
133
+ "api/v2/entities/products/restore",
134
+ params={"key": self._key()["key"]},
135
+ json=ids,
136
+ ).json()
137
+
138
+ # ------------------------------------------------------------------
139
+ # Номенклатурные группы
140
+ # ------------------------------------------------------------------
141
+
142
+ def nomenclature_group_list(
143
+ self,
144
+ include_deleted: bool = False,
145
+ revision_from: int = -1,
146
+ ids: list[str] | None = None,
147
+ parent_ids: list[str] | None = None,
148
+ ) -> Any:
149
+ """Return the list of nomenclature groups (v2 API).
150
+
151
+ :param include_deleted: Include deleted groups (default ``False``).
152
+ :param revision_from: Revision filter (default ``-1``).
153
+ :param ids: Filter by group UUIDs (optional).
154
+ :param parent_ids: Filter by parent-group UUIDs (optional).
155
+ :returns: Parsed JSON list of ProductGroupDto.
156
+ """
157
+ params: list[tuple[str, Any]] = [
158
+ ("key", self._key()["key"]),
159
+ ("includeDeleted", str(include_deleted).lower()),
160
+ ("revisionFrom", revision_from),
161
+ ]
162
+ for uid in ids or []:
163
+ params.append(("id", uid))
164
+ for pid in parent_ids or []:
165
+ params.append(("parentId", pid))
166
+ return self._get(
167
+ "api/v2/entities/products/group/list",
168
+ params=params,
169
+ ).json()
170
+
171
+ def nomenclature_group_save(self, payload: dict) -> Any:
172
+ """Create (import) a new nomenclature group.
173
+
174
+ :param payload: Group object dict. Required field: ``name``.
175
+ :returns: Parsed JSON with ``result``, ``errors``, ``response``.
176
+ """
177
+ return self._post(
178
+ "api/v2/entities/products/group/save",
179
+ params={"key": self._key()["key"]},
180
+ json=payload,
181
+ ).json()
182
+
183
+ def nomenclature_group_update(self, payload: dict) -> Any:
184
+ """Edit an existing nomenclature group.
185
+
186
+ :param payload: Group dict with ``id`` and fields to update.
187
+ :returns: Parsed JSON with ``result``, ``errors``, ``response``.
188
+ """
189
+ return self._post(
190
+ "api/v2/entities/products/group/update",
191
+ params={"key": self._key()["key"]},
192
+ json=payload,
193
+ ).json()
194
+
195
+ def nomenclature_group_delete(self, ids: list[str]) -> Any:
196
+ """Delete nomenclature groups by UUID list.
197
+
198
+ :param ids: List of group UUIDs to delete.
199
+ :returns: Parsed JSON operation result.
200
+ """
201
+ return self._post(
202
+ "api/v2/entities/products/group/delete",
203
+ params={"key": self._key()["key"]},
204
+ json=ids,
205
+ ).json()
206
+
207
+ def nomenclature_group_restore(self, ids: list[str]) -> Any:
208
+ """Restore previously deleted nomenclature groups.
209
+
210
+ :param ids: List of group UUIDs to restore.
211
+ :returns: Parsed JSON operation result.
212
+ """
213
+ return self._post(
214
+ "api/v2/entities/products/group/restore",
215
+ params={"key": self._key()["key"]},
216
+ json=ids,
217
+ ).json()
218
+
219
+ # ------------------------------------------------------------------
220
+ # Пользовательские категории
221
+ # ------------------------------------------------------------------
222
+
223
+ def nomenclature_category_list(
224
+ self,
225
+ include_deleted: bool = False,
226
+ revision_from: int = -1,
227
+ ) -> Any:
228
+ """Return the list of user-defined product categories (v2 API).
229
+
230
+ :param include_deleted: Include deleted categories (default ``False``).
231
+ :param revision_from: Revision filter (default ``-1``).
232
+ :returns: Parsed JSON list of EntityDto.
233
+ """
234
+ return self._get(
235
+ "api/v2/entities/products/category/list",
236
+ params=self._key(
237
+ includeDeleted=str(include_deleted).lower(),
238
+ revisionFrom=revision_from,
239
+ ),
240
+ ).json()
241
+
242
+ def nomenclature_category_save(self, payload: dict) -> Any:
243
+ """Create a new user-defined product category.
244
+
245
+ :param payload: Category dict. Required field: ``name``.
246
+ :returns: Parsed JSON with ``result``, ``errors``, ``response``.
247
+ """
248
+ return self._post(
249
+ "api/v2/entities/products/category/save",
250
+ params={"key": self._key()["key"]},
251
+ json=payload,
252
+ ).json()
253
+
254
+ def nomenclature_category_update(self, payload: dict) -> Any:
255
+ """Edit an existing user-defined product category.
256
+
257
+ :param payload: Category dict with ``id`` and fields to update.
258
+ :returns: Parsed JSON with ``result``, ``errors``, ``response``.
259
+ """
260
+ return self._post(
261
+ "api/v2/entities/products/category/update",
262
+ params={"key": self._key()["key"]},
263
+ json=payload,
264
+ ).json()
265
+
266
+ def nomenclature_category_delete(self, ids: list[str]) -> Any:
267
+ """Delete user-defined product categories by UUID list.
268
+
269
+ :param ids: List of category UUIDs to delete.
270
+ :returns: Parsed JSON operation result.
271
+ """
272
+ return self._post(
273
+ "api/v2/entities/products/category/delete",
274
+ params={"key": self._key()["key"]},
275
+ json=ids,
276
+ ).json()
277
+
278
+ def nomenclature_category_restore(self, ids: list[str]) -> Any:
279
+ """Restore previously deleted user-defined product categories.
280
+
281
+ :param ids: List of category UUIDs to restore.
282
+ :returns: Parsed JSON operation result.
283
+ """
284
+ return self._post(
285
+ "api/v2/entities/products/category/restore",
286
+ params={"key": self._key()["key"]},
287
+ json=ids,
288
+ ).json()