Fix new services implementation 1

This commit is contained in:
Urtzi Alfaro
2025-08-13 21:41:00 +02:00
parent 16b8a9d50c
commit 262b3dc9c4
13 changed files with 1702 additions and 1210 deletions

View File

@@ -3,40 +3,27 @@
Client for communicating with Inventory Service
"""
import httpx
import logging
from typing import List, Optional, Dict, Any
from uuid import UUID
from shared.clients.inventory_client import InventoryServiceClient as SharedInventoryClient
from ..core.config import settings
logger = logging.getLogger(__name__)
class InventoryClient:
"""Client for inventory service communication"""
"""Client for inventory service communication via shared client"""
def __init__(self):
self.base_url = settings.INVENTORY_SERVICE_URL
self.timeout = 30.0
self._shared_client = SharedInventoryClient(settings)
async def get_ingredient_by_id(self, tenant_id: UUID, ingredient_id: UUID) -> Optional[Dict[str, Any]]:
"""Get ingredient details from inventory service"""
try:
async with httpx.AsyncClient(timeout=self.timeout) as client:
response = await client.get(
f"{self.base_url}/api/v1/ingredients/{ingredient_id}",
headers={"X-Tenant-ID": str(tenant_id)}
)
if response.status_code == 200:
return response.json()
elif response.status_code == 404:
return None
else:
logger.error(f"Failed to get ingredient {ingredient_id}: {response.status_code}")
return None
result = await self._shared_client.get_ingredient_by_id(ingredient_id, str(tenant_id))
return result
except Exception as e:
logger.error(f"Error getting ingredient {ingredient_id}: {e}")
return None
@@ -44,19 +31,13 @@ class InventoryClient:
async def get_ingredients_by_ids(self, tenant_id: UUID, ingredient_ids: List[UUID]) -> List[Dict[str, Any]]:
"""Get multiple ingredients by IDs"""
try:
async with httpx.AsyncClient(timeout=self.timeout) as client:
response = await client.post(
f"{self.base_url}/api/v1/ingredients/batch",
headers={"X-Tenant-ID": str(tenant_id)},
json={"ingredient_ids": [str(id) for id in ingredient_ids]}
)
if response.status_code == 200:
return response.json()
else:
logger.error(f"Failed to get ingredients batch: {response.status_code}")
return []
# For now, get ingredients individually - could be optimized with batch endpoint
results = []
for ingredient_id in ingredient_ids:
ingredient = await self._shared_client.get_ingredient_by_id(ingredient_id, str(tenant_id))
if ingredient:
results.append(ingredient)
return results
except Exception as e:
logger.error(f"Error getting ingredients batch: {e}")
return []
@@ -64,20 +45,16 @@ class InventoryClient:
async def get_ingredient_stock_level(self, tenant_id: UUID, ingredient_id: UUID) -> Optional[Dict[str, Any]]:
"""Get current stock level for ingredient"""
try:
async with httpx.AsyncClient(timeout=self.timeout) as client:
response = await client.get(
f"{self.base_url}/api/v1/stock/ingredient/{ingredient_id}",
headers={"X-Tenant-ID": str(tenant_id)}
)
if response.status_code == 200:
return response.json()
elif response.status_code == 404:
return None
else:
logger.error(f"Failed to get stock level for {ingredient_id}: {response.status_code}")
return None
stock_entries = await self._shared_client.get_ingredient_stock(ingredient_id, str(tenant_id))
if stock_entries:
# Calculate total available stock from all entries
total_stock = sum(entry.get('available_quantity', 0) for entry in stock_entries)
return {
'ingredient_id': str(ingredient_id),
'total_available': total_stock,
'stock_entries': stock_entries
}
return None
except Exception as e:
logger.error(f"Error getting stock level for {ingredient_id}: {e}")
return None
@@ -114,23 +91,19 @@ class InventoryClient:
) -> Dict[str, Any]:
"""Record ingredient consumption for production"""
try:
async with httpx.AsyncClient(timeout=self.timeout) as client:
response = await client.post(
f"{self.base_url}/api/v1/stock/consume",
headers={"X-Tenant-ID": str(tenant_id)},
json={
"consumptions": consumptions,
"reference_number": str(production_batch_id),
"movement_type": "production_use"
}
)
consumption_data = {
"consumptions": consumptions,
"reference_number": str(production_batch_id),
"movement_type": "production_use"
}
result = await self._shared_client.consume_stock(consumption_data, str(tenant_id))
if result:
return {"success": True, "data": result}
else:
return {"success": False, "error": "Failed to consume ingredients"}
if response.status_code == 200:
return {"success": True, "data": response.json()}
else:
logger.error(f"Failed to consume ingredients: {response.status_code}")
return {"success": False, "error": response.text}
except Exception as e:
logger.error(f"Error consuming ingredients: {e}")
return {"success": False, "error": str(e)}
@@ -142,19 +115,13 @@ class InventoryClient:
) -> Dict[str, Any]:
"""Add finished product to inventory after production"""
try:
async with httpx.AsyncClient(timeout=self.timeout) as client:
response = await client.post(
f"{self.base_url}/api/v1/stock/add",
headers={"X-Tenant-ID": str(tenant_id)},
json=product_data
)
result = await self._shared_client.receive_stock(product_data, str(tenant_id))
if result:
return {"success": True, "data": result}
else:
return {"success": False, "error": "Failed to add finished product"}
if response.status_code == 200:
return {"success": True, "data": response.json()}
else:
logger.error(f"Failed to add finished product: {response.status_code}")
return {"success": False, "error": response.text}
except Exception as e:
logger.error(f"Error adding finished product: {e}")
return {"success": False, "error": str(e)}