File size: 8,161 Bytes
ae83e31
 
 
 
 
 
 
 
 
c0cfae9
ae83e31
 
 
 
 
c8477e1
ae83e31
 
 
 
 
 
 
 
 
 
038867c
ae83e31
 
 
 
 
038867c
 
 
 
 
 
 
 
ae83e31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3fba179
ae83e31
 
 
 
038867c
ae83e31
 
 
 
038867c
 
 
 
ae83e31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
038867c
c8477e1
 
 
 
038867c
 
 
 
c8477e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae83e31
9846b7e
ae83e31
 
 
038867c
ae83e31
 
038867c
 
ae83e31
c8477e1
ae83e31
 
 
c8477e1
ae83e31
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#!/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)