foodwise-remote-mcp / scripts /inventory_demo.py
LeoWalker's picture
enhance(dev): improve development tooling and configuration
c0cfae9
#!/usr/bin/env python3
"""
Manual test script to verify Notion database connectivity and basic operations.
This script tests the core FoodWiseNotionClient functionality:
1. Add a test item to the Notion database
2. Query it back to verify it was created
3. Clean up by archiving the test item
Run with: uv run python scripts/inventory_demo.py
"""
import sys
import os
from pathlib import Path
from datetime import datetime, timedelta, date
# Add src to path so we can import our modules
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from dotenv import load_dotenv
load_dotenv()
from foodwise.notion.notion_client import FoodWiseNotionClient
def run_notion_connection():
"""Test basic Notion database operations."""
print("πŸ§ͺ Testing Notion database connection...")
try:
# Initialize client
# Prefer test DBs if provided to avoid modifying prod data
test_inventory_db = os.getenv("NOTION_INVENTORY_DB_ID_TEST")
if test_inventory_db:
os.environ["NOTION_INVENTORY_DB_ID"] = test_inventory_db
test_shopping_db = os.getenv("NOTION_SHOPPING_DB_ID_TEST")
if test_shopping_db:
os.environ["NOTION_SHOPPING_DB_ID"] = test_shopping_db
client = FoodWiseNotionClient()
print("βœ… Notion client initialized successfully")
# Test data
demo_item = {
"name": "Hackathon Test Apple",
"category": "Fruits",
"storage_type": "Pantry",
"quantity": 3,
"unit": "pieces",
"best_by_date": "2024-12-31",
"purchase_date": "2024-12-01",
"temperature_sensitive": False,
"cooked_raw_status": "Raw",
"tags": ["Organic", "Sale Item"]
}
print(f"πŸ“ Adding test item: {demo_item['name']}")
# Add item to database
added_item = client.add_inventory_item(demo_item)
print(f"βœ… Item created successfully!")
print(f" πŸ“„ Notion URL: {added_item['url']}")
print(f" πŸ†” Page ID: {added_item['id']}")
# Query it back
print("πŸ” Searching for the test item...")
search_results = client.search_items("Hackathon Test Apple")
if search_results and len(search_results) > 0:
found_item = search_results[0]
print("βœ… Item found in search results!")
print(f" πŸ“‹ Name: {found_item['name']}")
print(f" πŸ“‚ Category: {found_item['category']}")
print(f" πŸ“¦ Storage: {found_item['storage_type']}")
print(f" πŸ”’ Quantity: {found_item['quantity']} {found_item['unit']}")
else:
print("❌ Item not found in search results")
return False
# Test expiring items query
print("πŸ“… Testing expiring items query...")
expiring_items = client.get_expiring_items(30) # Next 30 days
print(f"πŸ“Š Found {len(expiring_items)} items expiring in next 30 days")
# Clean up - archive the test item
print("🧹 Cleaning up test item...")
client.client.pages.update(
page_id=added_item['id'],
archived=True
)
print("βœ… Test item archived successfully")
print("\nπŸŽ‰ All tests passed! Notion integration is working correctly.")
return True
except Exception as e:
print(f"❌ Test failed with error: {e}")
print("\nπŸ”§ Troubleshooting:")
print(" 1. Check that NOTION_SECRET is set in your .env file")
print(" 2. Check that NOTION_INVENTORY_DB_ID is set in your .env file")
print(" 3. Verify your Notion integration has access to the database")
return False
def run_query_operations():
"""Test various query operations without adding new items."""
print("\nπŸ” Testing query operations...")
try:
# Prefer test DBs if provided
test_inventory_db = os.getenv("NOTION_INVENTORY_DB_ID_TEST")
if test_inventory_db:
os.environ["NOTION_INVENTORY_DB_ID"] = test_inventory_db
client = FoodWiseNotionClient()
# Test getting all inventory
print("πŸ“‹ Querying all inventory items...")
all_items = client.query_inventory()
print(f"πŸ“Š Found {len(all_items)} total items in inventory")
if all_items:
sample_item = all_items[0]
print(f" πŸ“ Sample item: {sample_item['name']}")
# Test category filter
print("πŸ₯› Testing category filter (Dairy)...")
dairy_items = client.query_inventory({
"property": "Category",
"select": {"equals": "Dairy"}
})
print(f"πŸ§€ Found {len(dairy_items)} dairy items")
return True
except Exception as e:
print(f"❌ Query test failed: {e}")
return False
def run_update_remove_operations():
"""Test update and remove operations with proper cleanup."""
print("\nπŸ”„ Testing update and remove operations...")
try:
# Prefer test DBs if provided
test_inventory_db = os.getenv("NOTION_INVENTORY_DB_ID_TEST")
if test_inventory_db:
os.environ["NOTION_INVENTORY_DB_ID"] = test_inventory_db
client = FoodWiseNotionClient()
# Create a test item specifically for update/remove testing
test_item = {
"name": "Update Test Banana",
"category": "Fruits",
"storage_type": "Pantry",
"quantity": 5.0,
"unit": "pieces",
"best_by_date": "2024-12-25",
"purchase_date": "2024-12-01",
"temperature_sensitive": False,
"cooked_raw_status": "Raw"
}
print(f"πŸ“ Adding test item for update/remove: {test_item['name']}")
added_item = client.add_inventory_item(test_item)
page_id = added_item['id']
print(f"βœ… Test item created with ID: {page_id}")
# Test update operation
print("πŸ”„ Testing update operation...")
update_data = {
"quantity": 3.0,
"best_by_date": "2024-12-20",
"tags": ["Low Stock"]
}
updated_item = client.update_inventory_item(page_id, update_data)
print("βœ… Update successful!")
print(f" πŸ”’ Updated quantity: {updated_item['quantity']}")
print(f" πŸ“… Updated best by: {updated_item['best_by_date']}")
# Test remove operation
print("πŸ—‘οΈ Testing remove operation...")
remove_result = client.remove_inventory_item(page_id)
print("βœ… Remove successful!")
print(f" πŸ“‹ Result: {remove_result['message']}")
print("πŸŽ‰ Update and remove operations working correctly!")
return True
except Exception as e:
print(f"❌ Update/remove test failed: {e}")
# Try to clean up if item was created but operations failed
try:
if 'page_id' in locals():
print("🧹 Attempting cleanup...")
client.remove_inventory_item(page_id)
print("βœ… Cleanup successful")
except:
print("⚠️ Cleanup failed - you may need to manually archive the test item")
return False
if __name__ == "__main__":
print("🍽️ FoodWise Inventory Demo (TEST DB)")
print("=" * 40)
# Run tests
connection_success = run_notion_connection()
if connection_success:
query_success = run_query_operations()
update_remove_success = run_update_remove_operations()
if query_success and update_remove_success:
print("\n🎯 All tests completed successfully!")
print(" Your Notion integration is ready for the agent!")
else:
print("\n⚠️ Some tests failed - check the output above")
else:
print("\nπŸ’₯ Connection test failed - fix setup before proceeding")
sys.exit(1)