yuncang-sdk 1.1.0__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.
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: yuncang-sdk
3
+ Version: 1.1.0
4
+ Summary: 云仓(YunCang)开放接口 Python SDK
5
+ Author: xiao yue
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/yuejiaxinabc/cloud-warehouse-sdk
8
+ Keywords: yuncang,wms,warehouse,sdk
9
+ Requires-Python: >=3.8
10
+ Description-Content-Type: text/markdown
11
+
12
+ # 云仓 Python SDK
13
+
14
+ ```bash
15
+ pip install ./python # 或 pip install -e ./python
16
+ ```
17
+
18
+ ```python
19
+ from yuncang import Client, Credential, StockInRequest, StockItem
20
+
21
+ client = Client(Credential("yc_live_xxx", "https://yc.example.com"), timeout=20, retries=2)
22
+
23
+ print(client.me()["name"], client.me()["scopes"])
24
+
25
+ # 入库并直接过账
26
+ r = client.stock_in(StockInRequest(
27
+ warehouse_id=1,
28
+ auto_post=True,
29
+ items=[StockItem(product_id=12, quantity=20, lot_number="B20261115-A1", box_code="A-01-02-03")],
30
+ ))
31
+ print(r["orderNo"], r["status"]) # IN-20261115-001 POSTED
32
+
33
+ # 出库(库存不足时 status 仍是 DRAFT,原因见 postError)
34
+ out = client.stock_out(StockOutRequest(warehouse_id=1, type="SALE", auto_post=True,
35
+ items=[StockItem(product_id=12, quantity=3)]))
36
+
37
+ # 分页
38
+ for page in client.paginate(client.inventory, {"warehouseId": 1}):
39
+ print(page["page"], len(page["items"]), page["total"])
40
+ ```
41
+
42
+ 测试:`python -m unittest discover -s tests -v`(8 项,本地 mock server)。
@@ -0,0 +1,31 @@
1
+ # 云仓 Python SDK
2
+
3
+ ```bash
4
+ pip install ./python # 或 pip install -e ./python
5
+ ```
6
+
7
+ ```python
8
+ from yuncang import Client, Credential, StockInRequest, StockItem
9
+
10
+ client = Client(Credential("yc_live_xxx", "https://yc.example.com"), timeout=20, retries=2)
11
+
12
+ print(client.me()["name"], client.me()["scopes"])
13
+
14
+ # 入库并直接过账
15
+ r = client.stock_in(StockInRequest(
16
+ warehouse_id=1,
17
+ auto_post=True,
18
+ items=[StockItem(product_id=12, quantity=20, lot_number="B20261115-A1", box_code="A-01-02-03")],
19
+ ))
20
+ print(r["orderNo"], r["status"]) # IN-20261115-001 POSTED
21
+
22
+ # 出库(库存不足时 status 仍是 DRAFT,原因见 postError)
23
+ out = client.stock_out(StockOutRequest(warehouse_id=1, type="SALE", auto_post=True,
24
+ items=[StockItem(product_id=12, quantity=3)]))
25
+
26
+ # 分页
27
+ for page in client.paginate(client.inventory, {"warehouseId": 1}):
28
+ print(page["page"], len(page["items"]), page["total"])
29
+ ```
30
+
31
+ 测试:`python -m unittest discover -s tests -v`(8 项,本地 mock server)。
@@ -0,0 +1,19 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "yuncang-sdk"
7
+ version = "1.1.0"
8
+ description = "云仓(YunCang)开放接口 Python SDK"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "Apache-2.0"
12
+ authors = [{ name = "xiao yue" }]
13
+ keywords = ["yuncang", "wms", "warehouse", "sdk"]
14
+
15
+ [project.urls]
16
+ Homepage = "https://github.com/yuejiaxinabc/cloud-warehouse-sdk"
17
+
18
+ [tool.setuptools.packages.find]
19
+ include = ["yuncang*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,115 @@
1
+ import json
2
+ import threading
3
+ import unittest
4
+ from http.server import BaseHTTPRequestHandler, HTTPServer
5
+
6
+ from yuncang import Client, Credential, StockInRequest, StockItem, YunCangError
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 yc_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="yc_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("yc_live_bad", self.base), retries=0)
102
+ with self.assertRaises(YunCangError) 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)
@@ -0,0 +1,36 @@
1
+ """云仓 Python SDK。
2
+
3
+ from yuncang import Client, Credential
4
+ client = Client(Credential("yc_live_xxx", "https://yc.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 YunCangError
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.1.0"
23
+ __all__ = [
24
+ "Client",
25
+ "Credential",
26
+ "YunCangError",
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,266 @@
1
+ """云仓客户端(对标腾讯云 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 YunCangError, 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 = "yuncang-sdk-python/1.1.0"
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
+ """云仓开放接口客户端。
74
+
75
+ >>> client = Client(Credential("yc_live_xxx", "https://yc.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):
92
+ url = self.credential.base_url + API_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 = YunCangError(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 YunCangError("请求失败", 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
+ def paginate(self, fn, params=None, page_size=200, max_pages=200):
146
+ """生成器:逐页产出 {page, items, total}。"""
147
+ params = dict(params or {})
148
+ for page in range(1, max_pages + 1):
149
+ res = fn(**{**params, "page": page, "pageSize": page_size})
150
+ items = (res or {}).get("items") or []
151
+ yield {"page": page, "items": items, "total": (res or {}).get("total", 0)}
152
+ if len(items) < page_size:
153
+ return
154
+
155
+ def all(self, fn, params=None, page_size=200, max_pages=200):
156
+ """一次拉全所有页。"""
157
+ out = []
158
+ for chunk in self.paginate(fn, params, page_size, max_pages):
159
+ out.extend(chunk["items"])
160
+ return out
161
+
162
+ # ------------------------------------------------------------ 只读接口
163
+ def me(self):
164
+ """当前密钥身份、scope 与仓库范围。"""
165
+ return self._request("/me")
166
+
167
+ def meta(self, **query):
168
+ return self._request("/meta", query=query)
169
+
170
+ def products(self, **query):
171
+ return self._request("/products", query=query)
172
+
173
+ def create_product(self, req: ProductCreateRequest):
174
+ return self._request("/products", method="POST", body=req.to_payload(),
175
+ idempotency_key=req.idempotency_key)
176
+
177
+ def warehouses(self, with_locations=False):
178
+ return self._request("/warehouses", query={"withLocations": 1} if with_locations else None)
179
+
180
+ def create_warehouse(self, req: WarehouseCreateRequest):
181
+ return self._request("/warehouses", method="POST", body=req.to_payload(),
182
+ idempotency_key=req.idempotency_key)
183
+
184
+ def locations(self, warehouse_id=None):
185
+ """货位拍平成「货架-排-列-位」,直接可做下拉框。"""
186
+ res = self.warehouses(with_locations=True)
187
+ rows = (res or {}).get("items") or res or []
188
+ out = []
189
+ for wh in rows:
190
+ if warehouse_id and str(wh.get("id")) != str(warehouse_id):
191
+ continue
192
+ for zone in wh.get("zones") or []:
193
+ zc = str(zone.get("code") or zone.get("name") or "")
194
+ for loc in zone.get("locations") or zone.get("boxes") or []:
195
+ lc = str(loc.get("code") or "")
196
+ full = lc if (not zc or lc.startswith(zc + "-")) else f"{zc}-{lc}"
197
+ out.append({
198
+ "id": str(loc.get("id")),
199
+ "code": full,
200
+ "name": loc.get("name") or "",
201
+ "warehouse_id": str(wh.get("id")),
202
+ "warehouse_name": wh.get("name") or "",
203
+ })
204
+ return out
205
+
206
+ def partners(self, **query):
207
+ return self._request("/partners", query=query)
208
+
209
+ def create_partner(self, req: PartnerCreateRequest):
210
+ return self._request("/partners", method="POST", body=req.to_payload(),
211
+ idempotency_key=req.idempotency_key)
212
+
213
+ def inventory(self, **query):
214
+ return self._request("/inventory", query=query)
215
+
216
+ def available(self, warehouse_id, product_id):
217
+ res = self.inventory(warehouseId=warehouse_id, productId=product_id, pageSize=50)
218
+ total = 0.0
219
+ for row in (res or {}).get("items") or []:
220
+ total += float(row.get("available", row.get("onHand", 0)) or 0)
221
+ return total
222
+
223
+ def lots(self, **query):
224
+ return self._request("/lots", query=query)
225
+
226
+ def movements(self, **query):
227
+ return self._request("/movements", query=query)
228
+
229
+ def orders(self, **query):
230
+ return self._request("/orders", query=query)
231
+
232
+ def low_stock(self, **query):
233
+ return self._request("/reports/low-stock", query=query)
234
+
235
+ def stock_summary(self, **query):
236
+ return self._request("/reports/stock-summary", query=query)
237
+
238
+ def stock_value(self, **query):
239
+ return self._request("/reports/stock-value", query=query)
240
+
241
+ # ------------------------------------------------------------ 写入接口
242
+ def stock_in(self, req: StockInRequest):
243
+ """入库;auto_post=True 建单即过账。返回里 postError 非空表示没过去,单据是草稿。"""
244
+ return self._request("/stock-in", method="POST", body=req.to_payload(),
245
+ idempotency_key=req.idempotency_key)
246
+
247
+ def stock_out(self, req: StockOutRequest):
248
+ return self._request("/stock-out", method="POST", body=req.to_payload(),
249
+ idempotency_key=req.idempotency_key)
250
+
251
+ def transfer(self, req: TransferRequest):
252
+ return self._request("/transfer", method="POST", body=req.to_payload(),
253
+ idempotency_key=req.idempotency_key)
254
+
255
+ def stocktake(self, req: StocktakeRequest):
256
+ return self._request("/stocktake", method="POST", body=req.to_payload(),
257
+ idempotency_key=req.idempotency_key)
258
+
259
+ def __repr__(self):
260
+ return f"Client(base_url={self.credential.base_url!r}, key={self.credential.masked()})"
261
+
262
+
263
+ def _uuid():
264
+ alphabet = string.hexdigits.lower()[:16]
265
+ raw = "".join(random.choice(alphabet) for _ in range(32))
266
+ return f"{raw[:8]}-{raw[8:12]}-{raw[12:16]}-{raw[16:20]}-{raw[20:]}"
@@ -0,0 +1,52 @@
1
+ """凭证:云仓用 API 密钥鉴权(Bearer),比腾讯云的 SecretId/SecretKey 简单一层。"""
2
+
3
+ from dataclasses import dataclass
4
+ from urllib.parse import urlparse
5
+
6
+
7
+ @dataclass
8
+ class Credential:
9
+ """一把云仓密钥 + 服务端地址。
10
+
11
+ >>> Credential.from_url("https://yc.example.com/api/v1/open", "yc_live_xxx")
12
+ """
13
+
14
+ api_key: str
15
+ base_url: str = "http://127.0.0.1:3000"
16
+
17
+ def __post_init__(self):
18
+ if not self.api_key:
19
+ raise ValueError("api_key 不能为空(云仓后台 → 设置 → API 管理 生成)")
20
+ self.base_url = normalize_base_url(self.base_url)
21
+
22
+ @classmethod
23
+ def from_url(cls, base_url, api_key):
24
+ return cls(api_key=api_key, base_url=base_url)
25
+
26
+ def headers(self):
27
+ return {
28
+ "Authorization": f"Bearer {self.api_key}",
29
+ "Accept": "application/json",
30
+ }
31
+
32
+ def masked(self):
33
+ """日志里用,别把密钥打全。"""
34
+ k = self.api_key
35
+ return k[:10] + "…" + k[-4:] if len(k) > 16 else "yc_…"
36
+
37
+
38
+ def normalize_base_url(value):
39
+ v = str(value or "").strip()
40
+ if not v:
41
+ raise ValueError("缺少服务器地址 base_url")
42
+ if not v.lower().startswith(("http://", "https://")):
43
+ v = "https://" + v
44
+ v = v.rstrip("/")
45
+ for suffix in ("/api/v1/open", "/api/v1/desktop", "/api/v1", "/api"):
46
+ if v.lower().endswith(suffix):
47
+ v = v[: -len(suffix)]
48
+ break
49
+ parsed = urlparse(v)
50
+ if not parsed.netloc:
51
+ raise ValueError(f"服务器地址不合法:{value}")
52
+ return v
@@ -0,0 +1,63 @@
1
+ """云仓 SDK 错误模型(与腾讯云 SDK 的 TencentCloudSDKError 对齐)。"""
2
+
3
+
4
+ class YunCangError(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"YunCangError(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 不在密钥白名单,去云仓后台加白名单",
40
+ "SCOPE_DENIED": "密钥缺少这个操作需要的权限(scope)",
41
+ "KEY_INVALID": "密钥无效或已过期,去云仓后台重新生成",
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
+ """把服务端的错误体翻译成 YunCangError。"""
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 YunCangError(
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
+ """请求/响应模型。字段按云仓开放接口的实际入参命名,保持与 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,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: yuncang-sdk
3
+ Version: 1.1.0
4
+ Summary: 云仓(YunCang)开放接口 Python SDK
5
+ Author: xiao yue
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/yuejiaxinabc/cloud-warehouse-sdk
8
+ Keywords: yuncang,wms,warehouse,sdk
9
+ Requires-Python: >=3.8
10
+ Description-Content-Type: text/markdown
11
+
12
+ # 云仓 Python SDK
13
+
14
+ ```bash
15
+ pip install ./python # 或 pip install -e ./python
16
+ ```
17
+
18
+ ```python
19
+ from yuncang import Client, Credential, StockInRequest, StockItem
20
+
21
+ client = Client(Credential("yc_live_xxx", "https://yc.example.com"), timeout=20, retries=2)
22
+
23
+ print(client.me()["name"], client.me()["scopes"])
24
+
25
+ # 入库并直接过账
26
+ r = client.stock_in(StockInRequest(
27
+ warehouse_id=1,
28
+ auto_post=True,
29
+ items=[StockItem(product_id=12, quantity=20, lot_number="B20261115-A1", box_code="A-01-02-03")],
30
+ ))
31
+ print(r["orderNo"], r["status"]) # IN-20261115-001 POSTED
32
+
33
+ # 出库(库存不足时 status 仍是 DRAFT,原因见 postError)
34
+ out = client.stock_out(StockOutRequest(warehouse_id=1, type="SALE", auto_post=True,
35
+ items=[StockItem(product_id=12, quantity=3)]))
36
+
37
+ # 分页
38
+ for page in client.paginate(client.inventory, {"warehouseId": 1}):
39
+ print(page["page"], len(page["items"]), page["total"])
40
+ ```
41
+
42
+ 测试:`python -m unittest discover -s tests -v`(8 项,本地 mock server)。
@@ -0,0 +1,13 @@
1
+ README.md
2
+ pyproject.toml
3
+ tests/test_client.py
4
+ yuncang/__init__.py
5
+ yuncang/_endpoints.py
6
+ yuncang/client.py
7
+ yuncang/credential.py
8
+ yuncang/errors.py
9
+ yuncang/models.py
10
+ yuncang_sdk.egg-info/PKG-INFO
11
+ yuncang_sdk.egg-info/SOURCES.txt
12
+ yuncang_sdk.egg-info/dependency_links.txt
13
+ yuncang_sdk.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ yuncang