docges-api-py 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.
@@ -0,0 +1,69 @@
1
+ """DocGes API Python client — async, typed, tested."""
2
+
3
+ from docges_api_py.client import AsyncDocGes, Endpoints, DocGesError, AuthenticationError, RequestError
4
+ from docges_api_py.models import (
5
+ # Auth
6
+ AuthRequest,
7
+ AuthResponse,
8
+ # Document
9
+ Document,
10
+ # Requests
11
+ ReqData,
12
+ ReqAuthData,
13
+ FileUpload,
14
+ ReqUpload,
15
+ SearchFilterValue,
16
+ SearchDateValue,
17
+ ReqSearchContent,
18
+ ReqCreateCategory,
19
+ ReqRenameCategory,
20
+ ReqDeleteCategory,
21
+ ReqMoveContent,
22
+ ReqUpdateContent,
23
+ ReqRemoveContent,
24
+ # Responses
25
+ ResCat,
26
+ ResCatItem,
27
+ ResSearch,
28
+ ResSearchItem,
29
+ ResFileDownload,
30
+ FileDownloadResponse,
31
+ ResultActionModel,
32
+ )
33
+
34
+ __version__ = "0.2.0" # Phase 5: All endpoints implemented
35
+ __all__ = [
36
+ # Client
37
+ "AsyncDocGes",
38
+ "Endpoints",
39
+ "DocGesError",
40
+ "AuthenticationError",
41
+ "RequestError",
42
+ # Auth
43
+ "AuthRequest",
44
+ "AuthResponse",
45
+ # Document
46
+ "Document",
47
+ # Requests
48
+ "ReqData",
49
+ "ReqAuthData",
50
+ "FileUpload",
51
+ "ReqUpload",
52
+ "SearchFilterValue",
53
+ "SearchDateValue",
54
+ "ReqSearchContent",
55
+ "ReqCreateCategory",
56
+ "ReqRenameCategory",
57
+ "ReqDeleteCategory",
58
+ "ReqMoveContent",
59
+ "ReqUpdateContent",
60
+ "ReqRemoveContent",
61
+ # Responses
62
+ "ResCat",
63
+ "ResCatItem",
64
+ "ResSearch",
65
+ "ResSearchItem",
66
+ "ResFileDownload",
67
+ "FileDownloadResponse",
68
+ "ResultActionModel",
69
+ ]
@@ -0,0 +1,416 @@
1
+ """AsyncDocGes client — Phase2 implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import time
7
+ from typing import Any
8
+
9
+ import httpx
10
+
11
+ from .models.auth import AuthRequest, AuthResponse
12
+ from .models.document import Document
13
+ from .models.responses import ResCat
14
+
15
+
16
+ class Endpoints:
17
+ """DocGes API endpoint paths."""
18
+
19
+ # Auth
20
+ auth_login = "/Auth/Login"
21
+
22
+ # Content - Tree
23
+ content_load_ini_cats = "/Content/LoadIniCats"
24
+ content_load_childs = "/Content/LoadChilds"
25
+
26
+ # Content - Upload/Download
27
+ content_download = "/Content/Download"
28
+ content_upload = "/Content/Upload"
29
+ content_upload_extended = "/Content/UploadExtended"
30
+
31
+ # Content - Search
32
+ content_search = "/Content/SearchContent"
33
+
34
+ # Content - Categories
35
+ content_create_category = "/Content/CreateCategory"
36
+ content_rename_category = "/Content/RenameCategory"
37
+ content_delete_category = "/Content/DeleteCategory"
38
+
39
+ # Content - Document Management
40
+ content_remove_document = "/Content/RemoveDocument"
41
+ content_remove_documents = "/Content/RemoveDocuments"
42
+ content_move = "/Content/Move"
43
+ content_update = "/Content/Update"
44
+
45
+
46
+ class DocGesError(Exception):
47
+ """Base exception for DocGes client errors."""
48
+
49
+
50
+ class AuthenticationError(DocGesError):
51
+ """Raised when authentication fails."""
52
+
53
+
54
+ class RequestError(DocGesError):
55
+ """Raised on HTTP or network errors."""
56
+
57
+
58
+ class AsyncDocGes:
59
+ """Async client for DocGes REST API.
60
+
61
+ Usage:
62
+ async with AsyncDocGes(base_url, user, pwd, appid) as client:
63
+ await client.auth()
64
+ # use client for API calls
65
+ """
66
+
67
+ def __init__(
68
+ self,
69
+ base_url: str,
70
+ user: str,
71
+ pwd: str,
72
+ appid: str,
73
+ *,
74
+ timeout: float = 30.0,
75
+ intents: int = 3,
76
+ token_ttl: int = 3600,
77
+ ) -> None:
78
+ self.base_url = base_url.rstrip("/")
79
+ self.user = user
80
+ self.pwd = pwd
81
+ self.appid = appid
82
+
83
+ self.timeout = timeout
84
+ self.intents = intents
85
+ self.token_ttl = token_ttl
86
+
87
+ self._token: str | None = None
88
+ self._token_expiry: float = 0.0
89
+ self._client: httpx.AsyncClient | None = None
90
+
91
+ # ------------------------------------------------------------------
92
+ # Client lifecycle
93
+ # ------------------------------------------------------------------
94
+
95
+ async def _get_client(self) -> httpx.AsyncClient:
96
+ if self._client is None:
97
+ self._client = httpx.AsyncClient(
98
+ base_url=self.base_url,
99
+ timeout=self.timeout,
100
+ headers={"Content-Type": "application/json"},
101
+ )
102
+ return self._client
103
+
104
+ async def close(self) -> None:
105
+ if self._client is not None:
106
+ await self._client.aclose()
107
+ self._client = None
108
+
109
+ async def __aenter__(self):
110
+ await self._get_client()
111
+ return self
112
+
113
+ async def __aexit__(self, exc_type, exc, tb):
114
+ await self.close()
115
+
116
+ # ------------------------------------------------------------------
117
+ # Auth
118
+ # ------------------------------------------------------------------
119
+
120
+ async def auth(self) -> AuthResponse:
121
+ """Authenticate against /Auth/Login and store the token."""
122
+ client = await self._get_client()
123
+ payload = AuthRequest(
124
+ username=self.user,
125
+ password=self.pwd,
126
+ appID=self.appid,
127
+ )
128
+
129
+ url = Endpoints.auth_login
130
+ try:
131
+ resp = await self.do_request(url, payload.model_dump(exclude_none=True))
132
+ except RequestError as e:
133
+ raise AuthenticationError(f"Authentication failed: {e}") from e
134
+
135
+ try:
136
+ auth_resp = AuthResponse(**resp)
137
+ except Exception as e:
138
+ raise AuthenticationError(f"Invalid auth response: {e}") from e
139
+
140
+ self._token = auth_resp.token
141
+ self._token_expiry = time.time() + self.token_ttl
142
+ return auth_resp
143
+
144
+ async def _ensure_token(self) -> str:
145
+ if self._token is None or time.time() >= self._token_expiry:
146
+ await self.auth()
147
+ assert self._token is not None
148
+ return self._token
149
+
150
+ # ------------------------------------------------------------------
151
+ # Generic request wrapper with retries
152
+ # ------------------------------------------------------------------
153
+
154
+ async def do_request(
155
+ self,
156
+ url: str,
157
+ payload: dict[str, Any],
158
+ ) -> dict[str, Any]:
159
+ """POST to `url` with `payload`, retrying up to `self.intents` times.
160
+
161
+ Raises:
162
+ RequestError: if all attempts fail.
163
+ """
164
+ client = await self._get_client()
165
+ last_exc: Exception | None = None
166
+
167
+ for attempt in range(1, self.intents + 1):
168
+ try:
169
+ resp = await client.post(url, json=payload)
170
+ resp.raise_for_status()
171
+ data = resp.json()
172
+ if data is None:
173
+ raise RequestError("Server returned null JSON")
174
+ return data
175
+ except (httpx.HTTPStatusError, httpx.RequestError, RequestError) as exc:
176
+ last_exc = exc
177
+ if attempt < self.intents:
178
+ # Exponential backoff: timeout * attempt (simplified)
179
+ await asyncio.sleep(self.timeout * attempt)
180
+
181
+ raise RequestError(
182
+ f"Request to {url} failed after {self.intents} attempts"
183
+ ) from last_exc
184
+
185
+ # ------------------------------------------------------------------
186
+ # Document endpoints (Phase 2)
187
+ # ------------------------------------------------------------------
188
+
189
+
190
+ # ------------------------------------------------------------------
191
+ # Document endpoints (Phase 2)
192
+ # ------------------------------------------------------------------
193
+
194
+ async def get_initial_cats(self) -> ResCat:
195
+ """Load initial categories for the user's warehouse."""
196
+ await self._ensure_token()
197
+
198
+ url = Endpoints.content_load_ini_cats
199
+ payload = {
200
+ "requestModel": {
201
+ "loginDocGesData": None,
202
+ "loginResponse": {"userInfo": {}, "wareHouseInfo": {}}
203
+ }
204
+ }
205
+ resp = await self.do_request(url, payload)
206
+ return ResCat.from_json(resp.get("result", {}))
207
+
208
+ async def get_cat_info(self, sid: str) -> ResCat:
209
+ """Load category details and its children by SID."""
210
+ await self._ensure_token()
211
+
212
+ url = Endpoints.content_load_childs
213
+ payload = {
214
+ "contenidoModel": {"SIDContenido": sid},
215
+ "requestModel": {
216
+ "loginDocGesData": None,
217
+ "loginResponse": {"userInfo": {}, "wareHouseInfo": {}}
218
+ }
219
+ }
220
+ resp = await self.do_request(url, payload)
221
+ return ResCat.from_json(resp.get("result", {}))
222
+
223
+ async def download_content(self, sid: str) -> "ResFileDownload":
224
+ """Download a document by SID. Returns ResFileDownload with base64 data."""
225
+ from .models.responses import ResFileDownload
226
+
227
+ await self._ensure_token()
228
+
229
+ url = Endpoints.content_download
230
+ payload = {
231
+ "contenidoModel": {"SIDContenido": sid},
232
+ "requestModel": {
233
+ "loginDocGesData": None,
234
+ "loginResponse": {"userInfo": {}, "wareHouseInfo": {}}
235
+ }
236
+ }
237
+ resp = await self.do_request(url, payload)
238
+ return ResFileDownload.from_json(resp)
239
+ # ------------------------------------------------------------------
240
+ # Upload & Search (Phase 2.3, 2.5)
241
+ # ------------------------------------------------------------------
242
+
243
+ async def upload_file(
244
+ self,
245
+ category_sid: str,
246
+ file_path: str,
247
+ erp_relation: str = "",
248
+ erp_property: str = "",
249
+ ) -> str:
250
+ """Upload a file to a category. Returns document SID."""
251
+ from .models.requests import FileUpload, ReqUpload
252
+ from .models.responses import ResultActionModel
253
+ import base64
254
+
255
+ await self._ensure_token()
256
+
257
+ # Read and base64-encode file
258
+ with open(file_path, "rb") as f:
259
+ file_data = base64.b64encode(f.read()).decode("utf-8")
260
+
261
+ file_upload = FileUpload(
262
+ fileData=file_data,
263
+ fileName=file_path.split("/")[-1],
264
+ SIDCategory=category_sid,
265
+ erpRelation=erp_relation,
266
+ erpProperty=erp_property,
267
+ )
268
+ payload = {
269
+ "fileModel": file_upload.model_dump(exclude_none=True),
270
+ "requestModel": {
271
+ "loginDocGesData": None,
272
+ "loginResponse": {"userInfo": {}, "wareHouseInfo": {}}
273
+ }
274
+ }
275
+ resp = await self.do_request(Endpoints.content_upload_extended, payload)
276
+ result = ResultActionModel(**resp)
277
+ if result.result:
278
+ return str(result.result)
279
+ raise RequestError(result.message)
280
+
281
+ async def search_content(
282
+ self,
283
+ field_values: list[dict] | None = None,
284
+ date_values: list[dict] | None = None,
285
+ ) -> "ResSearch":
286
+ """Search documents by field values."""
287
+ from .models.responses import ResSearch
288
+
289
+ await self._ensure_token()
290
+
291
+ payload = {
292
+ "fieldValues": field_values,
293
+ "dateValues": date_values,
294
+ "requestModel": {
295
+ "loginDocGesData": None,
296
+ "loginResponse": {"userInfo": {}, "wareHouseInfo": {}}
297
+ }
298
+ }
299
+ resp = await self.do_request(Endpoints.content_search, payload)
300
+ return ResSearch.from_json(resp)
301
+
302
+ # ------------------------------------------------------------------
303
+ # Category Management (Phase 2.6, 2.7, 2.8)
304
+ # ------------------------------------------------------------------
305
+
306
+ async def create_category(self, parent_sid: str, name: str) -> str:
307
+ """Create a subcategory. Returns new category SID."""
308
+ from .models.responses import ResultActionModel
309
+
310
+ await self._ensure_token()
311
+
312
+ payload = {
313
+ "parentSID": parent_sid,
314
+ "name": name,
315
+ "requestModel": {
316
+ "loginDocGesData": None,
317
+ "loginResponse": {"userInfo": {}, "wareHouseInfo": {}}
318
+ }
319
+ }
320
+ resp = await self.do_request(Endpoints.content_create_category, payload)
321
+ result = ResultActionModel(**resp)
322
+ if result.result:
323
+ return str(result.result)
324
+ raise RequestError(result.message)
325
+
326
+ async def rename_category(self, sid: str, new_name: str) -> bool:
327
+ """Rename a category. Returns True on success."""
328
+ await self._ensure_token()
329
+
330
+ payload = {
331
+ "SID": sid,
332
+ "name": new_name,
333
+ "requestModel": {
334
+ "loginDocGesData": None,
335
+ "loginResponse": {"userInfo": {}, "wareHouseInfo": {}}
336
+ }
337
+ }
338
+ resp = await self.do_request(Endpoints.content_rename_category, payload)
339
+ result = {"result": resp.get("result")}
340
+ return bool(result.get("result"))
341
+
342
+ async def delete_category(self, sid: str) -> bool:
343
+ """Delete a category. Returns True on success."""
344
+ await self._ensure_token()
345
+
346
+ payload = {
347
+ "SID": sid,
348
+ "requestModel": {
349
+ "loginDocGesData": None,
350
+ "loginResponse": {"userInfo": {}, "wareHouseInfo": {}}
351
+ }
352
+ }
353
+ resp = await self.do_request(Endpoints.content_delete_category, payload)
354
+ result = {"result": resp.get("result")}
355
+ return bool(result.get("result"))
356
+
357
+ # ------------------------------------------------------------------
358
+ # Document Management (Phase 2.9, 2.10, 2.11)
359
+ # ------------------------------------------------------------------
360
+
361
+ async def remove_document(self, sid: str) -> bool:
362
+ """Remove a single document. Returns True on success."""
363
+ await self._ensure_token()
364
+
365
+ payload = {
366
+ "contenidoModel": {"SIDContenido": sid},
367
+ "requestModel": {
368
+ "loginDocGesData": None,
369
+ "loginResponse": {"userInfo": {}, "wareHouseInfo": {}}
370
+ }
371
+ }
372
+ resp = await self.do_request(Endpoints.content_remove_document, payload)
373
+ result = {"result": resp.get("result")}
374
+ return bool(result.get("result"))
375
+
376
+ async def move_content(self, content_sid: str, destination_sid: str) -> bool:
377
+ """Move a document to another category. Returns True on success."""
378
+ await self._ensure_token()
379
+
380
+ payload = {
381
+ "contentSID": content_sid,
382
+ "destinationSID": destination_sid,
383
+ "requestModel": {
384
+ "loginDocGesData": None,
385
+ "loginResponse": {"userInfo": {}, "wareHouseInfo": {}}
386
+ }
387
+ }
388
+ resp = await self.do_request(Endpoints.content_move, payload)
389
+ result = {"result": resp.get("result")}
390
+ return bool(result.get("result"))
391
+
392
+ async def update_content(
393
+ self,
394
+ sid: str,
395
+ erp_relation: str = "",
396
+ erp_property: str = "",
397
+ ) -> str:
398
+ """Update document metadata. Returns document SID."""
399
+ await self._ensure_token()
400
+
401
+ payload = {
402
+ "contentModel": {"SID": sid, "RelacionGestion": erp_relation, "PropiedadGestion": erp_property},
403
+ "requestModel": {
404
+ "loginDocGesData": None,
405
+ "loginResponse": {"userInfo": {}, "wareHouseInfo": {}}
406
+ }
407
+ }
408
+ resp = await self.do_request(Endpoints.content_update, payload)
409
+ result = {"result": resp.get("result")}
410
+ return str(result.get("result")) if result.get("result") else ""
411
+
412
+
413
+ async def get_document(self, document_id: str) -> Document:
414
+ """Retrieve a document by ID (deprecated, use download_content)."""
415
+ result = await self.download_content(document_id)
416
+ return Document(id=document_id, name=result.result.name)
@@ -0,0 +1,45 @@
1
+ """DocGes API models (Pydantic)."""
2
+ from .auth import AuthRequest, AuthResponse
3
+ from .document import Document
4
+ from .requests import (
5
+ ReqData,
6
+ ReqAuthData,
7
+ FileUpload,
8
+ ReqUpload,
9
+ SearchFilterValue,
10
+ SearchDateValue,
11
+ ReqSearchContent,
12
+ ReqCreateCategory,
13
+ ReqRenameCategory,
14
+ ReqDeleteCategory,
15
+ ReqMoveContent,
16
+ ReqUpdateContent,
17
+ ReqRemoveContent,
18
+ )
19
+ from .responses import (
20
+ ResCat,
21
+ ResCatItem,
22
+ ResSearch,
23
+ ResSearchItem,
24
+ FileDownloadResponse,
25
+ ResFileDownload,
26
+ ResultActionModel,
27
+ )
28
+
29
+ __all__ = [
30
+ # Auth
31
+ "AuthRequest", "AuthResponse",
32
+ # Document
33
+ "Document",
34
+ # Requests
35
+ "ReqData", "ReqAuthData",
36
+ "FileUpload", "ReqUpload",
37
+ "SearchFilterValue", "SearchDateValue", "ReqSearchContent",
38
+ "ReqCreateCategory", "ReqRenameCategory", "ReqDeleteCategory",
39
+ "ReqMoveContent", "ReqUpdateContent", "ReqRemoveContent",
40
+ # Responses
41
+ "ResCat", "ResCatItem",
42
+ "ResSearch", "ResSearchItem",
43
+ "FileDownloadResponse", "ResFileDownload",
44
+ "ResultActionModel",
45
+ ]
@@ -0,0 +1,17 @@
1
+ """Pydantic models for DocGes authentication."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pydantic import BaseModel
6
+
7
+
8
+ class AuthRequest(BaseModel):
9
+ username: str
10
+ password: str
11
+ appID: str
12
+
13
+
14
+ class AuthResponse(BaseModel):
15
+ token: str
16
+ # Extend with other fields returned by /Auth/Login when known
17
+ # e.g., expiry: int | None = None
@@ -0,0 +1,15 @@
1
+ """Pydantic models for DocGes document/content operations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pydantic import BaseModel
6
+
7
+
8
+ class Document(BaseModel):
9
+ """Represents a DocGes document (subset — extend as needed)."""
10
+
11
+ id: str
12
+ name: str
13
+ # Add more fields as discovered from API responses
14
+ # e.g., size: int | None = None
15
+ # mime_type: str | None = None
@@ -0,0 +1,103 @@
1
+ """Pydantic v2 models for DocGes API requests."""
2
+ from __future__ import annotations
3
+
4
+ from pydantic import BaseModel
5
+ from typing import List, Optional
6
+
7
+
8
+ # --- Auth & Session ---
9
+
10
+ class ReqAuthData(BaseModel):
11
+ """Login data + response context for authenticated requests."""
12
+ loginDocGesData: dict
13
+ loginResponse: dict
14
+
15
+
16
+ # --- Content Models ---
17
+
18
+ class FileUpload(BaseModel):
19
+ """File data for upload requests."""
20
+ fileData: str # base64-encoded
21
+ fileName: str
22
+ SIDCategory: str
23
+ erpRelation: str = ""
24
+ erpProperty: str = ""
25
+
26
+
27
+ class ReqUpload(BaseModel):
28
+ """Upload request payload."""
29
+ fileModel: FileUpload
30
+ requestModel: dict
31
+
32
+
33
+ class ReqData(BaseModel):
34
+ """Generic content request with SID."""
35
+ contenidoModel: dict # {"SIDContenido": str}
36
+ requestModel: Optional[dict] = None
37
+
38
+
39
+ # --- Search Models ---
40
+
41
+ class SearchFilterValue(BaseModel):
42
+ """Field value filter for search."""
43
+ field: str
44
+ mode: str
45
+ text: str
46
+
47
+
48
+ class SearchDateValue(BaseModel):
49
+ """Date range filter for search."""
50
+ field: str
51
+ exactDate: Optional[str] = None
52
+ fromDate: Optional[str] = None
53
+ toDate: Optional[str] = None
54
+
55
+
56
+ class ReqSearchContent(BaseModel):
57
+ """Search content request payload."""
58
+ fieldValues: Optional[List[dict]] = None
59
+ dateValues: Optional[List[dict]] = None
60
+ requestModel: Optional[dict] = None
61
+
62
+
63
+ # --- Category Models ---
64
+
65
+ class ReqCreateCategory(BaseModel):
66
+ """Create category request."""
67
+ parentSID: str
68
+ name: str
69
+ requestModel: dict
70
+
71
+
72
+ class ReqRenameCategory(BaseModel):
73
+ """Rename category request."""
74
+ SID: str
75
+ name: str
76
+ requestModel: dict
77
+
78
+
79
+ class ReqDeleteCategory(BaseModel):
80
+ """Delete category request."""
81
+ SID: str
82
+ requestModel: dict
83
+
84
+
85
+ # --- Document Management Models ---
86
+
87
+ class ReqMoveContent(BaseModel):
88
+ """Move document request."""
89
+ contentSID: str
90
+ destinationSID: str
91
+ requestModel: dict
92
+
93
+
94
+ class ReqUpdateContent(BaseModel):
95
+ """Update document metadata request."""
96
+ contentModel: dict
97
+ requestModel: dict
98
+
99
+
100
+ class ReqRemoveContent(BaseModel):
101
+ """Remove multiple documents request."""
102
+ contenidos: List[dict]
103
+ requestModel: dict
@@ -0,0 +1,108 @@
1
+ """Pydantic v2 models for DocGes API responses."""
2
+ from __future__ import annotations
3
+
4
+ from pydantic import BaseModel, ConfigDict
5
+ from typing import List, Optional
6
+
7
+
8
+ class DocGesResponseModel(BaseModel):
9
+ """Base model for DocGes responses. Allows underscore-prefixed fields (e.g., _Nombre)."""
10
+ model_config = ConfigDict(underscore_attrs_are_private=False)
11
+
12
+
13
+ # --- Category & Tree Responses ---
14
+
15
+ class ResCatItem(DocGesResponseModel):
16
+ """Single category item in tree responses."""
17
+ Nombre: str
18
+ SID: str
19
+ CategoriasHijas: Optional[List[dict]] = None
20
+ Documentos: Optional[List[dict]] = None
21
+ CategoriasHijas: Optional[List[dict]] = None
22
+ Documentos: Optional[List[dict]] = None
23
+
24
+
25
+ class ResCat(DocGesResponseModel):
26
+ """Response from /Content/LoadIniCats and /Content/LoadChilds."""
27
+ CategoriasHijas: Optional[List[dict]] = None
28
+ Documentos: Optional[List[dict]] = None
29
+
30
+ @classmethod
31
+ def from_json(cls, data: dict) -> "ResCat":
32
+ """Create ResCat from API JSON response."""
33
+ # Map underscore-prefixed fields in nested items
34
+ if "CategoriasHijas" in data and data["CategoriasHijas"]:
35
+ mapped_cats = []
36
+ for cat in data["CategoriasHijas"]:
37
+ mapped = {k[1:] if k.startswith('_') else k: v for k, v in cat.items()}
38
+ mapped_cats.append(mapped)
39
+ data["CategoriasHijas"] = mapped_cats
40
+ return cls(**data)
41
+
42
+
43
+ # --- Search Responses ---
44
+
45
+ class ResSearchItem(DocGesResponseModel):
46
+ """Single search result item."""
47
+ SID: str
48
+ Nombre: str
49
+ Tamanyo: Optional[int] = None
50
+ FechaModificacion: Optional[str] = None
51
+ model_config = ConfigDict(
52
+ extra='ignore'
53
+ )
54
+
55
+ @classmethod
56
+ def from_json(cls, data: dict) -> "ResSearchItem":
57
+ """Create from API JSON, mapping underscore-prefixed fields."""
58
+ mapped = {}
59
+ for key, val in data.items():
60
+ new_key = key[1:] if key.startswith('_') else key
61
+ mapped[new_key] = val
62
+ return cls(**mapped)
63
+ # Add more fields as discovered from API
64
+
65
+
66
+ class ResSearch(DocGesResponseModel):
67
+ """Response from /Content/SearchContent."""
68
+ results: Optional[List[dict]] = None
69
+ message: str = "OK"
70
+
71
+ @classmethod
72
+ def from_json(cls, data: dict) -> "ResSearch":
73
+ """Create ResSearch from API JSON response."""
74
+ # Handle nested result structure if present
75
+ if "result" in data:
76
+ return cls(results=data["result"].get("results"), message=data.get("message", "OK"))
77
+ return cls(results=data.get("results"), message=data.get("message", "OK"))
78
+
79
+
80
+ # --- Download Responses ---
81
+
82
+ class FileDownloadResponse(DocGesResponseModel):
83
+ """File data in download response."""
84
+ data: str # base64-encoded
85
+ name: str
86
+ type: str = "application/octet-stream"
87
+
88
+
89
+ class ResFileDownload(DocGesResponseModel):
90
+ """Response from /Content/Download."""
91
+ result: FileDownloadResponse
92
+ message: str = "OK"
93
+
94
+ @classmethod
95
+ def from_json(cls, data: dict) -> "ResFileDownload":
96
+ """Create ResFileDownload from API JSON response."""
97
+ if data.get("result") and isinstance(data["result"], dict):
98
+ return cls(result=FileDownloadResponse(**data["result"]), message=data.get("message", "OK"))
99
+ # Handle error case (result is None or non-dict)
100
+ return cls(result=FileDownloadResponse(data="", name="", type=""), message=data.get("message", "Error"))
101
+
102
+
103
+ # --- Generic Response ---
104
+
105
+ class ResultActionModel(DocGesResponseModel):
106
+ """Generic API response wrapper (result + message)."""
107
+ result: Optional[object] = None
108
+ message: str = "OK"
@@ -0,0 +1,154 @@
1
+ Metadata-Version: 2.4
2
+ Name: docges-api-py
3
+ Version: 0.1.0
4
+ Summary: Async, typed Python client for DocGes REST API
5
+ Author-email: "ct.galega" <soporte@ctgalega.com>
6
+ License: MIT
7
+ Requires-Python: >=3.12
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: httpx>=0.27
11
+ Requires-Dist: pydantic>=2.0
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest>=8.0; extra == "dev"
14
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
15
+ Requires-Dist: respx>=0.22; extra == "dev"
16
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
17
+ Requires-Dist: ruff>=0.4; extra == "dev"
18
+ Requires-Dist: mypy>=1.10; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # docges-api-py
22
+
23
+ Async, typed Python client for the DocGes REST API.
24
+
25
+ > **Work in progress** — bootstrapped via SDD (Spec-Driven Development).
26
+ > Phase 1-4 completed: async client with auth, retry, token refresh, and tests.
27
+ > Phase 5 completed: All core endpoints implemented.
28
+
29
+ ## Features
30
+
31
+ - ✅ Async HTTP client using `httpx`
32
+ - ✅ Typed request/response models with Pydantic v2
33
+ - ✅ Configurable retries and timeouts
34
+ - ✅ Token-based auth with automatic refresh (TTL)
35
+ - ✅ Full test coverage (pytest + respx)
36
+ - ✅ Complete DocGes API client (upload, download, search, categories)
37
+
38
+ ## Implemented endpoints
39
+
40
+ ### Auth
41
+ - `auth()` — authenticate against `/Auth/Login`
42
+
43
+ ### Content Tree
44
+ - `get_initial_cats()` — load initial categories via `/Content/LoadIniCats`
45
+ - `get_cat_info(sid)` — load category children via `/Content/LoadChilds`
46
+
47
+ ### Document Operations
48
+ - `upload_file(category_sid, file_path)` — upload via `/Content/UploadExtended`
49
+ - `download_content(sid)` — download via `/Content/Download` (returns `ResFileDownload`)
50
+ - `get_document(sid)` — deprecated wrapper (calls `download_content()`)
51
+
52
+ ### Search
53
+ - `search_content(field_values, date_values)` — search via `/Content/SearchContent`
54
+
55
+ ### Category Management
56
+ - `create_category(parent_sid, name)` — create via `/Content/CreateCategory`
57
+ - `rename_category(sid, new_name)` — rename via `/Content/RenameCategory`
58
+ - `delete_category(sid)` — delete via `/Content/DeleteCategory`
59
+
60
+ ### Document Management
61
+ - `remove_document(sid)` — remove via `/Content/RemoveDocument`
62
+ - `move_content(content_sid, destination_sid)` — move via `/Content/Move`
63
+ - `update_content(sid, erp_relation, erp_property)` — update via `/Content/Update`
64
+
65
+ ## Quick start
66
+
67
+ ```bash
68
+ pip install -e ".[dev]"
69
+ ```
70
+
71
+ ```python
72
+ import asyncio
73
+ from docges_api_py import AsyncDocGes
74
+
75
+ async def main():
76
+ async with AsyncDocGes(
77
+ "https://docges.example.com", "user", "password", "appid"
78
+ ) as client:
79
+ # Auth
80
+ auth_resp = await client.auth()
81
+ print(f"Token (partial): {auth_resp.token[:8]}...")
82
+
83
+ # Load initial categories
84
+ cats = await client.get_initial_cats()
85
+ print(f"Initial categories: {len(cats.CategoriasHijas)}")
86
+
87
+ # Search documents
88
+ results = await client.search_content(
89
+ field_values=[{"field": "name", "mode": "contains", "text": "invoice"}]
90
+ )
91
+ print(f"Search results: {len(results.results)}")
92
+
93
+ asyncio.run(main())
94
+ ```
95
+
96
+ See `examples/quickstart.py` for a more complete example.
97
+
98
+ ## Development
99
+
100
+ ```bash
101
+ pip install -e ".[dev]"
102
+ ruff check src/ tests/
103
+ mypy src/
104
+ pytest --cov=docges_api_py
105
+ ```
106
+
107
+ ## Migration
108
+
109
+ The library is being migrated from a sync `requests`-based client (see `wm-sync` reference code). See `docs/MIGRATION.md` for details.
110
+
111
+ Key changes:
112
+ - Replaced `requests` (sync) with `httpx.AsyncClient`
113
+ - Replaced raw `__dict__` serialization with Pydantic v2 models
114
+ - Replaced silent `return None` with typed exceptions (`AuthenticationError`, `RequestError`)
115
+ - Added configurable retries with exponential backoff
116
+
117
+ ## Project structure
118
+
119
+ ```
120
+ docges-api-py/
121
+ ├── src/docges_api_py/
122
+ │ ├── __init__.py # Exports AsyncDocGes, models (ResCat, ResFileDownload, etc.)
123
+ │ ├── client.py # AsyncDocGes client (auth + all endpoints)
124
+ │ └── models/
125
+ │ ├── auth.py # AuthRequest, AuthResponse
126
+ │ ├── document.py # Document
127
+ │ ├── requests.py # Request models (ReqUpload, ReqSearchContent, etc.)
128
+ │ ├── responses.py # Response models (ResCat, ResFileDownload, etc.)
129
+ │ └── __init__.py # Model exports
130
+ ├── tests/
131
+ │ ├── conftest.py
132
+ │ ├── test_client_auth.py
133
+ │ ├── test_initial_cats.py
134
+ │ ├── test_content_methods.py
135
+ │ ├── test_remaining_methods.py
136
+ │ ├── test_models_requests.py
137
+ │ ├── test_models_responses.py
138
+ │ ├── test_models_init.py
139
+ │ ├── test_endpoints.py
140
+ │ ├── test_retry.py
141
+ │ └── test_token_refresh.py
142
+ ├── examples/
143
+ │ └── quickstart.py
144
+ ├── docs/
145
+ │ └── MIGRATION.md
146
+ ├── pyproject.toml
147
+ ├── ruff.toml
148
+ ├── mypy.ini
149
+ └── README.md
150
+ ```
151
+
152
+ ## Contributing
153
+
154
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
@@ -0,0 +1,12 @@
1
+ docges_api_py/__init__.py,sha256=3Bn6Vb82H3MmVhn9LeeCsaKgA8zO7c0bGxy9gqywrPI,1431
2
+ docges_api_py/client.py,sha256=88546xapL_gn-qKeijP_xBc4PhlPpv68ogPr9MBprB4,14039
3
+ docges_api_py/models/__init__.py,sha256=jCvmbanSbBXJaEmBdwyxDNTZ1lSX9oMbhLQxfxb9rCg,1067
4
+ docges_api_py/models/auth.py,sha256=llIomeOKmUuU90PYMeOFDT94xAgMG-ZlC79ekw5I_oo,352
5
+ docges_api_py/models/document.py,sha256=o8adkSXUF8lii3HPEkn6XVda1UYVNRmH1Xo-IHw8ExY,388
6
+ docges_api_py/models/requests.py,sha256=Z-IFksBNw7Lloim1JtQvMQzjQbWs1kw9IdGWFDXCLR4,2197
7
+ docges_api_py/models/responses.py,sha256=wEKXeVv2U1sCiAw7Tt1BQmKOwd8NZG99-gJL5561bcc,3652
8
+ docges_api_py-0.1.0.dist-info/licenses/LICENSE,sha256=nePDdFB8FfGpeCQMqHobjWXyw-FgyYMzErpxxPf8fX8,1081
9
+ docges_api_py-0.1.0.dist-info/METADATA,sha256=_5KFguh5SVhN5Asm49GqhSuUva6sOkSCq_G1Jrl28es,5155
10
+ docges_api_py-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
11
+ docges_api_py-0.1.0.dist-info/top_level.txt,sha256=UXhyKjALYJ8SeAugjJZxHxt8nqSztOgi1FSLvRV14Tc,14
12
+ docges_api_py-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Your Name / Organization
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ docges_api_py