153 lines
6.2 KiB
Python
153 lines
6.2 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
Test script to verify the sales import fix for inventory_product_id issue
|
||
"""
|
||
|
||
import asyncio
|
||
import json
|
||
import httpx
|
||
import csv
|
||
import io
|
||
from uuid import uuid4
|
||
|
||
# Test configuration
|
||
GATEWAY_URL = "http://localhost:8000"
|
||
TENANT_ID = "946206b3-7446-436b-b29d-f265b28d9ff5"
|
||
|
||
# Test token
|
||
TEST_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzOTUyYTEwOC1lNWFmLTRlMjktOTJkOC0xMjc0MTBiOWJiYmEiLCJ1c2VyX2lkIjoiMzk1MmExMDgtZTVhZi00ZTI5LTkyZDgtMTI3NDEwYjliYmJhIiwiZW1haWwiOiJkZnNmc2RAdGVzdC5jb20iLCJ0eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzU1MTY3NTk4LCJpYXQiOjE3NTUxNjU3OTgsImlzcyI6ImJha2VyeS1hdXRoIiwiZnVsbF9uYW1lIjoiZGZzZGZzZGYiLCJpc192ZXJpZmllZCI6ZmFsc2UsImlzX2FjdGl2ZSI6dHJ1ZSwicm9sZSI6InVzZXIifQ.hYyRqqqZ-Ud-uzn42l_ic-QjP-NWYvT8RmwmU12uaQU"
|
||
|
||
async def test_sales_import():
|
||
"""Test the sales import functionality with the inventory_product_id fix"""
|
||
|
||
print("🧪 Testing Sales Import Fix for inventory_product_id")
|
||
print("=" * 60)
|
||
|
||
headers = {
|
||
"Authorization": f"Bearer {TEST_TOKEN}",
|
||
"Content-Type": "application/json"
|
||
}
|
||
|
||
async with httpx.AsyncClient(timeout=60.0) as client:
|
||
|
||
# Step 1: Create test CSV data
|
||
print("\n1️⃣ Creating Test CSV Data")
|
||
print("-" * 50)
|
||
|
||
csv_data = [
|
||
["date", "product_name", "quantity_sold", "revenue", "location_id"],
|
||
["2024-01-15", "Test Bread", "10", "25.50", "store-1"],
|
||
["2024-01-15", "Test Croissant", "5", "15.00", "store-1"],
|
||
["2024-01-15", "Test Muffin", "8", "20.00", "store-2"]
|
||
]
|
||
|
||
# Convert to CSV string
|
||
csv_string = io.StringIO()
|
||
writer = csv.writer(csv_string)
|
||
for row in csv_data:
|
||
writer.writerow(row)
|
||
csv_content = csv_string.getvalue()
|
||
|
||
print(f"CSV Content:")
|
||
print(csv_content)
|
||
|
||
# Step 2: Test the import endpoint
|
||
print("\n2️⃣ Testing Sales Data Import")
|
||
print("-" * 50)
|
||
|
||
import_data = {
|
||
"csv_data": csv_content,
|
||
"import_type": "enhanced",
|
||
"overwrite_existing": False
|
||
}
|
||
|
||
import_url = f"{GATEWAY_URL}/api/v1/tenants/{TENANT_ID}/sales/import/csv"
|
||
print(f"URL: {import_url}")
|
||
|
||
try:
|
||
response = await client.post(import_url, json=import_data, headers=headers)
|
||
print(f"Status: {response.status_code}")
|
||
|
||
if response.status_code == 200:
|
||
result = response.json()
|
||
print(f"✅ Sales import completed!")
|
||
print(f"Records processed: {result.get('records_processed', 0)}")
|
||
print(f"Records created: {result.get('records_created', 0)}")
|
||
print(f"Records failed: {result.get('records_failed', 0)}")
|
||
print(f"Success: {result.get('success', False)}")
|
||
|
||
if result.get('errors'):
|
||
print(f"\n❌ Errors ({len(result['errors'])}):")
|
||
for error in result['errors'][:5]: # Show first 5 errors
|
||
print(f" - {error}")
|
||
|
||
if result.get('warnings'):
|
||
print(f"\n⚠️ Warnings ({len(result['warnings'])}):")
|
||
for warning in result['warnings'][:3]: # Show first 3 warnings
|
||
print(f" - {warning}")
|
||
|
||
else:
|
||
print("❌ Sales import FAILED!")
|
||
print(f"Response: {response.text}")
|
||
|
||
except Exception as e:
|
||
print(f"❌ Sales import ERROR: {e}")
|
||
|
||
# Step 3: Check if inventory items were created
|
||
print("\n3️⃣ Checking Inventory Items Creation")
|
||
print("-" * 50)
|
||
|
||
try:
|
||
ingredients_url = f"{GATEWAY_URL}/api/v1/tenants/{TENANT_ID}/ingredients"
|
||
response = await client.get(ingredients_url, headers=headers)
|
||
|
||
if response.status_code == 200:
|
||
ingredients = response.json()
|
||
print(f"✅ Found {len(ingredients)} inventory items")
|
||
|
||
test_products = ["Test Bread", "Test Croissant", "Test Muffin"]
|
||
for product in test_products:
|
||
found = any(ingredient.get('name') == product for ingredient in ingredients)
|
||
status = "✅" if found else "❌"
|
||
print(f" {status} {product}")
|
||
|
||
else:
|
||
print(f"❌ Failed to fetch inventory items: {response.status_code}")
|
||
|
||
except Exception as e:
|
||
print(f"❌ Error checking inventory items: {e}")
|
||
|
||
# Step 4: Check sales records
|
||
print("\n4️⃣ Checking Sales Records")
|
||
print("-" * 50)
|
||
|
||
try:
|
||
sales_url = f"{GATEWAY_URL}/api/v1/tenants/{TENANT_ID}/sales"
|
||
response = await client.get(sales_url, headers=headers)
|
||
|
||
if response.status_code == 200:
|
||
sales_data = response.json()
|
||
sales_count = len(sales_data) if isinstance(sales_data, list) else sales_data.get('total', 0)
|
||
print(f"✅ Found {sales_count} sales records")
|
||
|
||
# Show recent records
|
||
records = sales_data if isinstance(sales_data, list) else sales_data.get('records', [])
|
||
for i, record in enumerate(records[:3]): # Show first 3 records
|
||
inventory_id = record.get('inventory_product_id')
|
||
date = record.get('date', 'Unknown')
|
||
quantity = record.get('quantity_sold', 0)
|
||
revenue = record.get('revenue', 0)
|
||
print(f" Record {i+1}: Date={date}, Qty={quantity}, Revenue=${revenue}, InventoryID={inventory_id}")
|
||
|
||
else:
|
||
print(f"❌ Failed to fetch sales records: {response.status_code}")
|
||
|
||
except Exception as e:
|
||
print(f"❌ Error checking sales records: {e}")
|
||
|
||
if __name__ == "__main__":
|
||
print("Testing sales import fix...")
|
||
print("Make sure your services are running with docker-compose!")
|
||
print()
|
||
|
||
asyncio.run(test_sales_import()) |