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/server.py ADDED
@@ -0,0 +1,637 @@
1
+ """iiko Server API client (on-premise)."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ from io import StringIO
6
+ from typing import Any
7
+
8
+ from lxml import etree
9
+
10
+ from ._base import DEFAULT_TIMEOUT, BaseIikoClient
11
+ from ._server_nomenclature import _NomenclatureMixin
12
+ from .exceptions import IikoAuthError
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class IikoServer(_NomenclatureMixin, BaseIikoClient):
18
+ """Client for the iiko Server REST API (on-premise installations).
19
+
20
+ Authenticates on construction and stores the token for subsequent calls.
21
+ Pass a pre-existing *token* to skip the auth round-trip::
22
+
23
+ server = IikoServer(ip="https://host:443", login="user", password="sha1hash")
24
+ print(server.version())
25
+
26
+ One token occupies one license slot. Call :meth:`quit_token` when done to
27
+ free the slot, or use the client as a context manager::
28
+
29
+ with IikoServer(...) as server:
30
+ data = server.departments()
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ ip: str | None = None,
36
+ login: str | None = None,
37
+ password: str | None = None,
38
+ token: str | None = None,
39
+ timeout: int = DEFAULT_TIMEOUT,
40
+ ) -> None:
41
+ base_url = (ip or "").rstrip("/") + "/resto/"
42
+ super().__init__(base_url, timeout)
43
+ self.login = login
44
+ self.password = password
45
+ self._token: str = token or self.get_token()
46
+
47
+ # ------------------------------------------------------------------
48
+ # Auth
49
+ # ------------------------------------------------------------------
50
+
51
+ def _key(self, **extra: Any) -> dict[str, Any]:
52
+ """Return params dict containing the auth key plus any extra params."""
53
+ params: dict[str, Any] = {"key": self._token}
54
+ params.update({k: v for k, v in extra.items() if v is not None})
55
+ return params
56
+
57
+ def token(self) -> str:
58
+ """Return the current authentication token."""
59
+ return self._token
60
+
61
+ def get_token(self) -> str:
62
+ """Fetch a new authentication token from the server.
63
+
64
+ .. note::
65
+
66
+ Each token occupies one license slot. If you have a single
67
+ license and a live token, requesting a new one will fail.
68
+ Call :meth:`quit_token` to release the slot first.
69
+ """
70
+ response = self._get(
71
+ "api/auth",
72
+ params={"login": self.login, "pass": self.password},
73
+ )
74
+ token = response.text.strip()
75
+ if not token:
76
+ raise IikoAuthError("Server returned an empty token")
77
+ return token
78
+
79
+ def quit_token(self) -> None:
80
+ """Destroy the current token and release the license slot."""
81
+ self._get("api/logout", params={"key": self._token})
82
+ logger.info("Token destroyed: %s", self._token)
83
+
84
+ # ------------------------------------------------------------------
85
+ # Server info
86
+ # ------------------------------------------------------------------
87
+
88
+ def version(self) -> str:
89
+ """Return the iiko server version string."""
90
+ text = self._get(
91
+ "get_server_info.jsp", params={"encoding": "UTF-8"}
92
+ ).text
93
+ tree = etree.parse(StringIO(text))
94
+ nodes: list[Any] = tree.xpath(r"//version/text()") # type: ignore[assignment]
95
+ return "".join(str(x) for x in nodes)
96
+
97
+ def server_info(self) -> Any:
98
+ """Return server info and license status as a parsed JSON dict."""
99
+ return self._get(
100
+ "get_server_info.jsp", params={"encoding": "UTF-8"}
101
+ ).json()
102
+
103
+ # ------------------------------------------------------------------
104
+ # Корпорации
105
+ # ------------------------------------------------------------------
106
+
107
+ def departments(self) -> bytes:
108
+ """Return the department hierarchy (corporateItemDto).
109
+
110
+ .. csv-table:: Department types
111
+ :header: "Code", "Name"
112
+ :widths: 20, 30
113
+
114
+ "CORPORATION", Corporation
115
+ "JURPERSON", Legal entity
116
+ "ORGDEVELOPMENT", Structural unit
117
+ "DEPARTMENT", Trading enterprise
118
+ "MANUFACTURE", Production
119
+ "CENTRALSTORE", Central warehouse
120
+ "CENTRALOFFICE", Central office
121
+ "SALEPOINT", Point of sale
122
+ "STORE", Warehouse
123
+ """
124
+ return self._get("api/corporation/departments", params=self._key()).content
125
+
126
+ def stores(self) -> str:
127
+ """Return all warehouses as corporateItemDto XML."""
128
+ return self._get("api/corporation/stores", params=self._key()).text
129
+
130
+ def groups(self) -> bytes:
131
+ """Return groups, branches, and points of sale (groupDto)."""
132
+ return self._get("api/corporation/groups", params=self._key()).content
133
+
134
+ def terminals(self) -> bytes:
135
+ """Return all terminals (terminalDto)."""
136
+ return self._get("api/corporation/terminals", params=self._key()).content
137
+
138
+ def departments_find(self, code: str) -> bytes:
139
+ """Search for a department by code (regex).
140
+
141
+ :param code: Department code regex pattern.
142
+ :returns: corporateItemDto structure.
143
+ """
144
+ return self._get(
145
+ "api/corporation/departments/search",
146
+ params=self._key(departmentCode=code),
147
+ ).content
148
+
149
+ def stores_find(self, code: str) -> bytes:
150
+ """Search for a warehouse by code (regex).
151
+
152
+ :param code: Warehouse code regex pattern.
153
+ :returns: corporateItemDto structure.
154
+ """
155
+ return self._get(
156
+ "api/corporation/stores/search",
157
+ params=self._key(storeCode=code),
158
+ ).content
159
+
160
+ def groups_search(self, **kwargs: Any) -> bytes:
161
+ """Search for branch groups.
162
+
163
+ :param name: Group name regex.
164
+ :param departmentId: Department GUID.
165
+ """
166
+ return self._get(
167
+ "api/corporation/groups/search",
168
+ params=self._key(**kwargs),
169
+ ).content
170
+
171
+ def terminals_search(self, anonymous: bool = False, **kwargs: Any) -> bytes:
172
+ """Search for terminals.
173
+
174
+ :param anonymous: Front terminals have ``anonymous=False``; back-office
175
+ and system terminals have ``anonymous=True``.
176
+ :param name: Terminal name regex (optional).
177
+ :param computerName: Computer name regex (optional).
178
+ :returns: List of terminalDto.
179
+ """
180
+ return self._get(
181
+ "api/corporation/terminal/search",
182
+ params=self._key(anonymous=str(anonymous).lower(), **kwargs),
183
+ ).content
184
+
185
+ # ------------------------------------------------------------------
186
+ # Работники
187
+ # ------------------------------------------------------------------
188
+
189
+ def employees(self) -> bytes:
190
+ """Return all employees."""
191
+ return self._get("api/employees", params=self._key()).content
192
+
193
+ # ------------------------------------------------------------------
194
+ # События
195
+ # ------------------------------------------------------------------
196
+
197
+ def events(self, **kwargs: Any) -> bytes:
198
+ """Return a list of events.
199
+
200
+ :param from_time: Start time ISO ``yyyy-MM-ddTHH:mm:ss.SSS`` (optional).
201
+ :param to_time: End time ISO (exclusive, optional).
202
+ :param from_rev: Start revision number (optional).
203
+ :returns: eventsList XML.
204
+ """
205
+ return self._get("api/events", params=self._key(**kwargs)).content
206
+
207
+ def events_filter(self, body: str | bytes) -> bytes:
208
+ """Return events filtered by event type and order number.
209
+
210
+ :param body: XML filter body (application/xml).
211
+
212
+ .. code-block:: xml
213
+
214
+ <eventsRequestData>
215
+ <events>
216
+ <event>orderPaid</event>
217
+ </events>
218
+ <orderNums>
219
+ <orderNum>175658</orderNum>
220
+ </orderNums>
221
+ </eventsRequestData>
222
+
223
+ :returns: groupsList XML.
224
+ """
225
+ return self._post(
226
+ "api/events",
227
+ data=body,
228
+ params={"key": self._token},
229
+ ).content
230
+
231
+ def events_meta(self) -> bytes:
232
+ """Return event metadata tree."""
233
+ return self._get("api/events/metadata", params=self._key()).content
234
+
235
+ # ------------------------------------------------------------------
236
+ # Продукты
237
+ # ------------------------------------------------------------------
238
+
239
+ def products(self, includeDeleted: bool = True) -> bytes:
240
+ """Return the product catalog.
241
+
242
+ .. csv-table:: Product element types
243
+ :header: "Code", "Name"
244
+ :widths: 15, 20
245
+
246
+ "GOODS", Item
247
+ "DISH", Dish
248
+ "PREPARED", Preparation
249
+ "SERVICE", Service
250
+ "MODIFIER", Modifier
251
+
252
+ :param includeDeleted: Include deleted items (default ``True``).
253
+ """
254
+ return self._get(
255
+ "api/products",
256
+ params=self._key(includeDeleted=str(includeDeleted).lower()),
257
+ ).content
258
+
259
+ def products_find(self, **kwargs: Any) -> bytes:
260
+ """Search the product catalog.
261
+
262
+ :param includeDeleted: Include deleted items.
263
+ :param name: Name regex (optional).
264
+ :param code: Quick-dial code regex (optional).
265
+ :param mainUnit: Base unit of measure regex (optional).
266
+ :param num: Article number regex (optional).
267
+ :param cookingPlaceType: Cooking place type regex (optional).
268
+ :param productGroupType: Parent group type regex (optional).
269
+ :param productType: Product type regex (optional).
270
+ """
271
+ return self._get(
272
+ "api/products/search/",
273
+ params=self._key(**kwargs),
274
+ ).content
275
+
276
+ # ------------------------------------------------------------------
277
+ # Поставщики
278
+ # ------------------------------------------------------------------
279
+
280
+ def suppliers(self) -> bytes:
281
+ """Return all suppliers (employees structure)."""
282
+ return self._get("api/suppliers", params=self._key()).content
283
+
284
+ def suppliers_find(self, name: str = "", code: str = "") -> bytes:
285
+ """Search suppliers by name and/or code regex.
286
+
287
+ :param name: Supplier name regex (optional).
288
+ :param code: Supplier code regex (optional).
289
+ :returns: employees XML.
290
+ """
291
+ return self._get(
292
+ "api/suppliers",
293
+ params=self._key(name=name or None, code=code or None),
294
+ ).content
295
+
296
+ def suppliers_price(self, code: str, date: str | None = None) -> bytes:
297
+ """Return the supplier price list.
298
+
299
+ :param code: Supplier GUID.
300
+ :param date: Price list start date ``DD.MM.YYYY`` (optional,
301
+ defaults to latest).
302
+ """
303
+ return self._get(
304
+ f"api/suppliers/{code}/pricelist",
305
+ params=self._key(date=date),
306
+ ).content
307
+
308
+ # ------------------------------------------------------------------
309
+ # Отчеты
310
+ # ------------------------------------------------------------------
311
+
312
+ def olap(
313
+ self,
314
+ report: str | None = None,
315
+ data_from: str | None = None,
316
+ data_to: str | None = None,
317
+ **kwargs: Any,
318
+ ) -> str:
319
+ """Return an OLAP report.
320
+
321
+ :param report: Report type — ``SALES``, ``TRANSACTIONS``,
322
+ ``DELIVERIES``, or ``STOCK``.
323
+ :param data_from: Start date-time ISO.
324
+ :param data_to: End date-time ISO.
325
+ :param groupRow: Row grouping fields, e.g. ``WaiterName``.
326
+ :param groupCol: Column grouping fields.
327
+ :param agr: Aggregation fields.
328
+ :returns: Report XML/text.
329
+ """
330
+ return self._get(
331
+ "api/reports/olap",
332
+ params={
333
+ "key": self._token,
334
+ "report": report,
335
+ "from": data_from,
336
+ "to": data_to,
337
+ **{k: v for k, v in kwargs.items() if v is not None},
338
+ },
339
+ ).text
340
+
341
+ def store_operation(
342
+ self,
343
+ stores: str | None = None,
344
+ documentTypes: str | None = None,
345
+ productDetalization: bool = True,
346
+ showCostCorrections: bool = True,
347
+ presetId: str | None = None,
348
+ **kwargs: Any,
349
+ ) -> bytes:
350
+ """Return a warehouse operations report.
351
+
352
+ :param stores: Warehouse GUID filter (optional, all if omitted).
353
+ :param documentTypes: Document type filter (optional, all if omitted).
354
+ :param productDetalization: Include per-product rows (default ``True``).
355
+ :param showCostCorrections: Include cost corrections (default ``True``).
356
+ :param presetId: Preset report GUID (optional).
357
+ """
358
+ return self._get(
359
+ "api/reports/storeOperations",
360
+ params=self._key(
361
+ stores=stores,
362
+ documentTypes=documentTypes,
363
+ productDetalization=productDetalization,
364
+ showCostCorrections=showCostCorrections,
365
+ presetId=presetId,
366
+ **kwargs,
367
+ ),
368
+ ).content
369
+
370
+ def store_presets(self) -> bytes:
371
+ """Return warehouse report presets (storeReportPresets)."""
372
+ return self._get("api/reports/storeReportPresets", params=self._key()).content
373
+
374
+ def product_expense(self, departament: str, **kwargs: Any) -> bytes:
375
+ """Return a product consumption by sales report.
376
+
377
+ :param departament: Department GUID.
378
+ :param dateFrom: Start date ``DD.MM.YYYY``.
379
+ :param dateTo: End date ``DD.MM.YYYY``.
380
+ :param hourFrom: Start hour (default -1, full day).
381
+ :param hourTo: End hour (default -1, full day).
382
+ :returns: dayDishValue XML.
383
+ """
384
+ return self._get(
385
+ "api/reports/productExpense",
386
+ params=self._key(department=departament, **kwargs),
387
+ ).content
388
+
389
+ def sales(
390
+ self,
391
+ departament: str,
392
+ dishDetails: bool = False,
393
+ allRevenue: bool = True,
394
+ **kwargs: Any,
395
+ ) -> bytes:
396
+ """Return a revenue report.
397
+
398
+ :param departament: Department GUID.
399
+ :param dateFrom: Start date ``DD.MM.YYYY``.
400
+ :param dateTo: End date ``DD.MM.YYYY``.
401
+ :param dishDetails: Include per-dish breakdown (default ``False``).
402
+ :param allRevenue: All payment types if ``True``, revenue only if
403
+ ``False`` (default ``True``).
404
+ :returns: dayDishValue XML.
405
+ """
406
+ return self._get(
407
+ "api/reports/sales",
408
+ params=self._key(
409
+ department=departament,
410
+ dishDetails=dishDetails,
411
+ allRevenue=allRevenue,
412
+ **kwargs,
413
+ ),
414
+ ).content
415
+
416
+ def mounthly_plan(self, departament: str, **kwargs: Any) -> bytes:
417
+ """Return the monthly revenue plan.
418
+
419
+ :param departament: Department GUID.
420
+ :param dateFrom: Start date ``DD.MM.YYYY``.
421
+ :param dateTo: End date ``DD.MM.YYYY``.
422
+ :returns: budgetPlanItemDtoes XML.
423
+ """
424
+ return self._get(
425
+ "api/reports/monthlyIncomePlan",
426
+ params=self._key(department=departament, **kwargs),
427
+ ).content
428
+
429
+ def ingredient_entry(
430
+ self,
431
+ departament: str,
432
+ includeSubtree: bool = False,
433
+ **kwargs: Any,
434
+ ) -> bytes:
435
+ """Return an ingredient-in-dish report.
436
+
437
+ :param departament: Department GUID.
438
+ :param includeSubtree: Include sub-tree rows (default ``False``).
439
+ :param dateFrom: Start date ``DD.MM.YYYY``.
440
+ :param dateTo: End date ``DD.MM.YYYY``.
441
+ :param productArticle: Product article (search priority over product).
442
+ :returns: budgetPlanItemDtoes XML.
443
+ """
444
+ return self._get(
445
+ "api/reports/ingredientEntry",
446
+ params=self._key(
447
+ department=departament,
448
+ includeSubtree=includeSubtree,
449
+ **kwargs,
450
+ ),
451
+ ).content
452
+
453
+ def olap2(self, body: dict) -> Any:
454
+ """Return OLAP report data using the v2 JSON API.
455
+
456
+ :param body: Report request dict. See API docs for the full schema::
457
+
458
+ {
459
+ "reportType": "SALES",
460
+ "buildSummary": "true",
461
+ "groupByRowFields": ["OpenDate.Typed", "Department"],
462
+ "aggregateFields": ["DishDiscountSumInt.withoutVAT"],
463
+ "filters": { ... }
464
+ }
465
+
466
+ :returns: Parsed JSON response.
467
+ """
468
+ return self._post(
469
+ "api/v2/reports/olap",
470
+ params={"key": self._token},
471
+ json=body,
472
+ ).json()
473
+
474
+ def reports_balance(
475
+ self,
476
+ timestamp: str,
477
+ account: str | None = None,
478
+ counteragent: str | None = None,
479
+ department: str | None = None,
480
+ ) -> Any:
481
+ """Return account, counteragent, and department balances.
482
+
483
+ :param timestamp: Accounting date-time ``yyyy-MM-dd'T'HH:mm:ss``.
484
+ :param account: Account GUID filter (optional, repeatable).
485
+ :param counteragent: Counteragent GUID filter (optional).
486
+ :param department: Department GUID filter (optional).
487
+ :returns: Parsed JSON with quantity and monetary balances.
488
+ """
489
+ return self._get(
490
+ "reports/balance/counteragents",
491
+ params=self._key(
492
+ timestamp=timestamp,
493
+ account=account,
494
+ counteragent=counteragent,
495
+ department=department,
496
+ ),
497
+ ).json()
498
+
499
+ # ------------------------------------------------------------------
500
+ # Накладные
501
+ # ------------------------------------------------------------------
502
+
503
+ def invoice_in(self, **kwargs: Any) -> bytes:
504
+ """Export incoming invoices.
505
+
506
+ :param from: Start date ``YYYY-MM-DD`` (inclusive).
507
+ :param to: End date ``YYYY-MM-DD`` (inclusive, time ignored).
508
+ :param supplierId: Supplier GUID filter (optional).
509
+ :returns: Incoming invoice XSD.
510
+ """
511
+ return self._get(
512
+ "api/documents/export/incomingInvoice",
513
+ params=self._key(**kwargs),
514
+ ).content
515
+
516
+ def invoice_out(self, **kwargs: Any) -> bytes:
517
+ """Export outgoing invoices.
518
+
519
+ :param from: Start date ``YYYY-MM-DD`` (inclusive).
520
+ :param to: End date ``YYYY-MM-DD`` (inclusive, time ignored).
521
+ :param supplierId: Supplier GUID filter (optional).
522
+ :returns: Outgoing invoice XSD.
523
+ """
524
+ return self._get(
525
+ "api/documents/export/outgoingInvoice",
526
+ params=self._key(**kwargs),
527
+ ).content
528
+
529
+ def invoice_number_in(self, current_year: bool = True, **kwargs: Any) -> bytes:
530
+ """Export an incoming invoice by document number.
531
+
532
+ :param number: Document number.
533
+ :param current_year: Restrict to current year (default ``True``).
534
+ When ``False``, *from* and *to* must be provided.
535
+ :param from: Start date ``YYYY-MM-DD`` (required when
536
+ ``current_year=False``).
537
+ :param to: End date ``YYYY-MM-DD`` (required when
538
+ ``current_year=False``).
539
+ """
540
+ return self._get(
541
+ "api/documents/export/incomingInvoice/byNumber",
542
+ params=self._key(
543
+ currentYear=str(current_year).lower(), **kwargs
544
+ ),
545
+ ).content
546
+
547
+ def invoice_number_out(self, current_year: bool = True, **kwargs: Any) -> bytes:
548
+ """Export an outgoing invoice by document number.
549
+
550
+ :param number: Document number.
551
+ :param current_year: Restrict to current year (default ``True``).
552
+ When ``False``, *from* and *to* must be provided.
553
+ :param from: Start date ``YYYY-MM-DD`` (required when
554
+ ``current_year=False``).
555
+ :param to: End date ``YYYY-MM-DD`` (required when
556
+ ``current_year=False``).
557
+ """
558
+ return self._get(
559
+ "api/documents/export/outgoingInvoice/byNumber",
560
+ params=self._key(
561
+ currentYear=str(current_year).lower(), **kwargs
562
+ ),
563
+ ).content
564
+
565
+ def production_doc(self, xml: str | bytes) -> bytes:
566
+ """Upload a production act (акт приготовления).
567
+
568
+ :param xml: XML document body.
569
+ """
570
+ return self._post(
571
+ "api/documents/import/productionDocument",
572
+ params={"key": self._token},
573
+ data=xml,
574
+ headers={"Content-type": "text/xml"},
575
+ ).content
576
+
577
+ # ------------------------------------------------------------------
578
+ # Кассовые смены
579
+ # ------------------------------------------------------------------
580
+
581
+ def close_session(
582
+ self,
583
+ dateFrom: str | None = None,
584
+ dateTo: str | None = None,
585
+ ) -> bytes:
586
+ """Return a list of cash register sessions.
587
+
588
+ :param dateFrom: Start date ``DD.MM.YYYY``.
589
+ :param dateTo: End date ``DD.MM.YYYY``.
590
+ :returns: CloseSessionDto list.
591
+ """
592
+ return self._get(
593
+ "api/closeSession/list",
594
+ params=self._key(dateFrom=dateFrom, dateTo=dateTo),
595
+ ).content
596
+
597
+ def session(
598
+ self,
599
+ from_time: str | None = None,
600
+ to_time: str | None = None,
601
+ ) -> bytes:
602
+ """Return cash register session details.
603
+
604
+ :param from_time: Start ISO ``yyyy-MM-ddTHH:mm:ss.SSS``.
605
+ :param to_time: End ISO (exclusive).
606
+ :returns: Session information.
607
+ """
608
+ return self._get(
609
+ "api/events/sessions",
610
+ params=self._key(**{"from": from_time, "to": to_time}),
611
+ ).content
612
+
613
+ # ------------------------------------------------------------------
614
+ # EDI
615
+ # ------------------------------------------------------------------
616
+
617
+ def edi(
618
+ self,
619
+ edi: str,
620
+ gln: str | None = None,
621
+ inn: str | None = None,
622
+ kpp: str | None = None,
623
+ name: str | None = None,
624
+ ) -> bytes:
625
+ """Return EDI orders for a participant and supplier.
626
+
627
+ :param edi: EDI system GUID (EdiSystem identifier).
628
+ :param gln: Supplier GLN (required if *inn* is absent).
629
+ :param inn: Supplier INN (required if *gln* is absent).
630
+ :param kpp: Supplier KPP (optional).
631
+ :param name: Supplier name (optional).
632
+ :returns: EDI order list.
633
+ """
634
+ return self._get(
635
+ f"edi/{edi}/orders/bySeller",
636
+ params=self._key(gln=gln, inn=inn, kpp=kpp, name=name),
637
+ ).content