acumatica-api 0.1.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.
- acumatica/__init__.py +20 -0
- acumatica/auth.py +318 -0
- acumatica/client.py +284 -0
- acumatica/endpoints/__init__.py +0 -0
- acumatica/endpoints/base.py +191 -0
- acumatica/entities.py +88 -0
- acumatica/errors.py +21 -0
- acumatica/ratelimit.py +106 -0
- acumatica/utils.py +206 -0
- acumatica_api-0.1.0.dist-info/METADATA +232 -0
- acumatica_api-0.1.0.dist-info/RECORD +13 -0
- acumatica_api-0.1.0.dist-info/WHEEL +5 -0
- acumatica_api-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""The read-only entity handle."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
from urllib.parse import quote
|
|
7
|
+
|
|
8
|
+
from acumatica.errors import AcumaticaError
|
|
9
|
+
from acumatica.utils import build_query
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from collections.abc import Iterator, Sequence
|
|
13
|
+
|
|
14
|
+
from acumatica.client import Acumatica
|
|
15
|
+
|
|
16
|
+
# Unmeasured. The TESTING tenant holds seven stock items, so nothing there
|
|
17
|
+
# exercises a page boundary at this size, let alone the server's own ceiling.
|
|
18
|
+
# Page size is the highest-leverage number in a sweep -- it divides the request
|
|
19
|
+
# count directly -- so measure it against real data before trusting this.
|
|
20
|
+
DEFAULT_PAGE_SIZE = 200
|
|
21
|
+
|
|
22
|
+
# Spelled out here, where `list` is still the builtin. Inside `Entity` the name
|
|
23
|
+
# is taken by the method, so an inline `list[dict[str, Any]]` annotation
|
|
24
|
+
# resolves to that instead and the generated docs render it wrong.
|
|
25
|
+
Record = dict[str, Any]
|
|
26
|
+
Records = list[Record]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Entity:
|
|
30
|
+
"""One entity of one endpoint, read-only.
|
|
31
|
+
|
|
32
|
+
Returns payloads exactly as Acumatica sent them, which means every scalar
|
|
33
|
+
field arrives as `{"value": ...}`. Pass the result through
|
|
34
|
+
`acumatica.utils.unwrap` to flatten it -- kept opt-in so nothing is parsed
|
|
35
|
+
behind the caller's back, and so a field carrying an error is not silently
|
|
36
|
+
reduced to a value.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(self, client: Acumatica, name: str):
|
|
40
|
+
self._client = client
|
|
41
|
+
self._name = name
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def name(self) -> str:
|
|
45
|
+
"""The entity name, as it appears in the URL."""
|
|
46
|
+
return self._name
|
|
47
|
+
|
|
48
|
+
def get(
|
|
49
|
+
self,
|
|
50
|
+
*keys: str,
|
|
51
|
+
select: Sequence[str] | str | None = None,
|
|
52
|
+
expand: Sequence[str] | str | None = None,
|
|
53
|
+
custom: Sequence[str] | str | None = None,
|
|
54
|
+
) -> Record:
|
|
55
|
+
"""Get one record by ID or by its key fields.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
*keys: The record's ID, or its key fields in order. `SalesOrder`
|
|
59
|
+
takes two, `OrderType` and `OrderNbr`.
|
|
60
|
+
select (Sequence[str] | str, optional): Fields to return. Must
|
|
61
|
+
qualify fields of any expanded entity. Defaults to None.
|
|
62
|
+
expand (Sequence[str] | str, optional): Detail entities to include.
|
|
63
|
+
Defaults to None.
|
|
64
|
+
custom (Sequence[str] | str, optional): Custom fields to return.
|
|
65
|
+
Defaults to None.
|
|
66
|
+
|
|
67
|
+
Returns:
|
|
68
|
+
dict[str, Any]: The record.
|
|
69
|
+
|
|
70
|
+
Raises:
|
|
71
|
+
ValueError: If no key is given, or if `select` would silently empty
|
|
72
|
+
an expanded entity.
|
|
73
|
+
"""
|
|
74
|
+
if not keys:
|
|
75
|
+
raise ValueError(f"{self._name}.get() needs an ID or key fields")
|
|
76
|
+
# An empty or missing key is the dangerous case, not an obvious one.
|
|
77
|
+
# `get("")` builds `StockItem/`, which Acumatica answers as a *whole
|
|
78
|
+
# collection* read -- a success, typed here as one record. `get(None)`
|
|
79
|
+
# builds the literal segment "None" and 404s. Both are caller bugs
|
|
80
|
+
# worth naming rather than forwarding.
|
|
81
|
+
if any(key is None or str(key) == "" for key in keys):
|
|
82
|
+
raise ValueError(
|
|
83
|
+
f"{self._name}.get() was given an empty key. An empty segment "
|
|
84
|
+
f"reads the whole collection and returns it as one record."
|
|
85
|
+
)
|
|
86
|
+
# Key values are business data -- order numbers, item IDs -- and carry
|
|
87
|
+
# spaces and slashes often enough that leaving them raw builds a URL
|
|
88
|
+
# pointing at a different record, or at nothing.
|
|
89
|
+
segments = "/".join(quote(str(key), safe="") for key in keys)
|
|
90
|
+
return self._client.get(
|
|
91
|
+
f"{self._name}/{segments}",
|
|
92
|
+
params=build_query(select=select, expand=expand, custom=custom),
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
def list(
|
|
96
|
+
self,
|
|
97
|
+
*,
|
|
98
|
+
filter: str | None = None,
|
|
99
|
+
select: Sequence[str] | str | None = None,
|
|
100
|
+
expand: Sequence[str] | str | None = None,
|
|
101
|
+
top: int | None = None,
|
|
102
|
+
skip: int | None = None,
|
|
103
|
+
custom: Sequence[str] | str | None = None,
|
|
104
|
+
) -> Records:
|
|
105
|
+
"""List records, optionally filtered.
|
|
106
|
+
|
|
107
|
+
One request, one page. Use `stream` to walk the whole set.
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
filter (str, optional): An OData `$filter` expression. For
|
|
111
|
+
incremental sync use `acumatica.utils.modified_since`, which
|
|
112
|
+
handles the watermark precision trap. Defaults to None.
|
|
113
|
+
select (Sequence[str] | str, optional): Fields to return. Must
|
|
114
|
+
qualify fields of any expanded entity. Defaults to None.
|
|
115
|
+
expand (Sequence[str] | str, optional): Detail entities to include.
|
|
116
|
+
Defaults to None.
|
|
117
|
+
top (int, optional): Maximum records to return. Defaults to None.
|
|
118
|
+
skip (int, optional): Records to skip. Defaults to None.
|
|
119
|
+
custom (Sequence[str] | str, optional): Custom fields to return.
|
|
120
|
+
Defaults to None.
|
|
121
|
+
|
|
122
|
+
Returns:
|
|
123
|
+
list[dict[str, Any]]: The records on this page.
|
|
124
|
+
|
|
125
|
+
Raises:
|
|
126
|
+
ValueError: If `select` would silently empty an expanded entity.
|
|
127
|
+
AcumaticaError: If a 200 carries something other than an array.
|
|
128
|
+
"""
|
|
129
|
+
response = self._client.get(
|
|
130
|
+
self._name,
|
|
131
|
+
params=build_query(
|
|
132
|
+
filter=filter,
|
|
133
|
+
select=select,
|
|
134
|
+
expand=expand,
|
|
135
|
+
top=top,
|
|
136
|
+
skip=skip,
|
|
137
|
+
custom=custom,
|
|
138
|
+
),
|
|
139
|
+
)
|
|
140
|
+
if not isinstance(response, list):
|
|
141
|
+
# Coercing to `[]` would be the third silent-truncation bug in a
|
|
142
|
+
# package written to close the other two: an unexpected body would
|
|
143
|
+
# read as "no records" and end `stream` at zero rows.
|
|
144
|
+
raise AcumaticaError(
|
|
145
|
+
200,
|
|
146
|
+
f"{self._name} list returned {type(response).__name__}, not an array",
|
|
147
|
+
)
|
|
148
|
+
return response
|
|
149
|
+
|
|
150
|
+
def stream(
|
|
151
|
+
self,
|
|
152
|
+
*,
|
|
153
|
+
page_size: int | None = None,
|
|
154
|
+
**query: Any,
|
|
155
|
+
) -> Iterator[Record]:
|
|
156
|
+
"""Walk every record, a page at a time.
|
|
157
|
+
|
|
158
|
+
Args:
|
|
159
|
+
page_size (int, optional): Records per request. Defaults to
|
|
160
|
+
`DEFAULT_PAGE_SIZE`, which is a guess -- see the note there
|
|
161
|
+
before relying on it for a large sweep.
|
|
162
|
+
**query: Forwarded to `list`, except `top` and `skip`, which this
|
|
163
|
+
method owns.
|
|
164
|
+
|
|
165
|
+
Yields:
|
|
166
|
+
dict[str, Any]: Each record.
|
|
167
|
+
|
|
168
|
+
Raises:
|
|
169
|
+
ValueError: If `top` or `skip` is passed.
|
|
170
|
+
"""
|
|
171
|
+
if "top" in query or "skip" in query:
|
|
172
|
+
raise ValueError(
|
|
173
|
+
"stream() paginates for you -- pass page_size rather than top or skip"
|
|
174
|
+
)
|
|
175
|
+
take = page_size or DEFAULT_PAGE_SIZE
|
|
176
|
+
skip = 0
|
|
177
|
+
while True:
|
|
178
|
+
page = self.list(top=take, skip=skip, **query)
|
|
179
|
+
yield from page
|
|
180
|
+
# Stop on an *empty* page, not a short one.
|
|
181
|
+
#
|
|
182
|
+
# Treating short as final assumes the server honours `$top`
|
|
183
|
+
# exactly, and nothing here has established that it does -- an
|
|
184
|
+
# instance-configured record cap below `page_size` would make
|
|
185
|
+
# every page short, and the sweep would end after one of them
|
|
186
|
+
# with a 200 and no error. That is the same silent-truncation
|
|
187
|
+
# shape this package exists to close, so it costs one extra
|
|
188
|
+
# request per sweep to not depend on it.
|
|
189
|
+
if not page:
|
|
190
|
+
return
|
|
191
|
+
skip += len(page)
|
acumatica/entities.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Entity names proven readable on the ADi instance.
|
|
2
|
+
|
|
3
|
+
Not a definition of what exists -- `Default/25.200.001` publishes 735 schemas
|
|
4
|
+
and `MANUFACTURING/25.100.001` publishes 277. These are the names that returned
|
|
5
|
+
HTTP 200 when every entity in both contracts was probed on 2026-11-17, which is
|
|
6
|
+
a statement about the `ODS Integration` role's form access rights rather than
|
|
7
|
+
about the contracts. Of 173 top-level entities probed, 45 read and 124 returned
|
|
8
|
+
403 naming the form whose access right was missing.
|
|
9
|
+
|
|
10
|
+
Use them to discover what is reachable today. `Acumatica.entity()` takes any
|
|
11
|
+
name, so nothing here constrains what can be requested, and a grant added to
|
|
12
|
+
the role later will not appear here until someone re-probes.
|
|
13
|
+
|
|
14
|
+
Authoritative check, per endpoint:
|
|
15
|
+
|
|
16
|
+
GET {base_url}/entity/{endpoint}/{version}/swagger.json
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
# Sorted tuples rather than frozensets. A frozenset's repr order is derived
|
|
22
|
+
# from string hashes, which are seeded per process, so the generated docs
|
|
23
|
+
# differ on every regeneration and each release PR carries a diff that means
|
|
24
|
+
# nothing. Membership still reads the same: `"StockItem" in DEFAULT_ENTITIES`.
|
|
25
|
+
|
|
26
|
+
# Readable through `Default/25.200.001`.
|
|
27
|
+
DEFAULT_ENTITIES = (
|
|
28
|
+
"Bill",
|
|
29
|
+
"Carrier",
|
|
30
|
+
"CashSale",
|
|
31
|
+
"Check",
|
|
32
|
+
"Customer",
|
|
33
|
+
"CustomerClass",
|
|
34
|
+
"CustomerLocation",
|
|
35
|
+
"CustomerPaymentMethod",
|
|
36
|
+
"CustomerPriceClass",
|
|
37
|
+
"Discount",
|
|
38
|
+
"DiscountCode",
|
|
39
|
+
"FOBPoint",
|
|
40
|
+
"InventoryAdjustment",
|
|
41
|
+
"InventoryIssue",
|
|
42
|
+
"InventoryReceipt",
|
|
43
|
+
"Invoice",
|
|
44
|
+
"ItemClass",
|
|
45
|
+
"ItemSalesCategory",
|
|
46
|
+
"ItemWarehouse",
|
|
47
|
+
"KitAssembly",
|
|
48
|
+
"KitSpecification",
|
|
49
|
+
"LotSerialClass",
|
|
50
|
+
"NonStockItem",
|
|
51
|
+
"Payment",
|
|
52
|
+
"PhysicalInventoryReview",
|
|
53
|
+
"PurchaseOrder",
|
|
54
|
+
"PurchaseReceipt",
|
|
55
|
+
"SalesInvoice",
|
|
56
|
+
"SalesOrder",
|
|
57
|
+
"SalesPriceWorksheet",
|
|
58
|
+
"Salesperson",
|
|
59
|
+
"ShipVia",
|
|
60
|
+
"Shipment",
|
|
61
|
+
"ShippingBox",
|
|
62
|
+
"ShippingTerm",
|
|
63
|
+
"ShippingZones",
|
|
64
|
+
"StockItem",
|
|
65
|
+
"Tax",
|
|
66
|
+
"TaxCategory",
|
|
67
|
+
"TaxZone",
|
|
68
|
+
"TransferOrder",
|
|
69
|
+
"Vendor",
|
|
70
|
+
"VendorClass",
|
|
71
|
+
"VendorPriceWorksheet",
|
|
72
|
+
"Warehouse",
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
# Readable through `MANUFACTURING/25.100.001`.
|
|
76
|
+
#
|
|
77
|
+
# None of these carry `LastModifiedDateTime` -- not one of the endpoint's 277
|
|
78
|
+
# schemas does, and a `$filter` on it returns HTTP 500 rather than a 400, so it
|
|
79
|
+
# reads like a server fault rather than a bad field name. The underlying DACs
|
|
80
|
+
# do carry it, so the field exists and is simply unmapped. Until that is
|
|
81
|
+
# addressed, manufacturing reconciles by full sweep while push notifications
|
|
82
|
+
# carry the real-time half.
|
|
83
|
+
MANUFACTURING_ENTITIES = (
|
|
84
|
+
"BillOfMaterial",
|
|
85
|
+
"ProductionOrder",
|
|
86
|
+
"ProductionOrderDetail",
|
|
87
|
+
"WorkCenter",
|
|
88
|
+
)
|
acumatica/errors.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Exceptions raised by the REST client.
|
|
2
|
+
|
|
3
|
+
Their own module so `endpoints` can raise them without importing `client`,
|
|
4
|
+
which imports `endpoints`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AcumaticaError(Exception):
|
|
13
|
+
"""A non-success response from the REST API."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, status_code: int, message: Any):
|
|
16
|
+
self.status_code = status_code
|
|
17
|
+
super().__init__(f"Acumatica API error {status_code}: {message}")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class AcumaticaRetryableError(AcumaticaError):
|
|
21
|
+
"""A response worth retrying -- throttling, or a gateway blip."""
|
acumatica/ratelimit.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""A token bucket over requests per minute.
|
|
2
|
+
|
|
3
|
+
Acumatica's licence caps three things, and the one that binds is not the one
|
|
4
|
+
that looks binding. Measured on the TESTING tenant (tier M1 - Prime):
|
|
5
|
+
|
|
6
|
+
| constraint | value |
|
|
7
|
+
|--------------------------------------|-------|
|
|
8
|
+
| Web Services API Users | 20 |
|
|
9
|
+
| Concurrent Web Services API Requests | 3 |
|
|
10
|
+
| Web Services API Requests per Minute | 150 |
|
|
11
|
+
|
|
12
|
+
150/min is 2.5 req/s, so three concurrent requests stay legal only if each
|
|
13
|
+
takes at least 1.2s. Measured latencies run 0.40-1.76s, mean around 0.8s, so
|
|
14
|
+
the concurrency limit is never what stops you -- the rate is. Hence a rate
|
|
15
|
+
limiter and not a semaphore.
|
|
16
|
+
|
|
17
|
+
All three are tenant-wide, shared with every other integration on the
|
|
18
|
+
instance, which is why the default budget here is well under the cap.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import threading
|
|
24
|
+
import time
|
|
25
|
+
from typing import TYPE_CHECKING
|
|
26
|
+
|
|
27
|
+
if TYPE_CHECKING:
|
|
28
|
+
from collections.abc import Callable
|
|
29
|
+
|
|
30
|
+
# Two thirds of the measured 150/min cap. The rest is headroom for Grafana,
|
|
31
|
+
# Tableau, webhook callbacks and anything else sharing the tenant.
|
|
32
|
+
DEFAULT_REQUESTS_PER_MINUTE = 100
|
|
33
|
+
|
|
34
|
+
# How many requests may go out back-to-back before pacing takes over.
|
|
35
|
+
#
|
|
36
|
+
# A bucket that starts full at its per-minute rate can emit `rate` requests
|
|
37
|
+
# instantly and then another `rate` as it refills, which is 2x the budget
|
|
38
|
+
# inside one 60-second window. Keeping the burst small bounds the worst case
|
|
39
|
+
# at `burst + per_minute` per window -- 110 against a cap of 150.
|
|
40
|
+
DEFAULT_BURST = 10
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class RateLimiter:
|
|
44
|
+
"""Paces requests to a sustained rate, allowing a small burst."""
|
|
45
|
+
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
per_minute: int = DEFAULT_REQUESTS_PER_MINUTE,
|
|
49
|
+
burst: int = DEFAULT_BURST,
|
|
50
|
+
*,
|
|
51
|
+
clock: Callable[[], float] = time.monotonic,
|
|
52
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
53
|
+
):
|
|
54
|
+
"""Initialize the limiter.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
per_minute (int, optional): The sustained rate.
|
|
58
|
+
Defaults to 100.
|
|
59
|
+
burst (int, optional): How many requests may go out back-to-back.
|
|
60
|
+
Defaults to 10.
|
|
61
|
+
clock (Callable[[], float], optional): A monotonic clock, injectable
|
|
62
|
+
for tests. Defaults to `time.monotonic`.
|
|
63
|
+
sleep (Callable[[float], None], optional): A sleep, injectable for
|
|
64
|
+
tests. Defaults to `time.sleep`.
|
|
65
|
+
|
|
66
|
+
Raises:
|
|
67
|
+
ValueError: If `per_minute` or `burst` is not positive.
|
|
68
|
+
"""
|
|
69
|
+
if per_minute <= 0:
|
|
70
|
+
raise ValueError("per_minute must be positive")
|
|
71
|
+
if burst <= 0:
|
|
72
|
+
raise ValueError("burst must be positive")
|
|
73
|
+
self._rate = per_minute / 60.0
|
|
74
|
+
self._capacity = float(burst)
|
|
75
|
+
self._tokens = float(burst)
|
|
76
|
+
self._clock = clock
|
|
77
|
+
self._sleep = sleep
|
|
78
|
+
self._updated = clock()
|
|
79
|
+
self._lock = threading.Lock()
|
|
80
|
+
|
|
81
|
+
def acquire(self) -> float:
|
|
82
|
+
"""Block until one request may be sent.
|
|
83
|
+
|
|
84
|
+
Thread-safe, but in-process only. Acumatica's budget is tenant-wide, so
|
|
85
|
+
several Lambda containers each holding their own limiter can still
|
|
86
|
+
exceed it between them -- that case needs a rate-limited queue
|
|
87
|
+
consumer, not a bigger bucket here.
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
float: Seconds spent waiting, for logging. Zero when a token was
|
|
91
|
+
already available.
|
|
92
|
+
"""
|
|
93
|
+
waited = 0.0
|
|
94
|
+
while True:
|
|
95
|
+
with self._lock:
|
|
96
|
+
now = self._clock()
|
|
97
|
+
self._tokens = min(
|
|
98
|
+
self._capacity, self._tokens + (now - self._updated) * self._rate
|
|
99
|
+
)
|
|
100
|
+
self._updated = now
|
|
101
|
+
if self._tokens >= 1.0:
|
|
102
|
+
self._tokens -= 1.0
|
|
103
|
+
return waited
|
|
104
|
+
delay = (1.0 - self._tokens) / self._rate
|
|
105
|
+
self._sleep(delay)
|
|
106
|
+
waited += delay
|
acumatica/utils.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""Query construction, watermarks, and payload unwrapping.
|
|
2
|
+
|
|
3
|
+
Two of Acumatica's failure modes return HTTP 200 with the wrong data, which is
|
|
4
|
+
worse than an error because nothing downstream can tell. Both are closed here
|
|
5
|
+
rather than left to callers:
|
|
6
|
+
|
|
7
|
+
- An unqualified `$select` beside `$expand` silently empties the expansion.
|
|
8
|
+
`build_query` raises instead of sending such a request.
|
|
9
|
+
- A `$filter` on `LastModifiedDateTime` compares against a value that can sit
|
|
10
|
+
fractionally below the one the API displayed, so a sub-second watermark drops
|
|
11
|
+
rows. `watermark` truncates to the whole second and backs off by an overlap.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from datetime import datetime, timedelta
|
|
17
|
+
from typing import TYPE_CHECKING, Any
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from collections.abc import Sequence
|
|
21
|
+
|
|
22
|
+
# Rows modified inside this window are re-fetched rather than risked. The ODS
|
|
23
|
+
# upserts by key, so re-reading a row costs a little bandwidth; missing one
|
|
24
|
+
# costs a silent gap that only a full sweep would ever find.
|
|
25
|
+
_DEFAULT_OVERLAP = timedelta(minutes=5)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _as_list(value: Sequence[str] | str | None) -> list[str]:
|
|
29
|
+
"""Normalise a comma string or sequence of fields into a list.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
value (Sequence[str] | str | None): The fields, however they were given.
|
|
33
|
+
|
|
34
|
+
Returns:
|
|
35
|
+
list[str]: The fields, stripped, with blanks dropped.
|
|
36
|
+
"""
|
|
37
|
+
if value is None:
|
|
38
|
+
return []
|
|
39
|
+
parts = value.split(",") if isinstance(value, str) else list(value)
|
|
40
|
+
return [p.strip() for p in parts if p and p.strip()]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _check_select_covers_expand(select: list[str], expand: list[str]) -> None:
|
|
44
|
+
"""Refuse a `$select` that would silently empty an `$expand`.
|
|
45
|
+
|
|
46
|
+
Acumatica answers such a request with HTTP 200 and the expanded collection
|
|
47
|
+
present but empty, so there is no error to catch and no row count to
|
|
48
|
+
compare against -- the detail lines simply are not there. Measured against
|
|
49
|
+
`StockItem` + `WarehouseDetails`, where it first read as "this warehouse
|
|
50
|
+
holds nothing".
|
|
51
|
+
|
|
52
|
+
The contract is that every expanded entity needs at least one field
|
|
53
|
+
selected through it, qualified with its path.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
select (list[str]): The requested `$select` fields.
|
|
57
|
+
expand (list[str]): The requested `$expand` paths.
|
|
58
|
+
|
|
59
|
+
Raises:
|
|
60
|
+
ValueError: If an expanded path has no field selected through it.
|
|
61
|
+
"""
|
|
62
|
+
if not select or not expand:
|
|
63
|
+
return
|
|
64
|
+
for path in expand:
|
|
65
|
+
prefix = f"{path}/"
|
|
66
|
+
if not any(field.startswith(prefix) for field in select):
|
|
67
|
+
raise ValueError(
|
|
68
|
+
f"$select is set but names no field under the expanded "
|
|
69
|
+
f"'{path}'. Acumatica would answer 200 with '{path}' empty "
|
|
70
|
+
f"rather than failing. Add '{prefix}<Field>' to $select, or "
|
|
71
|
+
f"drop $select entirely."
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def build_query(
|
|
76
|
+
*,
|
|
77
|
+
filter: str | None = None,
|
|
78
|
+
select: Sequence[str] | str | None = None,
|
|
79
|
+
expand: Sequence[str] | str | None = None,
|
|
80
|
+
top: int | None = None,
|
|
81
|
+
skip: int | None = None,
|
|
82
|
+
custom: Sequence[str] | str | None = None,
|
|
83
|
+
) -> dict[str, str] | None:
|
|
84
|
+
"""Build OData query parameters for a contract-based REST request.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
filter (str, optional): An OData `$filter` expression. Defaults to None.
|
|
88
|
+
select (Sequence[str] | str, optional):
|
|
89
|
+
Fields to return. Must qualify fields of any expanded entity with
|
|
90
|
+
its path, e.g. `WarehouseDetails/WarehouseID`. Defaults to None.
|
|
91
|
+
expand (Sequence[str] | str, optional):
|
|
92
|
+
Detail entities to include. Contract version 4 nests with a slash,
|
|
93
|
+
e.g. `Operations/Material`. Defaults to None.
|
|
94
|
+
top (int, optional): Maximum records to return. Defaults to None.
|
|
95
|
+
skip (int, optional): Records to skip. Defaults to None.
|
|
96
|
+
custom (Sequence[str] | str, optional):
|
|
97
|
+
Custom fields to return, in Acumatica's `View.Field` form.
|
|
98
|
+
Defaults to None.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
dict[str, str] | None: The query parameters, or None if there are none.
|
|
102
|
+
|
|
103
|
+
Raises:
|
|
104
|
+
ValueError: If `select` would silently empty an expanded entity.
|
|
105
|
+
"""
|
|
106
|
+
select_fields = _as_list(select)
|
|
107
|
+
expand_paths = _as_list(expand)
|
|
108
|
+
_check_select_covers_expand(select_fields, expand_paths)
|
|
109
|
+
|
|
110
|
+
params: dict[str, str] = {}
|
|
111
|
+
if filter:
|
|
112
|
+
params["$filter"] = filter
|
|
113
|
+
if select_fields:
|
|
114
|
+
params["$select"] = ",".join(select_fields)
|
|
115
|
+
if expand_paths:
|
|
116
|
+
params["$expand"] = ",".join(expand_paths)
|
|
117
|
+
if custom_fields := _as_list(custom):
|
|
118
|
+
params["$custom"] = ",".join(custom_fields)
|
|
119
|
+
if top is not None:
|
|
120
|
+
params["$top"] = str(top)
|
|
121
|
+
if skip is not None:
|
|
122
|
+
params["$skip"] = str(skip)
|
|
123
|
+
return params or None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def watermark(moment: datetime, overlap: timedelta = _DEFAULT_OVERLAP) -> str:
|
|
127
|
+
"""Render an OData datetime literal safe to use as a sync watermark.
|
|
128
|
+
|
|
129
|
+
Acumatica compares `LastModifiedDateTime` against a value that can sit
|
|
130
|
+
fractionally below the one it reported, so a watermark carrying
|
|
131
|
+
microseconds excludes rows written in the same second. Confirmed on two
|
|
132
|
+
separate rows before being believed.
|
|
133
|
+
|
|
134
|
+
Truncating rounds *down*, so the error direction is re-reading a row rather
|
|
135
|
+
than missing one, and the overlap covers clock skew between the ODS and the
|
|
136
|
+
ERP.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
moment (datetime): A timezone-aware moment, usually the start of the
|
|
140
|
+
last successful sync.
|
|
141
|
+
overlap (timedelta, optional): How far to back off.
|
|
142
|
+
Defaults to five minutes.
|
|
143
|
+
|
|
144
|
+
Returns:
|
|
145
|
+
str: A contract-version-4 `datetimeoffset` literal.
|
|
146
|
+
|
|
147
|
+
Raises:
|
|
148
|
+
ValueError: If `moment` is naive. The ERP's own timestamps carry an
|
|
149
|
+
offset, so a naive one would compare against an unknown zone.
|
|
150
|
+
"""
|
|
151
|
+
if moment.tzinfo is None:
|
|
152
|
+
raise ValueError(
|
|
153
|
+
"watermark() needs a timezone-aware datetime -- Acumatica's "
|
|
154
|
+
"timestamps carry an offset, so a naive one compares against an "
|
|
155
|
+
"unknown zone. Use datetime.now(UTC)."
|
|
156
|
+
)
|
|
157
|
+
floored = (moment - overlap).replace(microsecond=0)
|
|
158
|
+
return f"datetimeoffset'{floored.isoformat()}'"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def modified_since(moment: datetime, overlap: timedelta = _DEFAULT_OVERLAP) -> str:
|
|
162
|
+
"""Build the incremental-sync `$filter` for an entity that carries a watermark.
|
|
163
|
+
|
|
164
|
+
Not every entity does. The whole `MANUFACTURING/25.100.001` endpoint
|
|
165
|
+
exposes `LastModifiedDateTime` on none of its 277 schemas, and filtering on
|
|
166
|
+
it there returns HTTP 500 rather than a 400 -- so this reads like a server
|
|
167
|
+
fault rather than a bad field name. Check the endpoint's `swagger.json`
|
|
168
|
+
before assuming an entity supports it.
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
moment (datetime): A timezone-aware moment to sync from.
|
|
172
|
+
overlap (timedelta, optional): How far to back off.
|
|
173
|
+
Defaults to five minutes.
|
|
174
|
+
|
|
175
|
+
Returns:
|
|
176
|
+
str: An OData `$filter` expression.
|
|
177
|
+
"""
|
|
178
|
+
return f"LastModifiedDateTime gt {watermark(moment, overlap)}"
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def unwrap(payload: Any) -> Any:
|
|
182
|
+
"""Strip Acumatica's `{"value": ...}` envelope from a response.
|
|
183
|
+
|
|
184
|
+
Every scalar field arrives wrapped, which makes a raw payload awkward to
|
|
185
|
+
hand to anything expecting plain rows. The client returns the payload
|
|
186
|
+
verbatim -- like every other source client in the house -- and this is the
|
|
187
|
+
opt-in step, so nothing is parsed behind the caller's back.
|
|
188
|
+
|
|
189
|
+
A field carrying anything *besides* `value`, such as the per-field `error`
|
|
190
|
+
that contract version 5 adds, is left as a dict rather than unwrapped. The
|
|
191
|
+
error is the half worth keeping, and silently discarding it would turn a
|
|
192
|
+
rejected field into a plausible-looking value.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
payload (Any): A response, a record, or any fragment of one.
|
|
196
|
+
|
|
197
|
+
Returns:
|
|
198
|
+
Any: The same structure with single-key value envelopes collapsed.
|
|
199
|
+
"""
|
|
200
|
+
if isinstance(payload, list):
|
|
201
|
+
return [unwrap(item) for item in payload]
|
|
202
|
+
if isinstance(payload, dict):
|
|
203
|
+
if set(payload) == {"value"}:
|
|
204
|
+
return payload["value"]
|
|
205
|
+
return {key: unwrap(value) for key, value in payload.items()}
|
|
206
|
+
return payload
|