Álvaro Valenzuela Valdes commited on
Commit ·
06b757a
1
Parent(s): 26a90fc
fix: refine OC API parameters and handle 500 errors gracefully
Browse files
backend/app/services/mercado_publico_oc.py
CHANGED
|
@@ -80,9 +80,18 @@ async def _fetch_oc(params: Dict[str, str]) -> List[PurchaseOrder]:
|
|
| 80 |
|
| 81 |
params["ticket"] = settings.mercado_publico_ticket
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
try:
|
| 84 |
async with httpx.AsyncClient(timeout=45.0) as client:
|
| 85 |
response = await client.get(API_BASE_OC, params=params)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
response.raise_for_status()
|
| 87 |
data = response.json()
|
| 88 |
|
|
@@ -100,7 +109,17 @@ async def get_oc_by_code(code: str) -> Optional[PurchaseOrder]:
|
|
| 100 |
return results[0] if results else None
|
| 101 |
|
| 102 |
async def get_ocs_by_date(date: str, status: str = "todos") -> List[PurchaseOrder]:
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
async def get_ocs_by_provider(provider_code: str, date: str) -> List[PurchaseOrder]:
|
| 106 |
return await _fetch_oc({"CodigoProveedor": provider_code, "fecha": date})
|
|
|
|
| 80 |
|
| 81 |
params["ticket"] = settings.mercado_publico_ticket
|
| 82 |
|
| 83 |
+
# Cleaning params: if status is "todos", it's better to omit it when fecha is present
|
| 84 |
+
if params.get("estado") == "todos":
|
| 85 |
+
del params["estado"]
|
| 86 |
+
|
| 87 |
try:
|
| 88 |
async with httpx.AsyncClient(timeout=45.0) as client:
|
| 89 |
response = await client.get(API_BASE_OC, params=params)
|
| 90 |
+
# Handle MP API quirks: sometimes it returns 500 when no data is found for a date
|
| 91 |
+
if response.status_code == 500:
|
| 92 |
+
print(f"⚠️ API returned 500 for {response.url} - Likely no data for this query.")
|
| 93 |
+
return []
|
| 94 |
+
|
| 95 |
response.raise_for_status()
|
| 96 |
data = response.json()
|
| 97 |
|
|
|
|
| 109 |
return results[0] if results else None
|
| 110 |
|
| 111 |
async def get_ocs_by_date(date: str, status: str = "todos") -> List[PurchaseOrder]:
|
| 112 |
+
params = {"estado": status}
|
| 113 |
+
|
| 114 |
+
# Logic based on documentation examples:
|
| 115 |
+
# If it's today, the doc suggests using estado=todos without fecha
|
| 116 |
+
today_str = datetime.now().strftime("%d%m%Y")
|
| 117 |
+
if date == today_str and status == "todos":
|
| 118 |
+
return await _fetch_oc({"estado": "todos"})
|
| 119 |
+
|
| 120 |
+
# Otherwise, use the date
|
| 121 |
+
params["fecha"] = date
|
| 122 |
+
return await _fetch_oc(params)
|
| 123 |
|
| 124 |
async def get_ocs_by_provider(provider_code: str, date: str) -> List[PurchaseOrder]:
|
| 125 |
return await _fetch_oc({"CodigoProveedor": provider_code, "fecha": date})
|