Checking onboardin flow - fix 3

This commit is contained in:
Urtzi Alfaro
2025-07-27 11:04:32 +02:00
parent 30ac945058
commit 0b14cf9eb2
3 changed files with 92 additions and 12 deletions

View File

@@ -83,13 +83,11 @@ async def start_training_job(
except Exception as e:
logger.warning("Failed to publish job started event", error=str(e))
# Start training in background
background_tasks.add_task(
training_service.execute_training_job,
db, # Pass the database session
job.job_id,
job.tenant_id,
request # Pass the request object
training_service.execute_training_job_simple,
new_job_id,
tenant_id_str,
request
)
logger.info("Training job created",

View File

@@ -31,6 +31,36 @@ class TrainingService:
def __init__(self):
self.ml_trainer = BakeryMLTrainer()
async def execute_training_job_simple(self, job_id: str, tenant_id_str: str, request: TrainingJobRequest):
"""Simple wrapper that creates its own database session"""
try:
# Import database_manager locally to avoid circular imports
from app.core.database import database_manager
logger.info(f"Starting background training job {job_id} for tenant {tenant_id_str}")
# Create new session for background task
async with database_manager.async_session_local() as session:
await self.execute_training_job(session, job_id, tenant_id_str, request)
await session.commit()
except Exception as e:
logger.error(f"Background training job {job_id} failed: {str(e)}")
# Try to update job status to failed
try:
from app.core.database import database_manager
async with database_manager.async_session_local() as error_session:
await self._update_job_status(
error_session, job_id, "failed", 0,
f"Training failed: {str(e)}", error_message=str(e)
)
await error_session.commit()
except Exception as update_error:
logger.error(f"Failed to update job status: {str(update_error)}")
raise
async def create_training_job(self,
db: AsyncSession,
@@ -425,7 +455,7 @@ class TrainingService:
params["limit"] = limit
response = await client.get(
f"{settings.DATA_SERVICE_URL}/api/v1/tenants/{tenant_id}/sales/",
f"{settings.DATA_SERVICE_URL}/api/v1/tenants/{tenant_id}/sales",
params=params,
headers=headers,
timeout=30.0
@@ -516,7 +546,7 @@ class TrainingService:
params["end_date"] = request.end_date.isoformat()
response = await client.get(
f"{settings.DATA_SERVICE_URL}/tenants/{tenant_id}/traffic/historical",
f"http://gateway:8000/tenants/{tenant_id}/traffic/historical",
params=params,
timeout=30.0
)

View File

@@ -298,19 +298,40 @@ echo -e "${STEP_ICONS[1]} ${PURPLE}STEP 2: BAKERY REGISTRATION${NC}"
echo "Simulating onboarding page step 2 - 'Datos de Panadería'"
echo ""
log_step "2.1. Registering bakery/tenant"
log_step "2.1. Registering bakery/tenant with mock coordinates"
# Using exact schema from BakeryRegistration
# Mock coordinates for Madrid locations (since geolocation service is not running)
# These are real Madrid coordinates for testing weather and traffic data acquisition
MADRID_COORDS=(
"40.4168:-3.7038" # Sol (city center)
"40.4378:-3.6795" # Retiro area
"40.4093:-3.6936" # Atocha area
"40.4517:-3.6847" # Chamberí area
"40.3897:-3.6774" # Delicias area
)
# Select random coordinates from Madrid locations
SELECTED_COORDS=${MADRID_COORDS[$((RANDOM % ${#MADRID_COORDS[@]}))]}
IFS=':' read -r MOCK_LATITUDE MOCK_LONGITUDE <<< "$SELECTED_COORDS"
echo "Using mock coordinates for Madrid:"
echo " Latitude: $MOCK_LATITUDE"
echo " Longitude: $MOCK_LONGITUDE"
echo " (This simulates the address-to-coordinates conversion service)"
# Using exact schema from BakeryRegistration with added coordinates
BAKERY_DATA="{
\"name\": \"Panadería Test $(date +%H%M)\",
\"business_type\": \"bakery\",
\"address\": \"Calle Gran Vía 123\",
\"city\": \"Madrid\",
\"postal_code\": \"28001\",
\"phone\": \"+34600123456\"
\"phone\": \"+34600123456\",
\"latitude\": $MOCK_LATITUDE,
\"longitude\": $MOCK_LONGITUDE
}"
echo "Bakery Data:"
echo "Bakery Data with mock coordinates:"
echo "$BAKERY_DATA" | python3 -m json.tool
BAKERY_RESPONSE=$(curl -s -w "\nHTTP_CODE:%{http_code}" -X POST "$API_BASE/api/v1/tenants/register" \
@@ -330,6 +351,37 @@ if check_response "$BAKERY_RESPONSE" "Bakery Registration"; then
TENANT_ID=$(extract_json_field "$BAKERY_RESPONSE" "id")
if [ -n "$TENANT_ID" ]; then
log_success "Tenant ID extracted: $TENANT_ID"
log_success "Mock coordinates will be used for weather/traffic data: ($MOCK_LATITUDE, $MOCK_LONGITUDE)"
# Store coordinates for later use in training
echo "BAKERY_LATITUDE=$MOCK_LATITUDE" > /tmp/bakery_coords.env
echo "BAKERY_LONGITUDE=$MOCK_LONGITUDE" >> /tmp/bakery_coords.env
echo "TENANT_ID=$TENANT_ID" >> /tmp/bakery_coords.env
log_step "2.2. Testing weather data acquisition with mock coordinates"
# Test if weather service can use these coordinates
WEATHER_TEST_RESPONSE=$(curl -s -X GET "$API_BASE/api/v1/training/$TENANT_ID/weather/current?latitude=$MOCK_LATITUDE&longitude=$MOCK_LONGITUDE" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "X-Tenant-ID: $TENANT_ID" 2>/dev/null || echo '{"status":"service_unavailable"}')
if echo "$WEATHER_TEST_RESPONSE" | grep -q '"temperature"\|"weather"'; then
log_success "Weather service can use mock coordinates"
else
log_warning "Weather service test skipped (coordinates stored for training)"
fi
log_step "2.3. Testing traffic data acquisition with mock coordinates"
# Test if traffic service can use these coordinates
TRAFFIC_TEST_RESPONSE=$(curl -s -X GET "$API_BASE/api/v1/training/$TENANT_ID/traffic/current?latitude=$MOCK_LATITUDE&longitude=$MOCK_LONGITUDE" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "X-Tenant-ID: $TENANT_ID" 2>/dev/null || echo '{"status":"service_unavailable"}')
if echo "$TRAFFIC_TEST_RESPONSE" | grep -q '"traffic_volume"\|"intensity"'; then
log_success "Traffic service can use mock coordinates"
else
log_warning "Traffic service test skipped (coordinates stored for training)"
fi
else
log_error "Failed to extract tenant ID"
exit 1