tavisowms-sdk 1.3.1__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.
- tavisowms_sdk-1.3.1/PKG-INFO +33 -0
- tavisowms_sdk-1.3.1/README.md +18 -0
- tavisowms_sdk-1.3.1/pyproject.toml +25 -0
- tavisowms_sdk-1.3.1/setup.cfg +4 -0
- tavisowms_sdk-1.3.1/tavisowms/__init__.py +36 -0
- tavisowms_sdk-1.3.1/tavisowms/_endpoints.py +249 -0
- tavisowms_sdk-1.3.1/tavisowms/client.py +281 -0
- tavisowms_sdk-1.3.1/tavisowms/credential.py +69 -0
- tavisowms_sdk-1.3.1/tavisowms/errors.py +63 -0
- tavisowms_sdk-1.3.1/tavisowms/models.py +195 -0
- tavisowms_sdk-1.3.1/tavisowms_sdk.egg-info/PKG-INFO +33 -0
- tavisowms_sdk-1.3.1/tavisowms_sdk.egg-info/SOURCES.txt +13 -0
- tavisowms_sdk-1.3.1/tavisowms_sdk.egg-info/dependency_links.txt +1 -0
- tavisowms_sdk-1.3.1/tavisowms_sdk.egg-info/top_level.txt +1 -0
- tavisowms_sdk-1.3.1/tests/test_client.py +115 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tavisowms-sdk
|
|
3
|
+
Version: 1.3.1
|
|
4
|
+
Summary: Tavisowms开放接口 Python SDK
|
|
5
|
+
Author: xiao yue
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/Taviso-inc/Tavisowms-SDK
|
|
8
|
+
Keywords: tavisowms,wms,warehouse,sdk,inventory
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Topic :: Office/Business :: Financial :: Accounting
|
|
12
|
+
Classifier: Typing :: Typed
|
|
13
|
+
Requires-Python: >=3.8
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# tavisowms-sdk(Python)
|
|
17
|
+
|
|
18
|
+
Tavisowms 开放接口的 Python SDK,只用标准库。
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install ./python
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from tavisowms import Client, Credential
|
|
26
|
+
|
|
27
|
+
client = Client(Credential("TVS-SDK_xxx:WMS-Taviso-xxx", "https://wms.example.com"))
|
|
28
|
+
print(client.me()["data"]["name"])
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
要求 Python ≥ 3.8。完整接口清单与场景配方见 [SDK 手册](../docs/MANUAL.md)。
|
|
32
|
+
|
|
33
|
+
Apache License 2.0。
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# tavisowms-sdk(Python)
|
|
2
|
+
|
|
3
|
+
Tavisowms 开放接口的 Python SDK,只用标准库。
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install ./python
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from tavisowms import Client, Credential
|
|
11
|
+
|
|
12
|
+
client = Client(Credential("TVS-SDK_xxx:WMS-Taviso-xxx", "https://wms.example.com"))
|
|
13
|
+
print(client.me()["data"]["name"])
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
要求 Python ≥ 3.8。完整接口清单与场景配方见 [SDK 手册](../docs/MANUAL.md)。
|
|
17
|
+
|
|
18
|
+
Apache License 2.0。
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "tavisowms-sdk"
|
|
7
|
+
version = "1.3.1"
|
|
8
|
+
description = "Tavisowms开放接口 Python SDK"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
authors = [{ name = "xiao yue" }]
|
|
13
|
+
keywords = ["tavisowms", "wms", "warehouse", "sdk", "inventory"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Topic :: Office/Business :: Financial :: Accounting",
|
|
18
|
+
"Typing :: Typed",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://github.com/Taviso-inc/Tavisowms-SDK"
|
|
23
|
+
|
|
24
|
+
[tool.setuptools.packages.find]
|
|
25
|
+
include = ["tavisowms*"]
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Tavisowms Python SDK。
|
|
2
|
+
|
|
3
|
+
from tavisowms import Client, Credential
|
|
4
|
+
client = Client(Credential("tw_live_xxx", "https://wms.example.com"))
|
|
5
|
+
print(client.me()["name"])
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .client import Client
|
|
9
|
+
from .credential import Credential, normalize_base_url
|
|
10
|
+
from .errors import TavisowmsError
|
|
11
|
+
from .models import (
|
|
12
|
+
PartnerCreateRequest,
|
|
13
|
+
ProductCreateRequest,
|
|
14
|
+
StockInRequest,
|
|
15
|
+
StockItem,
|
|
16
|
+
StockOutRequest,
|
|
17
|
+
StocktakeRequest,
|
|
18
|
+
TransferRequest,
|
|
19
|
+
WarehouseCreateRequest,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
__version__ = "1.3.1"
|
|
23
|
+
__all__ = [
|
|
24
|
+
"Client",
|
|
25
|
+
"Credential",
|
|
26
|
+
"TavisowmsError",
|
|
27
|
+
"normalize_base_url",
|
|
28
|
+
"StockItem",
|
|
29
|
+
"StockInRequest",
|
|
30
|
+
"StockOutRequest",
|
|
31
|
+
"TransferRequest",
|
|
32
|
+
"StocktakeRequest",
|
|
33
|
+
"ProductCreateRequest",
|
|
34
|
+
"PartnerCreateRequest",
|
|
35
|
+
"WarehouseCreateRequest",
|
|
36
|
+
]
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"""由 scripts/gen-endpoints.mjs 生成,不要手改。"""
|
|
2
|
+
|
|
3
|
+
ENDPOINTS = [
|
|
4
|
+
{
|
|
5
|
+
"id": "inventory",
|
|
6
|
+
"method": "GET",
|
|
7
|
+
"path": "/inventory",
|
|
8
|
+
"scope": "inventory:read"
|
|
9
|
+
},
|
|
10
|
+
{
|
|
11
|
+
"id": "lots",
|
|
12
|
+
"method": "GET",
|
|
13
|
+
"path": "/lots",
|
|
14
|
+
"scope": "lot:read"
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
"id": "low-stock",
|
|
18
|
+
"method": "GET",
|
|
19
|
+
"path": "/reports/low-stock",
|
|
20
|
+
"scope": "report:read"
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
"id": "me",
|
|
24
|
+
"method": "GET",
|
|
25
|
+
"path": "/me",
|
|
26
|
+
"scope": None
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
"id": "meta",
|
|
30
|
+
"method": "GET",
|
|
31
|
+
"path": "/meta",
|
|
32
|
+
"scope": "product:read"
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
"id": "movements",
|
|
36
|
+
"method": "GET",
|
|
37
|
+
"path": "/movements",
|
|
38
|
+
"scope": "stock:read"
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
"id": "order-detail",
|
|
42
|
+
"method": "GET",
|
|
43
|
+
"path": "/orders/{id}",
|
|
44
|
+
"scope": "order:read"
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
"id": "orders",
|
|
48
|
+
"method": "GET",
|
|
49
|
+
"path": "/orders",
|
|
50
|
+
"scope": "order:read"
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
"id": "partner-create",
|
|
54
|
+
"method": "POST",
|
|
55
|
+
"path": "/partners",
|
|
56
|
+
"scope": "partner:write"
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
"id": "partners",
|
|
60
|
+
"method": "GET",
|
|
61
|
+
"path": "/partners",
|
|
62
|
+
"scope": "partner:read"
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
"id": "product-create",
|
|
66
|
+
"method": "POST",
|
|
67
|
+
"path": "/products",
|
|
68
|
+
"scope": "product:write"
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
"id": "products",
|
|
72
|
+
"method": "GET",
|
|
73
|
+
"path": "/products",
|
|
74
|
+
"scope": "product:read"
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
"id": "stock-in",
|
|
78
|
+
"method": "POST",
|
|
79
|
+
"path": "/stock-in",
|
|
80
|
+
"scope": "stock:write"
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
"id": "stock-in-list",
|
|
84
|
+
"method": "GET",
|
|
85
|
+
"path": "/stock-in",
|
|
86
|
+
"scope": "stock:read"
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
"id": "stock-in-post",
|
|
90
|
+
"method": "POST",
|
|
91
|
+
"path": "/stock-in/{id}/post",
|
|
92
|
+
"scope": "stock:write"
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
"id": "stock-out",
|
|
96
|
+
"method": "POST",
|
|
97
|
+
"path": "/stock-out",
|
|
98
|
+
"scope": "stock:write"
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
"id": "stock-out-list",
|
|
102
|
+
"method": "GET",
|
|
103
|
+
"path": "/stock-out",
|
|
104
|
+
"scope": "stock:read"
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
"id": "stock-out-post",
|
|
108
|
+
"method": "POST",
|
|
109
|
+
"path": "/stock-out/{id}/post",
|
|
110
|
+
"scope": "stock:write"
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
"id": "stock-summary",
|
|
114
|
+
"method": "GET",
|
|
115
|
+
"path": "/reports/stock-summary",
|
|
116
|
+
"scope": "report:read"
|
|
117
|
+
},
|
|
118
|
+
{
|
|
119
|
+
"id": "stock-value",
|
|
120
|
+
"method": "GET",
|
|
121
|
+
"path": "/reports/stock-value",
|
|
122
|
+
"scope": "report:read"
|
|
123
|
+
},
|
|
124
|
+
{
|
|
125
|
+
"id": "stocktake",
|
|
126
|
+
"method": "POST",
|
|
127
|
+
"path": "/stocktake",
|
|
128
|
+
"scope": "stocktake:write"
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
"id": "stocktake-count",
|
|
132
|
+
"method": "PATCH",
|
|
133
|
+
"path": "/stocktake/{id}",
|
|
134
|
+
"scope": "stocktake:write"
|
|
135
|
+
},
|
|
136
|
+
{
|
|
137
|
+
"id": "stocktake-detail",
|
|
138
|
+
"method": "GET",
|
|
139
|
+
"path": "/stocktake/{id}",
|
|
140
|
+
"scope": "stock:read"
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
"id": "stocktake-settle",
|
|
144
|
+
"method": "POST",
|
|
145
|
+
"path": "/stocktake/{id}/settle",
|
|
146
|
+
"scope": "stocktake:write"
|
|
147
|
+
},
|
|
148
|
+
{
|
|
149
|
+
"id": "transfer",
|
|
150
|
+
"method": "POST",
|
|
151
|
+
"path": "/transfer",
|
|
152
|
+
"scope": "transfer:write"
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
"id": "transfer-detail",
|
|
156
|
+
"method": "GET",
|
|
157
|
+
"path": "/transfer/{id}",
|
|
158
|
+
"scope": "order:read"
|
|
159
|
+
},
|
|
160
|
+
{
|
|
161
|
+
"id": "transfer-receive",
|
|
162
|
+
"method": "POST",
|
|
163
|
+
"path": "/transfer/{id}/receive",
|
|
164
|
+
"scope": "transfer:write"
|
|
165
|
+
},
|
|
166
|
+
{
|
|
167
|
+
"id": "transfer-send",
|
|
168
|
+
"method": "POST",
|
|
169
|
+
"path": "/transfer/{id}/send",
|
|
170
|
+
"scope": "transfer:write"
|
|
171
|
+
},
|
|
172
|
+
{
|
|
173
|
+
"id": "warehouse-create",
|
|
174
|
+
"method": "POST",
|
|
175
|
+
"path": "/warehouses",
|
|
176
|
+
"scope": "warehouse:write"
|
|
177
|
+
},
|
|
178
|
+
{
|
|
179
|
+
"id": "warehouses",
|
|
180
|
+
"method": "GET",
|
|
181
|
+
"path": "/warehouses",
|
|
182
|
+
"scope": "warehouse:read"
|
|
183
|
+
}
|
|
184
|
+
]
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def attach(client):
|
|
188
|
+
"""把生成的方法挂到 Client 上;已存在的不覆盖。"""
|
|
189
|
+
if not hasattr(client, "inventory"):
|
|
190
|
+
client.inventory = lambda **query: client._request("/inventory", query=query)
|
|
191
|
+
if not hasattr(client, "lots"):
|
|
192
|
+
client.lots = lambda **query: client._request("/lots", query=query)
|
|
193
|
+
if not hasattr(client, "low_stock"):
|
|
194
|
+
client.low_stock = lambda **query: client._request("/reports/low-stock", query=query)
|
|
195
|
+
if not hasattr(client, "me"):
|
|
196
|
+
client.me = lambda **query: client._request("/me", query=query)
|
|
197
|
+
if not hasattr(client, "meta"):
|
|
198
|
+
client.meta = lambda **query: client._request("/meta", query=query)
|
|
199
|
+
if not hasattr(client, "movements"):
|
|
200
|
+
client.movements = lambda **query: client._request("/movements", query=query)
|
|
201
|
+
if not hasattr(client, "order_get"):
|
|
202
|
+
client.order_get = lambda id, **query: client._request("/orders/" + str(id) + "", query=query)
|
|
203
|
+
if not hasattr(client, "orders"):
|
|
204
|
+
client.orders = lambda **query: client._request("/orders", query=query)
|
|
205
|
+
if not hasattr(client, "create_partner"):
|
|
206
|
+
client.create_partner = lambda body: client._request("/partners", method="POST", body=body.to_payload() if hasattr(body, "to_payload") else body)
|
|
207
|
+
if not hasattr(client, "partners"):
|
|
208
|
+
client.partners = lambda **query: client._request("/partners", query=query)
|
|
209
|
+
if not hasattr(client, "create_product"):
|
|
210
|
+
client.create_product = lambda body: client._request("/products", method="POST", body=body.to_payload() if hasattr(body, "to_payload") else body)
|
|
211
|
+
if not hasattr(client, "products"):
|
|
212
|
+
client.products = lambda **query: client._request("/products", query=query)
|
|
213
|
+
if not hasattr(client, "stock_in"):
|
|
214
|
+
client.stock_in = lambda body: client._request("/stock-in", method="POST", body=body.to_payload() if hasattr(body, "to_payload") else body)
|
|
215
|
+
if not hasattr(client, "stock_in_list"):
|
|
216
|
+
client.stock_in_list = lambda **query: client._request("/stock-in", query=query)
|
|
217
|
+
if not hasattr(client, "stock_in_post"):
|
|
218
|
+
client.stock_in_post = lambda id, **query: client._request("/stock-in/" + str(id) + "/post", query=query)
|
|
219
|
+
if not hasattr(client, "stock_out"):
|
|
220
|
+
client.stock_out = lambda body: client._request("/stock-out", method="POST", body=body.to_payload() if hasattr(body, "to_payload") else body)
|
|
221
|
+
if not hasattr(client, "stock_out_list"):
|
|
222
|
+
client.stock_out_list = lambda **query: client._request("/stock-out", query=query)
|
|
223
|
+
if not hasattr(client, "stock_out_post"):
|
|
224
|
+
client.stock_out_post = lambda id, **query: client._request("/stock-out/" + str(id) + "/post", query=query)
|
|
225
|
+
if not hasattr(client, "stock_summary"):
|
|
226
|
+
client.stock_summary = lambda **query: client._request("/reports/stock-summary", query=query)
|
|
227
|
+
if not hasattr(client, "stock_value"):
|
|
228
|
+
client.stock_value = lambda **query: client._request("/reports/stock-value", query=query)
|
|
229
|
+
if not hasattr(client, "stocktake"):
|
|
230
|
+
client.stocktake = lambda body: client._request("/stocktake", method="POST", body=body.to_payload() if hasattr(body, "to_payload") else body)
|
|
231
|
+
if not hasattr(client, "stocktake_enter_count"):
|
|
232
|
+
client.stocktake_enter_count = lambda id, items: client._request("/stocktake/" + str(id) + "", method="PATCH", body={"items": items})
|
|
233
|
+
if not hasattr(client, "stocktake_get"):
|
|
234
|
+
client.stocktake_get = lambda id, **query: client._request("/stocktake/" + str(id) + "", query=query)
|
|
235
|
+
if not hasattr(client, "stocktake_settle"):
|
|
236
|
+
client.stocktake_settle = lambda id, **query: client._request("/stocktake/" + str(id) + "/settle", query=query)
|
|
237
|
+
if not hasattr(client, "transfer"):
|
|
238
|
+
client.transfer = lambda body: client._request("/transfer", method="POST", body=body.to_payload() if hasattr(body, "to_payload") else body)
|
|
239
|
+
if not hasattr(client, "transfer_get"):
|
|
240
|
+
client.transfer_get = lambda id, **query: client._request("/transfer/" + str(id) + "", query=query)
|
|
241
|
+
if not hasattr(client, "transfer_receive"):
|
|
242
|
+
client.transfer_receive = lambda id, body=None: client._request("/transfer/" + str(id) + "/receive", method="POST", body=body)
|
|
243
|
+
if not hasattr(client, "transfer_send"):
|
|
244
|
+
client.transfer_send = lambda id, **query: client._request("/transfer/" + str(id) + "/send", query=query)
|
|
245
|
+
if not hasattr(client, "create_warehouse"):
|
|
246
|
+
client.create_warehouse = lambda body: client._request("/warehouses", method="POST", body=body.to_payload() if hasattr(body, "to_payload") else body)
|
|
247
|
+
if not hasattr(client, "warehouses"):
|
|
248
|
+
client.warehouses = lambda **query: client._request("/warehouses", query=query)
|
|
249
|
+
return client
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""Tavisowms 客户端(对标腾讯云 SDK:Credential + Client + 按资源分组的方法)。"""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import random
|
|
5
|
+
import string
|
|
6
|
+
import time
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
|
|
11
|
+
from .credential import Credential
|
|
12
|
+
from .errors import TavisowmsError, from_response
|
|
13
|
+
from .models import (
|
|
14
|
+
PartnerCreateRequest,
|
|
15
|
+
ProductCreateRequest,
|
|
16
|
+
StockInRequest,
|
|
17
|
+
StockOutRequest,
|
|
18
|
+
StocktakeRequest,
|
|
19
|
+
TransferRequest,
|
|
20
|
+
WarehouseCreateRequest,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
API_PREFIX = "/api/v1/open"
|
|
24
|
+
USER_AGENT = "tavisowms-sdk-python/1.3.1"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Result(dict):
|
|
28
|
+
"""解包后的返回体。
|
|
29
|
+
|
|
30
|
+
服务端信封是 {"success": true, "data": {...}};这里解包 data,
|
|
31
|
+
同时保留 .data 指向自己,于是 res["items"] 与 res.data["items"] 都能用。
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def data(self):
|
|
36
|
+
return self
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ResultList(list):
|
|
40
|
+
"""data 是数组时的返回体(如盘点录实盘返回每行差异)。"""
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def data(self):
|
|
44
|
+
return self
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _camel(key):
|
|
48
|
+
"""page_size → pageSize;已经驼峰的键原样返回。"""
|
|
49
|
+
if "_" not in key:
|
|
50
|
+
return key
|
|
51
|
+
head, *rest = key.split("_")
|
|
52
|
+
return head + "".join(w[:1].upper() + w[1:] for w in rest)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _camel_query(query):
|
|
56
|
+
if not query:
|
|
57
|
+
return {}
|
|
58
|
+
return {_camel(k): v for k, v in query.items()}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _unwrap(parsed):
|
|
62
|
+
if isinstance(parsed, dict) and parsed.get("success") is True and "data" in parsed:
|
|
63
|
+
data = parsed["data"]
|
|
64
|
+
if isinstance(data, dict):
|
|
65
|
+
return Result(data)
|
|
66
|
+
if isinstance(data, list):
|
|
67
|
+
return ResultList(data)
|
|
68
|
+
return data
|
|
69
|
+
return parsed
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Client:
|
|
73
|
+
"""Tavisowms 开放接口客户端。
|
|
74
|
+
|
|
75
|
+
>>> client = Client(Credential("tw_live_xxx", "https://wms.example.com"))
|
|
76
|
+
>>> client.me()["name"]
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
def __init__(self, credential, timeout=20, retries=2, headers=None):
|
|
80
|
+
if not isinstance(credential, Credential):
|
|
81
|
+
raise TypeError("credential 必须是 Credential 实例")
|
|
82
|
+
self.credential = credential
|
|
83
|
+
self.timeout = timeout
|
|
84
|
+
self.retries = retries
|
|
85
|
+
self.headers = headers or {}
|
|
86
|
+
# 生成器产出的方法(详情/过账/收发/录盘结算…);手写方法优先,不覆盖
|
|
87
|
+
from ._endpoints import attach as _attach_generated
|
|
88
|
+
_attach_generated(self)
|
|
89
|
+
|
|
90
|
+
# ------------------------------------------------------------------ 传输
|
|
91
|
+
def _request(self, path, method="GET", query=None, body=None, idempotency_key=None, retries=None, prefix=API_PREFIX):
|
|
92
|
+
url = self.credential.base_url + prefix + path
|
|
93
|
+
if query:
|
|
94
|
+
query = _camel_query(query)
|
|
95
|
+
pairs = [(k, v) for k, v in query.items() if v not in (None, "")]
|
|
96
|
+
if pairs:
|
|
97
|
+
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(pairs)
|
|
98
|
+
|
|
99
|
+
headers = dict(self.credential.headers())
|
|
100
|
+
headers["User-Agent"] = USER_AGENT
|
|
101
|
+
headers.update(self.headers)
|
|
102
|
+
data = None
|
|
103
|
+
if body is not None and method not in ("GET", "HEAD"):
|
|
104
|
+
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
|
105
|
+
headers["Content-Type"] = "application/json"
|
|
106
|
+
if method not in ("GET", "HEAD"):
|
|
107
|
+
headers["Idempotency-Key"] = idempotency_key or _uuid()
|
|
108
|
+
|
|
109
|
+
max_retries = self.retries if retries is None else retries
|
|
110
|
+
attempt = 0
|
|
111
|
+
last_error = None
|
|
112
|
+
while attempt <= max_retries:
|
|
113
|
+
attempt += 1
|
|
114
|
+
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
115
|
+
try:
|
|
116
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
117
|
+
raw = resp.read().decode("utf-8") or "{}"
|
|
118
|
+
return _unwrap(json.loads(raw)) if raw else {}
|
|
119
|
+
except urllib.error.HTTPError as e:
|
|
120
|
+
raw = e.read().decode("utf-8", "replace")
|
|
121
|
+
try:
|
|
122
|
+
parsed = json.loads(raw) if raw else {}
|
|
123
|
+
except ValueError:
|
|
124
|
+
parsed = {"raw": raw}
|
|
125
|
+
err = from_response(e.code, parsed)
|
|
126
|
+
if err.retryable and attempt <= max_retries:
|
|
127
|
+
time.sleep(min(2.0, 0.2 * (2 ** (attempt - 1))))
|
|
128
|
+
last_error = err
|
|
129
|
+
continue
|
|
130
|
+
raise err from None
|
|
131
|
+
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
|
132
|
+
last_error = TavisowmsError(f"网络请求失败:{e}", code="NETWORK", retryable=True,
|
|
133
|
+
hint="检查地址、网络、证书;内网自签证书需在服务端配置可信证书")
|
|
134
|
+
if attempt <= max_retries:
|
|
135
|
+
time.sleep(min(2.0, 0.2 * (2 ** (attempt - 1))))
|
|
136
|
+
continue
|
|
137
|
+
raise last_error from None
|
|
138
|
+
raise last_error or TavisowmsError("请求失败", code="UNKNOWN")
|
|
139
|
+
|
|
140
|
+
# ------------------------------------------------------------ 通用能力
|
|
141
|
+
def request(self, path, method="GET", query=None, body=None, idempotency_key=None):
|
|
142
|
+
"""打任意接口,path 从 /api/v1/open 之后开始,如 '/inventory'。"""
|
|
143
|
+
return self._request(path, method=method, query=query, body=body, idempotency_key=idempotency_key)
|
|
144
|
+
|
|
145
|
+
# ------------------------------------------------------------ MCP
|
|
146
|
+
def mcp(self, method, params=None):
|
|
147
|
+
"""调用 MCP JSON-RPC(与开放接口共用双密钥鉴权)。"""
|
|
148
|
+
payload = {"jsonrpc": "2.0", "id": int(time.time() * 1000), "method": method, "params": params or {}}
|
|
149
|
+
res = self._request("/api/mcp", method="POST", body=payload, prefix="")
|
|
150
|
+
if isinstance(res, dict) and res.get("error"):
|
|
151
|
+
raise TavisowmsError(res["error"].get("message") or "MCP 调用失败", code="MCP_ERROR", body=res)
|
|
152
|
+
return res.get("result") if isinstance(res, dict) and "result" in res else res
|
|
153
|
+
|
|
154
|
+
def mcp_tools(self):
|
|
155
|
+
return (self.mcp("tools/list") or {}).get("tools") or []
|
|
156
|
+
|
|
157
|
+
def mcp_call(self, name, arguments=None):
|
|
158
|
+
return self.mcp("tools/call", {"name": name, "arguments": arguments or {}})
|
|
159
|
+
|
|
160
|
+
def paginate(self, fn, params=None, page_size=200, max_pages=200):
|
|
161
|
+
"""生成器:逐页产出 {page, items, total}。"""
|
|
162
|
+
params = dict(params or {})
|
|
163
|
+
for page in range(1, max_pages + 1):
|
|
164
|
+
res = fn(**{**params, "page": page, "pageSize": page_size})
|
|
165
|
+
items = (res or {}).get("items") or []
|
|
166
|
+
yield {"page": page, "items": items, "total": (res or {}).get("total", 0)}
|
|
167
|
+
if len(items) < page_size:
|
|
168
|
+
return
|
|
169
|
+
|
|
170
|
+
def all(self, fn, params=None, page_size=200, max_pages=200):
|
|
171
|
+
"""一次拉全所有页。"""
|
|
172
|
+
out = []
|
|
173
|
+
for chunk in self.paginate(fn, params, page_size, max_pages):
|
|
174
|
+
out.extend(chunk["items"])
|
|
175
|
+
return out
|
|
176
|
+
|
|
177
|
+
# ------------------------------------------------------------ 只读接口
|
|
178
|
+
def me(self):
|
|
179
|
+
"""当前密钥身份、scope 与仓库范围。"""
|
|
180
|
+
return self._request("/me")
|
|
181
|
+
|
|
182
|
+
def meta(self, **query):
|
|
183
|
+
return self._request("/meta", query=query)
|
|
184
|
+
|
|
185
|
+
def products(self, **query):
|
|
186
|
+
return self._request("/products", query=query)
|
|
187
|
+
|
|
188
|
+
def create_product(self, req: ProductCreateRequest):
|
|
189
|
+
return self._request("/products", method="POST", body=req.to_payload(),
|
|
190
|
+
idempotency_key=req.idempotency_key)
|
|
191
|
+
|
|
192
|
+
def warehouses(self, with_locations=False):
|
|
193
|
+
return self._request("/warehouses", query={"withLocations": 1} if with_locations else None)
|
|
194
|
+
|
|
195
|
+
def create_warehouse(self, req: WarehouseCreateRequest):
|
|
196
|
+
return self._request("/warehouses", method="POST", body=req.to_payload(),
|
|
197
|
+
idempotency_key=req.idempotency_key)
|
|
198
|
+
|
|
199
|
+
def locations(self, warehouse_id=None):
|
|
200
|
+
"""货位拍平成「货架-排-列-位」,直接可做下拉框。"""
|
|
201
|
+
res = self.warehouses(with_locations=True)
|
|
202
|
+
rows = (res or {}).get("items") or res or []
|
|
203
|
+
out = []
|
|
204
|
+
for wh in rows:
|
|
205
|
+
if warehouse_id and str(wh.get("id")) != str(warehouse_id):
|
|
206
|
+
continue
|
|
207
|
+
for zone in wh.get("zones") or []:
|
|
208
|
+
zc = str(zone.get("code") or zone.get("name") or "")
|
|
209
|
+
for loc in zone.get("locations") or zone.get("boxes") or []:
|
|
210
|
+
lc = str(loc.get("code") or "")
|
|
211
|
+
full = lc if (not zc or lc.startswith(zc + "-")) else f"{zc}-{lc}"
|
|
212
|
+
out.append({
|
|
213
|
+
"id": str(loc.get("id")),
|
|
214
|
+
"code": full,
|
|
215
|
+
"name": loc.get("name") or "",
|
|
216
|
+
"warehouse_id": str(wh.get("id")),
|
|
217
|
+
"warehouse_name": wh.get("name") or "",
|
|
218
|
+
})
|
|
219
|
+
return out
|
|
220
|
+
|
|
221
|
+
def partners(self, **query):
|
|
222
|
+
return self._request("/partners", query=query)
|
|
223
|
+
|
|
224
|
+
def create_partner(self, req: PartnerCreateRequest):
|
|
225
|
+
return self._request("/partners", method="POST", body=req.to_payload(),
|
|
226
|
+
idempotency_key=req.idempotency_key)
|
|
227
|
+
|
|
228
|
+
def inventory(self, **query):
|
|
229
|
+
return self._request("/inventory", query=query)
|
|
230
|
+
|
|
231
|
+
def available(self, warehouse_id, product_id):
|
|
232
|
+
res = self.inventory(warehouseId=warehouse_id, productId=product_id, pageSize=50)
|
|
233
|
+
total = 0.0
|
|
234
|
+
for row in (res or {}).get("items") or []:
|
|
235
|
+
total += float(row.get("available", row.get("onHand", 0)) or 0)
|
|
236
|
+
return total
|
|
237
|
+
|
|
238
|
+
def lots(self, **query):
|
|
239
|
+
return self._request("/lots", query=query)
|
|
240
|
+
|
|
241
|
+
def movements(self, **query):
|
|
242
|
+
return self._request("/movements", query=query)
|
|
243
|
+
|
|
244
|
+
def orders(self, **query):
|
|
245
|
+
return self._request("/orders", query=query)
|
|
246
|
+
|
|
247
|
+
def low_stock(self, **query):
|
|
248
|
+
return self._request("/reports/low-stock", query=query)
|
|
249
|
+
|
|
250
|
+
def stock_summary(self, **query):
|
|
251
|
+
return self._request("/reports/stock-summary", query=query)
|
|
252
|
+
|
|
253
|
+
def stock_value(self, **query):
|
|
254
|
+
return self._request("/reports/stock-value", query=query)
|
|
255
|
+
|
|
256
|
+
# ------------------------------------------------------------ 写入接口
|
|
257
|
+
def stock_in(self, req: StockInRequest):
|
|
258
|
+
"""入库;auto_post=True 建单即过账。返回里 postError 非空表示没过去,单据是草稿。"""
|
|
259
|
+
return self._request("/stock-in", method="POST", body=req.to_payload(),
|
|
260
|
+
idempotency_key=req.idempotency_key)
|
|
261
|
+
|
|
262
|
+
def stock_out(self, req: StockOutRequest):
|
|
263
|
+
return self._request("/stock-out", method="POST", body=req.to_payload(),
|
|
264
|
+
idempotency_key=req.idempotency_key)
|
|
265
|
+
|
|
266
|
+
def transfer(self, req: TransferRequest):
|
|
267
|
+
return self._request("/transfer", method="POST", body=req.to_payload(),
|
|
268
|
+
idempotency_key=req.idempotency_key)
|
|
269
|
+
|
|
270
|
+
def stocktake(self, req: StocktakeRequest):
|
|
271
|
+
return self._request("/stocktake", method="POST", body=req.to_payload(),
|
|
272
|
+
idempotency_key=req.idempotency_key)
|
|
273
|
+
|
|
274
|
+
def __repr__(self):
|
|
275
|
+
return f"Client(base_url={self.credential.base_url!r}, key={self.credential.masked()})"
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _uuid():
|
|
279
|
+
alphabet = string.hexdigits.lower()[:16]
|
|
280
|
+
raw = "".join(random.choice(alphabet) for _ in range(32))
|
|
281
|
+
return f"{raw[:8]}-{raw[8:12]}-{raw[12:16]}-{raw[16:20]}-{raw[20:]}"
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""凭证:支持 SecretId + SecretKey 双密钥(推荐),兼容旧的单密钥 Bearer。"""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from urllib.parse import urlparse
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass
|
|
8
|
+
class Credential:
|
|
9
|
+
"""一把Tavisowms 密钥 + 服务端地址。
|
|
10
|
+
|
|
11
|
+
>>> Credential.from_url("https://wms.example.com/api/v1/open", "tw_live_xxx")
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
api_key: str = ""
|
|
15
|
+
base_url: str = "http://127.0.0.1:3000"
|
|
16
|
+
secret_id: str = ""
|
|
17
|
+
secret_key: str = ""
|
|
18
|
+
|
|
19
|
+
def __post_init__(self):
|
|
20
|
+
self.api_key = str(self.api_key or "").strip()
|
|
21
|
+
self.secret_id = str(self.secret_id or "").strip()
|
|
22
|
+
self.secret_key = str(self.secret_key or "").strip()
|
|
23
|
+
if not (self.secret_id and self.secret_key) and not self.api_key:
|
|
24
|
+
raise ValueError("需要 SecretId + SecretKey,或旧版 api_key(Tavisowms 后台 → 设置 → API 管理 生成)")
|
|
25
|
+
self.base_url = normalize_base_url(self.base_url)
|
|
26
|
+
|
|
27
|
+
@classmethod
|
|
28
|
+
def from_url(cls, base_url, api_key):
|
|
29
|
+
return cls(api_key=api_key, base_url=base_url)
|
|
30
|
+
|
|
31
|
+
@classmethod
|
|
32
|
+
def from_keys(cls, base_url, secret_id, secret_key):
|
|
33
|
+
return cls(secret_id=secret_id, secret_key=secret_key, base_url=base_url)
|
|
34
|
+
|
|
35
|
+
def headers(self):
|
|
36
|
+
if self.secret_id and self.secret_key:
|
|
37
|
+
return {
|
|
38
|
+
"X-TVS-Secret-Id": self.secret_id,
|
|
39
|
+
"X-TVS-Secret-Key": self.secret_key,
|
|
40
|
+
"Accept": "application/json",
|
|
41
|
+
}
|
|
42
|
+
return {
|
|
43
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
44
|
+
"Accept": "application/json",
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
def masked(self):
|
|
48
|
+
"""日志里用,别把密钥打全。"""
|
|
49
|
+
if self.secret_id and self.secret_key:
|
|
50
|
+
return self.secret_id + ":****"
|
|
51
|
+
k = self.api_key
|
|
52
|
+
return k[:10] + "…" + k[-4:] if len(k) > 16 else "tw_…"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def normalize_base_url(value):
|
|
56
|
+
v = str(value or "").strip()
|
|
57
|
+
if not v:
|
|
58
|
+
raise ValueError("缺少服务器地址 base_url")
|
|
59
|
+
if not v.lower().startswith(("http://", "https://")):
|
|
60
|
+
v = "https://" + v
|
|
61
|
+
v = v.rstrip("/")
|
|
62
|
+
for suffix in ("/api/v1/open", "/api/v1/desktop", "/api/v1", "/api"):
|
|
63
|
+
if v.lower().endswith(suffix):
|
|
64
|
+
v = v[: -len(suffix)]
|
|
65
|
+
break
|
|
66
|
+
parsed = urlparse(v)
|
|
67
|
+
if not parsed.netloc:
|
|
68
|
+
raise ValueError(f"服务器地址不合法:{value}")
|
|
69
|
+
return v
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Tavisowms SDK 错误模型(与腾讯云 SDK 的 TencentCloudSDKError 对齐)。"""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class TavisowmsError(Exception):
|
|
5
|
+
"""所有接口错误统一抛这个类型。
|
|
6
|
+
|
|
7
|
+
status: HTTP 状态码,网络错误时为 0
|
|
8
|
+
code: 服务端业务码,如 KEY_INVALID / SCOPE_DENIED
|
|
9
|
+
hint: 给运维看的一句话处置建议
|
|
10
|
+
request_id: 服务端请求 id(排查时提供)
|
|
11
|
+
retryable: 是否可重试
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def __init__(self, message, status=0, code="", body=None, request_id="", hint="", retryable=False):
|
|
15
|
+
super().__init__(message)
|
|
16
|
+
self.message = message
|
|
17
|
+
self.status = status
|
|
18
|
+
self.code = code
|
|
19
|
+
self.body = body or {}
|
|
20
|
+
self.request_id = request_id
|
|
21
|
+
self.hint = hint
|
|
22
|
+
self.retryable = retryable
|
|
23
|
+
|
|
24
|
+
def __str__(self):
|
|
25
|
+
parts = [f"[{self.status}] {self.code or 'ERROR'}: {self.message}"]
|
|
26
|
+
if self.hint:
|
|
27
|
+
parts.append(f"({self.hint})")
|
|
28
|
+
if self.request_id:
|
|
29
|
+
parts.append(f" requestId={self.request_id}")
|
|
30
|
+
return "".join(parts)
|
|
31
|
+
|
|
32
|
+
def __repr__(self):
|
|
33
|
+
return f"TavisowmsError(status={self.status}, code={self.code!r}, message={self.message!r})"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _hint_for(status, code):
|
|
37
|
+
return {
|
|
38
|
+
"HTTPS_REQUIRED": "该密钥要求 HTTPS,把 base_url 改成 https:// 开头",
|
|
39
|
+
"IP_NOT_ALLOWED": "当前出口 IP 不在密钥白名单,去Tavisowms 后台加白名单",
|
|
40
|
+
"SCOPE_DENIED": "密钥缺少这个操作需要的权限(scope)",
|
|
41
|
+
"KEY_INVALID": "密钥无效或已过期,去Tavisowms 后台重新生成",
|
|
42
|
+
}.get(code) or {
|
|
43
|
+
401: "密钥无效或已过期",
|
|
44
|
+
403: "密钥没有权限,或访问了不允许的仓库",
|
|
45
|
+
404: "接口不存在:确认服务端版本支持 /api/v1/open",
|
|
46
|
+
429: "触发限流,稍后重试",
|
|
47
|
+
}.get(status, "")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def from_response(status, body):
|
|
51
|
+
"""把服务端的错误体翻译成 TavisowmsError。"""
|
|
52
|
+
body = body or {}
|
|
53
|
+
code = str(body.get("code") or body.get("error_code") or "")
|
|
54
|
+
message = str(body.get("error") or body.get("message") or f"HTTP {status}")
|
|
55
|
+
return TavisowmsError(
|
|
56
|
+
message,
|
|
57
|
+
status=status,
|
|
58
|
+
code=code,
|
|
59
|
+
body=body,
|
|
60
|
+
request_id=str(body.get("requestId") or body.get("request_id") or ""),
|
|
61
|
+
hint=_hint_for(status, code),
|
|
62
|
+
retryable=status == 429 or status >= 500,
|
|
63
|
+
)
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""请求/响应模型。字段按Tavisowms 开放接口的实际入参命名,保持与 JSON 一致。"""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field, asdict
|
|
4
|
+
from typing import Any, Dict, List, Optional
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _drop_none(d):
|
|
8
|
+
return {k: v for k, v in d.items() if v is not None}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class StockItem:
|
|
13
|
+
"""出入库明细行。"""
|
|
14
|
+
product_id: Any = None
|
|
15
|
+
quantity: float = 0
|
|
16
|
+
lot_number: Optional[str] = None
|
|
17
|
+
box_code: Optional[str] = None
|
|
18
|
+
sku_variant_id: Any = None
|
|
19
|
+
cost_price: Optional[float] = None
|
|
20
|
+
remark: Optional[str] = None
|
|
21
|
+
|
|
22
|
+
def to_payload(self):
|
|
23
|
+
return _drop_none({
|
|
24
|
+
"productId": self.product_id,
|
|
25
|
+
"quantity": self.quantity,
|
|
26
|
+
"lotNumber": self.lot_number,
|
|
27
|
+
"boxCode": self.box_code,
|
|
28
|
+
"skuVariantId": self.sku_variant_id,
|
|
29
|
+
"costPrice": self.cost_price,
|
|
30
|
+
"remark": self.remark,
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class StockInRequest:
|
|
36
|
+
"""入库请求。autoPost=True 表示建单即过账(加库存)。"""
|
|
37
|
+
warehouse_id: Any = None
|
|
38
|
+
items: List[StockItem] = field(default_factory=list)
|
|
39
|
+
type: Optional[str] = None
|
|
40
|
+
supplier_id: Any = None
|
|
41
|
+
remark: Optional[str] = None
|
|
42
|
+
auto_post: bool = True
|
|
43
|
+
idempotency_key: Optional[str] = None
|
|
44
|
+
|
|
45
|
+
def to_payload(self):
|
|
46
|
+
return _drop_none({
|
|
47
|
+
"warehouseId": self.warehouse_id,
|
|
48
|
+
"type": self.type,
|
|
49
|
+
"supplierId": self.supplier_id,
|
|
50
|
+
"remark": self.remark,
|
|
51
|
+
"autoPost": self.auto_post,
|
|
52
|
+
"items": [i.to_payload() for i in self.items],
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass
|
|
57
|
+
class StockOutRequest:
|
|
58
|
+
"""出库请求。type: SALE/PICK/RETURN/TRANSFER/MAINTAIN/REPLACE/OTHER。"""
|
|
59
|
+
warehouse_id: Any = None
|
|
60
|
+
items: List[StockItem] = field(default_factory=list)
|
|
61
|
+
type: str = "SALE"
|
|
62
|
+
customer_id: Any = None
|
|
63
|
+
remark: Optional[str] = None
|
|
64
|
+
auto_post: bool = True
|
|
65
|
+
idempotency_key: Optional[str] = None
|
|
66
|
+
|
|
67
|
+
def to_payload(self):
|
|
68
|
+
return _drop_none({
|
|
69
|
+
"warehouseId": self.warehouse_id,
|
|
70
|
+
"type": self.type,
|
|
71
|
+
"customerId": self.customer_id,
|
|
72
|
+
"remark": self.remark,
|
|
73
|
+
"autoPost": self.auto_post,
|
|
74
|
+
"items": [i.to_payload() for i in self.items],
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass
|
|
79
|
+
class TransferRequest:
|
|
80
|
+
from_warehouse_id: Any = None
|
|
81
|
+
to_warehouse_id: Any = None
|
|
82
|
+
items: List[StockItem] = field(default_factory=list)
|
|
83
|
+
remark: Optional[str] = None
|
|
84
|
+
auto_post: bool = False
|
|
85
|
+
idempotency_key: Optional[str] = None
|
|
86
|
+
|
|
87
|
+
def to_payload(self):
|
|
88
|
+
return _drop_none({
|
|
89
|
+
"fromWarehouseId": self.from_warehouse_id,
|
|
90
|
+
"toWarehouseId": self.to_warehouse_id,
|
|
91
|
+
"remark": self.remark,
|
|
92
|
+
"autoPost": self.auto_post,
|
|
93
|
+
"items": [i.to_payload() for i in self.items],
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass
|
|
98
|
+
class StocktakeRequest:
|
|
99
|
+
warehouse_id: Any = None
|
|
100
|
+
items: List[Dict[str, Any]] = field(default_factory=list)
|
|
101
|
+
type: Optional[str] = None
|
|
102
|
+
remark: Optional[str] = None
|
|
103
|
+
idempotency_key: Optional[str] = None
|
|
104
|
+
|
|
105
|
+
def to_payload(self):
|
|
106
|
+
return _drop_none({
|
|
107
|
+
"warehouseId": self.warehouse_id,
|
|
108
|
+
"type": self.type,
|
|
109
|
+
"remark": self.remark,
|
|
110
|
+
"items": self.items,
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass
|
|
115
|
+
class ProductCreateRequest:
|
|
116
|
+
code: str = ""
|
|
117
|
+
name: str = ""
|
|
118
|
+
barcode: Optional[str] = None
|
|
119
|
+
unit: Optional[str] = None
|
|
120
|
+
category: Optional[str] = None
|
|
121
|
+
category_id: Any = None
|
|
122
|
+
brand: Optional[str] = None
|
|
123
|
+
model: Optional[str] = None
|
|
124
|
+
safety_stock: Optional[float] = None
|
|
125
|
+
default_cost: Optional[float] = None
|
|
126
|
+
enable_batch: Optional[bool] = None
|
|
127
|
+
enable_serial: Optional[bool] = None
|
|
128
|
+
remark: Optional[str] = None
|
|
129
|
+
idempotency_key: Optional[str] = None
|
|
130
|
+
|
|
131
|
+
def to_payload(self):
|
|
132
|
+
return _drop_none({
|
|
133
|
+
"code": self.code,
|
|
134
|
+
"name": self.name,
|
|
135
|
+
"barcode": self.barcode,
|
|
136
|
+
"unit": self.unit,
|
|
137
|
+
"category": self.category,
|
|
138
|
+
"categoryId": self.category_id,
|
|
139
|
+
"brand": self.brand,
|
|
140
|
+
"model": self.model,
|
|
141
|
+
"safetyStock": self.safety_stock,
|
|
142
|
+
"defaultCost": self.default_cost,
|
|
143
|
+
"enableBatch": self.enable_batch,
|
|
144
|
+
"enableSerial": self.enable_serial,
|
|
145
|
+
"remark": self.remark,
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@dataclass
|
|
150
|
+
class PartnerCreateRequest:
|
|
151
|
+
"""type: customer | supplier"""
|
|
152
|
+
code: str = ""
|
|
153
|
+
name: str = ""
|
|
154
|
+
type: str = "customer"
|
|
155
|
+
contact: Optional[str] = None
|
|
156
|
+
phone: Optional[str] = None
|
|
157
|
+
email: Optional[str] = None
|
|
158
|
+
address: Optional[str] = None
|
|
159
|
+
remark: Optional[str] = None
|
|
160
|
+
idempotency_key: Optional[str] = None
|
|
161
|
+
|
|
162
|
+
def to_payload(self):
|
|
163
|
+
return _drop_none({
|
|
164
|
+
"code": self.code,
|
|
165
|
+
"name": self.name,
|
|
166
|
+
"type": self.type,
|
|
167
|
+
"contact": self.contact,
|
|
168
|
+
"phone": self.phone,
|
|
169
|
+
"email": self.email,
|
|
170
|
+
"address": self.address,
|
|
171
|
+
"remark": self.remark,
|
|
172
|
+
})
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@dataclass
|
|
176
|
+
class WarehouseCreateRequest:
|
|
177
|
+
code: str = ""
|
|
178
|
+
name: str = ""
|
|
179
|
+
address: Optional[str] = None
|
|
180
|
+
shelves: Optional[int] = None
|
|
181
|
+
lies: Optional[int] = None
|
|
182
|
+
pais: Optional[int] = None
|
|
183
|
+
weis: Optional[int] = None
|
|
184
|
+
idempotency_key: Optional[str] = None
|
|
185
|
+
|
|
186
|
+
def to_payload(self):
|
|
187
|
+
return _drop_none({
|
|
188
|
+
"code": self.code,
|
|
189
|
+
"name": self.name,
|
|
190
|
+
"address": self.address,
|
|
191
|
+
"shelves": self.shelves,
|
|
192
|
+
"lies": self.lies,
|
|
193
|
+
"pais": self.pais,
|
|
194
|
+
"weis": self.weis,
|
|
195
|
+
})
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tavisowms-sdk
|
|
3
|
+
Version: 1.3.1
|
|
4
|
+
Summary: Tavisowms开放接口 Python SDK
|
|
5
|
+
Author: xiao yue
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/Taviso-inc/Tavisowms-SDK
|
|
8
|
+
Keywords: tavisowms,wms,warehouse,sdk,inventory
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Topic :: Office/Business :: Financial :: Accounting
|
|
12
|
+
Classifier: Typing :: Typed
|
|
13
|
+
Requires-Python: >=3.8
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# tavisowms-sdk(Python)
|
|
17
|
+
|
|
18
|
+
Tavisowms 开放接口的 Python SDK,只用标准库。
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install ./python
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from tavisowms import Client, Credential
|
|
26
|
+
|
|
27
|
+
client = Client(Credential("TVS-SDK_xxx:WMS-Taviso-xxx", "https://wms.example.com"))
|
|
28
|
+
print(client.me()["data"]["name"])
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
要求 Python ≥ 3.8。完整接口清单与场景配方见 [SDK 手册](../docs/MANUAL.md)。
|
|
32
|
+
|
|
33
|
+
Apache License 2.0。
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
tavisowms/__init__.py
|
|
4
|
+
tavisowms/_endpoints.py
|
|
5
|
+
tavisowms/client.py
|
|
6
|
+
tavisowms/credential.py
|
|
7
|
+
tavisowms/errors.py
|
|
8
|
+
tavisowms/models.py
|
|
9
|
+
tavisowms_sdk.egg-info/PKG-INFO
|
|
10
|
+
tavisowms_sdk.egg-info/SOURCES.txt
|
|
11
|
+
tavisowms_sdk.egg-info/dependency_links.txt
|
|
12
|
+
tavisowms_sdk.egg-info/top_level.txt
|
|
13
|
+
tests/test_client.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
tavisowms
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import threading
|
|
3
|
+
import unittest
|
|
4
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
5
|
+
|
|
6
|
+
from tavisowms import Client, Credential, StockInRequest, StockItem, TavisowmsError
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Handler(BaseHTTPRequestHandler):
|
|
10
|
+
hits = 0
|
|
11
|
+
fail_once = False
|
|
12
|
+
last_idem = ""
|
|
13
|
+
|
|
14
|
+
def log_message(self, *args):
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
def _send(self, code, body):
|
|
18
|
+
raw = json.dumps(body).encode()
|
|
19
|
+
self.send_response(code)
|
|
20
|
+
self.send_header("content-type", "application/json")
|
|
21
|
+
self.send_header("content-length", str(len(raw)))
|
|
22
|
+
self.end_headers()
|
|
23
|
+
self.wfile.write(raw)
|
|
24
|
+
|
|
25
|
+
def do_GET(self):
|
|
26
|
+
auth = self.headers.get("authorization", "")
|
|
27
|
+
path = self.path.split("?")[0]
|
|
28
|
+
if not auth.startswith("Bearer tw_live_good"):
|
|
29
|
+
if path.endswith("/products") and Handler.fail_once:
|
|
30
|
+
Handler.fail_once = False
|
|
31
|
+
return self._send(500, {"error": "boom"})
|
|
32
|
+
return self._send(401, {"error": "密钥无效", "code": "KEY_INVALID"})
|
|
33
|
+
Handler.hits += 1
|
|
34
|
+
if path.endswith("/me"):
|
|
35
|
+
return self._send(200, {"name": "华东仓作业密钥", "scopes": ["product:read", "stock:write"]})
|
|
36
|
+
if path.endswith("/products"):
|
|
37
|
+
q = self.path.split("?", 1)[1] if "?" in self.path else ""
|
|
38
|
+
page = int(dict(p.split("=") for p in q.split("&") if "=" in p).get("page", 1))
|
|
39
|
+
size = int(dict(p.split("=") for p in q.split("&") if "=" in p).get("pageSize", 2))
|
|
40
|
+
all_items = [{"id": str(i), "code": f"P{i}"} for i in range(1, 6)]
|
|
41
|
+
return self._send(200, {"items": all_items[(page - 1) * size: page * size], "total": 5})
|
|
42
|
+
if path.endswith("/inventory"):
|
|
43
|
+
return self._send(200, {"items": [{"onHand": 10, "available": 8}, {"onHand": 2, "available": 2}], "total": 2})
|
|
44
|
+
if path.endswith("/warehouses"):
|
|
45
|
+
return self._send(200, {"items": [{"id": "1", "name": "上海一号仓", "zones": [
|
|
46
|
+
{"code": "A", "locations": [{"id": "11", "code": "01-02-03"}]}]}]})
|
|
47
|
+
return self._send(404, {"error": "not found"})
|
|
48
|
+
|
|
49
|
+
def do_POST(self):
|
|
50
|
+
Handler.hits += 1
|
|
51
|
+
Handler.last_idem = self.headers.get("idempotency-key", "")
|
|
52
|
+
length = int(self.headers.get("content-length", 0))
|
|
53
|
+
body = json.loads(self.rfile.read(length) or b"{}")
|
|
54
|
+
if not body.get("warehouseId"):
|
|
55
|
+
return self._send(400, {"error": "缺少 warehouseId"})
|
|
56
|
+
status = "POSTED" if body.get("autoPost") else "DRAFT"
|
|
57
|
+
return self._send(200, {"success": True, "orderNo": "IN-1", "status": status})
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class SDLTest(unittest.TestCase):
|
|
61
|
+
@classmethod
|
|
62
|
+
def setUpClass(cls):
|
|
63
|
+
cls.server = HTTPServer(("127.0.0.1", 0), Handler)
|
|
64
|
+
cls.port = cls.server.server_address[1]
|
|
65
|
+
threading.Thread(target=cls.server.serve_forever, daemon=True).start()
|
|
66
|
+
cls.base = f"http://127.0.0.1:{cls.port}"
|
|
67
|
+
|
|
68
|
+
@classmethod
|
|
69
|
+
def tearDownClass(cls):
|
|
70
|
+
cls.server.shutdown()
|
|
71
|
+
|
|
72
|
+
def client(self, key="tw_live_goodkey", retries=1):
|
|
73
|
+
return Client(Credential(key, self.base + "/api/v1/open"), retries=retries)
|
|
74
|
+
|
|
75
|
+
def test_me(self):
|
|
76
|
+
me = self.client().me()
|
|
77
|
+
self.assertEqual(me["name"], "华东仓作业密钥")
|
|
78
|
+
self.assertIn("stock:write", me["scopes"])
|
|
79
|
+
|
|
80
|
+
def test_base_url_normalized(self):
|
|
81
|
+
self.assertEqual(self.client().credential.base_url, self.base)
|
|
82
|
+
|
|
83
|
+
def test_pagination_all(self):
|
|
84
|
+
items = self.client().all(self.client().products, {"pageSize": 2})
|
|
85
|
+
self.assertEqual(len(items), 5)
|
|
86
|
+
|
|
87
|
+
def test_available_sum(self):
|
|
88
|
+
self.assertEqual(self.client().available(1, 2), 10.0)
|
|
89
|
+
|
|
90
|
+
def test_stock_in_idempotency_and_post(self):
|
|
91
|
+
c = self.client()
|
|
92
|
+
r = c.stock_in(StockInRequest(warehouse_id=1, items=[StockItem(product_id=12, quantity=3)], auto_post=True))
|
|
93
|
+
self.assertEqual(r["status"], "POSTED")
|
|
94
|
+
self.assertGreaterEqual(len(Handler.last_idem), 8)
|
|
95
|
+
|
|
96
|
+
def test_locations_four_segments(self):
|
|
97
|
+
rows = self.client().locations()
|
|
98
|
+
self.assertEqual(rows[0]["code"], "A-01-02-03")
|
|
99
|
+
|
|
100
|
+
def test_401_maps_to_error_with_hint(self):
|
|
101
|
+
c = Client(Credential("tw_live_bad", self.base), retries=0)
|
|
102
|
+
with self.assertRaises(TavisowmsError) as ctx:
|
|
103
|
+
c.me()
|
|
104
|
+
self.assertEqual(ctx.exception.status, 401)
|
|
105
|
+
self.assertIn("密钥", ctx.exception.hint)
|
|
106
|
+
|
|
107
|
+
def test_5xx_retry(self):
|
|
108
|
+
Handler.fail_once = True
|
|
109
|
+
c = self.client(retries=2)
|
|
110
|
+
res = c.products(pageSize=2)
|
|
111
|
+
self.assertEqual(res["total"], 5)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
if __name__ == "__main__":
|
|
115
|
+
unittest.main(verbosity=2)
|