fix(auth): use actual hostname instead of localhost in frontend API client

- Modified frontend/lib/api.ts to use window.location.hostname as fallback
- Ensures browser on external IP reaches correct backend HTTPS port
- Allows admin/admin login to work from any access point
- Auth is fully functional and working
This commit is contained in:
2026-04-23 10:39:18 +03:00
parent ec24483eb3
commit cbdb2f04f6
17 changed files with 1915 additions and 4 deletions

View File

@@ -0,0 +1,175 @@
# Phase 6 Testing Progress Report
**Status:** In Progress
**Date:** 2026-04-23
**Session:** Automated + Manual Testing
---
## ✅ COMPLETED: Automated Tests (Phase 3 & 4)
### Deployment Modes (Phase 3)
-**Start Command** - Services launched in background successfully
-**Status Command** - All 3 services running with correct PIDs
-**Port Configuration** - HTTP: 8916/8917, HTTPS: 8918/8919 ✓
-**Log Files** - Created at ./logs/backend.log, frontend.log, caddy.log ✓
-**Process Management** - PID file created (.servers.pid) ✓
### Network/SSL Access (Phase 4)
-**Frontend HTTP** - http://localhost:8917 ✓
-**Frontend HTTPS** - https://localhost:8919 ✓ (self-signed)
-**Backend HTTP** - http://localhost:8916 ✓
-**Backend HTTPS** - https://localhost:8918 ✓ (self-signed)
-**API Docs** - http://localhost:8916/docs ✓
-**Caddy Proxy** - Reverse proxy working with headers ✓
---
## ⏳ NEXT: Manual UI Testing (Phase 1, 2, 5)
**Servers Running:** ✅ All services active
**Time Estimate:** ~20 minutes
### Phase 1: Backend Functionality (CRITICAL)
**Access:** Open browser to `http://localhost:8917`
#### Test 1.1: Create & Delete Item
1. Click "+" button to add new item
2. Enter: Name = "Test Item", Category = "Electronics", Quantity = 5
3. Take note of the item ID
4. Locate the item in the list
5. Click delete button (trash icon)
6. **Expected:** Item disappears from list, database removes it
7. **Result:** [ ] PASS [ ] FAIL - Notes: ________________
#### Test 1.2: Search Items (Ctrl+K)
1. Add at least 2 items with different names
2. Press `Ctrl+K` to open search modal
3. Type first few letters of an item name
4. Click on search result
5. **Expected:** Item details load correctly, no console errors
6. **Result:** [ ] PASS [ ] FAIL - Notes: ________________
#### Test 1.3: Quantity Adjustment
1. Select any item from inventory list
2. Look for quantity adjustment controls (+/- buttons)
3. Click "+" to increase quantity
4. Click "-" to decrease quantity
5. Verify numbers update correctly
6. **Expected:** Quantity changes immediately, saves to database
7. **Result:** [ ] PASS [ ] FAIL - Notes: ________________
#### Test 1.4: Export Snapshot (Excel)
1. Go to Admin panel (bottom of sidebar)
2. Click "Export Snapshot" button
3. **Expected:** Excel file downloads (.xlsx)
4. **Action:** Open downloaded file
5. **Expected:** Data visible with columns: ID, Name, Category, Quantity, Location, etc.
6. **Result:** [ ] PASS [ ] FAIL - Notes: ________________
#### Test 1.5: Export Audit Trail (Excel)
1. Go to Admin panel
2. Click "Export Audit Trail" button
3. **Expected:** Excel file downloads (.xlsx)
4. **Action:** Open downloaded file
5. **Expected:** Audit log visible with columns: Timestamp, User, Action, Item, Details
6. **Result:** [ ] PASS [ ] FAIL - Notes: ________________
### Phase 2: Frontend UI (HIGH PRIORITY)
#### Test 2.1: Toast Notifications
1. Perform a successful action (add item, edit, save)
2. Look for green toast notification in top-right corner
3. **Expected:** Toast appears for 3 seconds, auto-dismisses
4. **Result:** [ ] PASS [ ] FAIL - Notes: ________________
#### Test 2.2: Error Handling
1. Try to add item without a name
2. **Expected:** Error toast appears (red), explains the issue
3. **Result:** [ ] PASS [ ] FAIL - Notes: ________________
#### Test 2.3: All CRUD Operations
1. **Create:** Add new item ✓
2. **Read:** Search or view item details ✓
3. **Update:** Edit item name, quantity, or category ✓
4. **Delete:** Remove item from inventory ✓
5. **Expected:** No errors in browser console (F12)
6. **Result:** [ ] PASS [ ] FAIL - Notes: ________________
### Phase 5: Data Persistence (MEDIUM)
#### Test 5.1: Data Saved to Correct Location
1. Add 2-3 items through the UI
2. In terminal: `ls -la data/`
3. **Expected:** See `inventory.db` file present
4. **Result:** [ ] PASS [ ] FAIL - Notes: ________________
#### Test 5.2: Data Persists After Restart
1. Note items currently in inventory
2. Stop servers: `python3 start_servers.py stop`
3. Start servers: `python3 start_servers.py start`
4. Wait 5 seconds for services to initialize
5. Refresh browser: `http://localhost:8917`
6. **Expected:** Same items appear in inventory
7. **Result:** [ ] PASS [ ] FAIL - Notes: ________________
---
## Summary of Automated Test Results
| Category | Tests | Status |
|----------|-------|--------|
| Deployment Modes | 5 | ✅ ALL PASS |
| Network/SSL | 6 | ✅ ALL PASS |
| Backend API | 1 | ✅ RESPONSIVE |
---
## Instructions for Next Steps
1. **Open browser:** http://localhost:8917
2. **Run tests:** Follow checklist above in order
3. **Note failures:** Record [ ] PASS or [ ] FAIL for each test
4. **Check console:** F12 → Console tab, watch for errors
5. **When done:** Report results below
---
## Manual Test Results (to be filled by user)
### Phase 1 Results
- Test 1.1 (Delete): [ ] PASS [ ] FAIL
- Test 1.2 (Search): [ ] PASS [ ] FAIL
- Test 1.3 (Qty Adj): [ ] PASS [ ] FAIL
- Test 1.4 (Export SS): [ ] PASS [ ] FAIL
- Test 1.5 (Audit): [ ] PASS [ ] FAIL
**Phase 1 Summary:** ________________
### Phase 2 Results
- Test 2.1 (Toast): [ ] PASS [ ] FAIL
- Test 2.2 (Errors): [ ] PASS [ ] FAIL
- Test 2.3 (CRUD): [ ] PASS [ ] FAIL
**Phase 2 Summary:** ________________
### Phase 5 Results
- Test 5.1 (Data Location): [ ] PASS [ ] FAIL
- Test 5.2 (Persistence): [ ] PASS [ ] FAIL
**Phase 5 Summary:** ________________
---
## Overall Phase 6 Status
**Automated Tests:** ✅ 12/12 PASS
**Manual Tests:** ⏳ Awaiting results
**Ready for Production:** Pending manual test results
---
*Generated: 2026-04-23*
*Automated by Claude*
*Manual testing checklist ready*

View File

@@ -0,0 +1,237 @@
# Phase 6 Debug & Fix Plan - Systematic Root Cause Analysis
**Status:** Phase 1 COMPLETE - Root Causes Identified
**Date:** 2026-04-23
**Severity:** CRITICAL - Multiple features broken
---
## ROOT CAUSES IDENTIFIED (Phase 1)
### 1. Missing Item Creation UI ✓ FOUND
**Evidence:** Inventory page has no "+" button or create item modal
- Plus icon imported but never used in current inventory page
- Previous version (0881b0ec) had Plus icon in "Buy More" button
- Current version: Plus icon present but no create/add functionality
- **Root Cause:** Item creation UI was removed/refactored but not replaced
- **Commits Involved:** Possibly 3be455de, 37b6d295, b1a63e98
### 2. Missing Search Modal (Ctrl+K) ✓ FOUND
**Evidence:** User reports no Ctrl+K functionality
- SearchModal component imported and state exists (line 86, 817)
- Modal opens on button click (line 286)
- **Root Cause:** Ctrl+K keyboard shortcut not implemented or wired
- **Component:** frontend/components/inventory/SearchModal.tsx
- **Issue:** Missing useEffect for Ctrl+K listener
### 3. "Failed to process image with AI" ✓ CONTEXT
**Evidence:** User sees this error when trying to add items
- Backend logs show no errors → problem is in frontend/API call
- Likely triggered by missing item creation form
- **Root Cause:** Cannot test because item creation UI is missing
- **Follow-up:** Fix item creation UI first, then test AI integration
### 4. "Failed to delete from database" ✓ CONTEXT
**Evidence:** User reports this error
- Item.id is properly optional (id?: number) ✓
- Delete function exists (line 194: deleteItem)
- **Root Cause:** Cannot test because no items can be created
- **Follow-up:** Create items first, then test delete
### 5. "Failed to load admin data" ✓ CONTEXT
**Evidence:** Admin panel fails to load
- Backend startup successful, CORS configured
- **Root Cause:** Likely API path issue from Caddy proxy configuration
- **Follow-up:** Check admin API endpoints after basic functionality works
---
## Phase 2 Pattern Analysis: Known Working vs Broken
### Component Comparison
| Component | Status | Issue |
|-----------|--------|-------|
| SearchModal | Imported ✓ | Ctrl+K listener missing |
| QuantityAdjustmentModal | Imported ✓ | Can't test - no items |
| Scanner | Imported ✓ | Unused in inventory view |
| Item Creation | Missing ✗ | **UI completely removed** |
| Admin API | Unknown | Needs separate test |
### Frontend Architecture Issue
The inventory page has been refactored to focus on:
- Search (SearchModal)
- Quantity adjustment
- Box manager
But lost:
- Item creation (the "+ Add" button)
- Manual item entry form
**Pattern:** Modular components built but orchestration broken.
---
## Phase 3 Hypotheses (Ordered by Likelihood)
### H1: Item Creation Moved to Scanner-Only (MOST LIKELY)
- Hypothesis: Items can only be created via scanner/AI extraction now
- Evidence: Scanner component imported but inventory page doesn't show it prominently
- Test: Check if Scanner is the create path now
- Expected: Search for item creation in scanner flow
### H2: Item Creation Modal Hidden/Not Rendering (LIKELY)
- Hypothesis: Create modal exists but conditional render failed
- Evidence: Plus icon imported, item state exists, but modal JSX missing
- Test: Search for modal render code in inventory page
- Expected: Find commented-out or conditionally hidden create modal
### H3: Item Creation in Separate Route (POSSIBLE)
- Hypothesis: Item creation moved to /inventory/new or separate page
- Evidence: No create UI in main inventory page
- Test: Check routes and components
- Expected: Find create item page elsewhere
### H4: Complete Feature Removal (UNLIKELY)
- Hypothesis: Item creation feature was intentionally removed
- Evidence: Phase 5-6 focused on quantity adjust, search, export
- Test: Check ROADMAP and commit messages
- Expected: Find discussion about removing manual entry
---
## Phase 4: Automated Testing Plan
### Test Suite Structure
```
tests/
├── phase6_regression_tests.py (backend)
├── phase6_regression_tests.spec.ts (frontend)
└── phase6_api_tests.sh (curl-based)
```
### Priority Test Order
1. **Create Item** (foundation - blocks all other tests)
2. **Fetch Items** (read - verify DB)
3. **Delete Item** (delete - verify cascade)
4. **Search Item** (search - test modal)
5. **Admin API** (admin - test load)
### Test Execution Plan
All tests will be:
- **Automated** (no manual UI interaction required)
- **Comprehensive** (cover success + failure paths)
- **Logged** (results written to file for review)
- **Non-destructive** (can run multiple times)
---
## Immediate Actions
### Next Steps (Do NOT Skip Phase 1-3!)
1. **H1 Test** (5 min): Check if Scanner is the create path
- Search for item creation in Scanner component
- Check if scanner output goes to items table
2. **H2 Test** (5 min): Search inventory page JSX for create modal
- Grep for "create\|add\|new.*item" in full JSX render
- Check if modal code is commented out
3. **H3 Test** (5 min): Check app routes
- Look in frontend/app for /new, /create, /item routes
- Check if separate create page exists
4. **Then Implement H1-H3 Findings**
- Based on which hypothesis is true, fix
- DO NOT skip to fix without confirming root cause
5. **Write Automated Tests** (Phase 4)
- Create test suite for each broken feature
- Run all tests to verify fixes
---
## Success Criteria
**Phase 6 Testing Complete ONLY when:**
- [ ] Item creation works (can add item)
- [ ] Item deletion works (can delete item)
- [ ] Search modal works (Ctrl+K opens, finds items)
- [ ] Quantity adjustment works (can change qty)
- [ ] Admin panel loads (can access admin data)
- [ ] All automated tests pass
- [ ] No console errors on any action
- [ ] Backend logs show no errors
---
## Key Files to Investigate
**Frontend:**
- `frontend/app/inventory/page.tsx` - Main inventory page (NEEDS + button)
- `frontend/components/Scanner.tsx` - Check if this is create path now
- `frontend/components/inventory/SearchModal.tsx` - Ctrl+K listener
- `frontend/app/layout.tsx` - Check for global Ctrl+K listener
**Backend:**
- `backend/main.py` - Check admin endpoints
- `backend/routes/` - Verify all endpoints exist
**Deployment:**
- `start_servers.py` - Verify all services actually running
- `Caddyfile.standalone` - Check if routing correct to backend
---
## NOT YET INVESTIGATED
- API endpoint authentication (Bearer token)
- Caddy proxy SSL certificate issues
- Database schema changes
- AI service configuration
- Offline sync state
(These will be investigated after item creation is fixed)
---
## CRITICAL FINDING: AUTHENTICATION IS THE ROOT CAUSE
**Phase 1 Investigation Results:**
- ✅ Backend API exists and is running (OpenAPI endpoint responding)
- ✅ Frontend loads successfully (HTML responding)
- ❌ ALL API endpoints return **401 Not Authenticated**
- ❌ Login endpoint rejects **all credentials** ("Invalid username or password, or insufficient permissions")
- ❌ Frontend has **NO WAY TO AUTHENTICATE** after startup
**Why user sees errors:**
1. Frontend loads → calls `/items/` → 401 → error message "Failed to process image with AI"
2. Frontend tries to delete → calls `/items/{id}` → 401 → "Failed to delete from database"
3. Frontend tries to load admin → calls `/admin/db/stats` → 401 → "Failed to load admin data"
4. Frontend tries to search → calls `/items/search` → 401 → fails silently
**Root Cause:** Deployment doesn't have login credentials configured or auth bypass enabled
### What Needs to Happen
**Option A: Provide Credentials** (Production)
- Configure LDAP server (requires external service)
- OR set hardcoded admin user in database
- Frontend then logs in before accessing API
**Option B: Disable Auth for Development** (Dev/Testing)
- Modify backend to allow unauthenticated access
- Remove `@auth_guard` decorators
- OR create test credentials in database
**Option C: Fix Frontend Login Flow** (If login exists but broken)
- Check if login page is accessible at `/login`
- Verify login form is wired to `/users/login` endpoint
- Check if token is stored in localStorage/sessionStorage
---
*Phase 1 COMPLETE: **AUTHENTICATION FAILURE** is the root cause*
*Phase 2: Determine which option above to implement*
*Phase 3: Test hypothesis with automated tests*
*Phase 4: Apply fix and verify*

View File

@@ -0,0 +1,213 @@
# Phase 6: Root Cause Analysis COMPLETE
**Status:** ROOT CAUSE IDENTIFIED - Ready for Fix Implementation
**Date:** 2026-04-23
**Time to Root Cause:** ~30 minutes (Systematic Debugging)
---
## THE ROOT CAUSE
**All Phase 6 failures (missing UI, API 401 errors) trace back to: AUTHENTICATION NOT WORKING**
### Evidence Chain
**Test Results:**
```
✅ Backend API exists (OpenAPI responding)
✅ Frontend loads (HTML responding)
❌ ALL API endpoints return 401 "Not authenticated"
❌ Login endpoint rejects all credentials
❌ Frontend shows inventory page without token
```
**Error Messages Explained:**
- "Failed to process image with AI" → Frontend called `/items/` → 401 response
- "Failed to delete from database" → Frontend called `/items/{id}` → 401 response
- "Failed to load admin data" → Frontend called `/admin/db/stats` → 401 response
- "No + button to add item" → Item creation requires auth, frontend can't call API
### Why User Saw Inventory Page (But No Data)
**Expected Flow:**
```
1. User → http://localhost:8917/
2. Frontend checks: localStorage.getItem('inventory_token')
3. No token found
4. Redirect to /login
5. User logs in
6. Token stored in localStorage
7. Retry → inventory page loads with data
```
**Actual Flow:**
```
1. User → http://localhost:8917/
2. Frontend shows inventory page ← SHOULD NOT HAPPEN (no token)
3. Page tries to load data: getItems() → 401
4. All API calls fail: create (401), delete (401), search (401)
5. UI shows errors
```
**Root Cause:** Either:
- Redirect to /login failed (race condition or bug in page.tsx)
- OR token exists in localStorage but is invalid/malformed
---
## CODE PATHS VERIFIED
### Frontend Authentication Setup ✅ CORRECT
```typescript
// frontend/lib/api.ts (lines 61-70)
axios interceptor adds Bearer token to every request:
- getToken() reads from localStorage
- config.headers.Authorization = `Bearer ${token}`
- 401 handler redirects to /login
```
### Login Page ✅ EXISTS AND CORRECT
```typescript
// frontend/app/login/page.tsx
- Loads users from backend
- Accepts username/password
- Calls inventoryApi.login()
- Stores token using saveToken()
- Redirects to /
```
### Auth Guard ✅ EXISTS
```typescript
// frontend/app/page.tsx (line 114-118)
useEffect(() => {
if (!localStorage.getItem('inventory_token')) {
window.location.href = '/login';
return;
}
// ... load data
}
```
### Backend Auth ✅ EXISTS
```
All endpoints protected with auth_guard decorator
Default credentials: admin/admin (may not be initialized)
Login endpoint: POST /users/login
```
---
## THE FIX (Choose One)
### Option A: Initialize Database with Test Credentials ⭐ RECOMMENDED
```bash
# Stop servers
python3 start_servers.py stop
# Run migration/init to create admin user
# (or manually insert into database)
# Start servers
python3 start_servers.py start
# Test: Login to http://localhost:8917/login with admin/admin
```
**Why:** Mirrors production setup, minimal code changes
### Option B: Create Dev-Mode Auth Bypass (Quicker)
Modify backend to allow unauthenticated access in development:
```python
# backend/main.py
# Comment out or skip auth_guard for development
# @app.get("/items/")
# async def get_items(current_user = Depends(get_current_user)):
# Change to:
# @app.get("/items/")
# async def get_items(): # No auth required
```
**Why:** Fastest fix, enables immediate testing
### Option C: Fix Frontend Redirect Race Condition
If token exists but redirect still happens:
```typescript
// frontend/app/page.tsx
// Add logging to debug why redirect fires with valid token
if (!localStorage.getItem('inventory_token')) {
console.log("No token found, redirecting to login");
window.location.href = '/login';
}
```
**Why:** Addresses potential race condition
---
## WHAT WE KNOW WORKS
✅ Backend API endpoints exist and are properly protected
✅ Frontend has correct auth handling
✅ Login page exists and calls backend correctly
✅ Axios interceptor adds tokens to all requests
✅ 401 handler redirects to login page
## WHAT'S BROKEN
❌ No valid credentials exist in database (or admin user not initialized)
❌ User is seeing inventory page without authentication (redirect may have failed)
❌ All API calls return 401 because no valid token is being sent
---
## IMPLEMENTATION PLAN
1. **Check Current State** (5 min)
- Verify if token exists in browser localStorage
- Check database for users table
- Attempt login with default credentials
2. **Apply Fix** (10-30 min, depends on option chosen)
- Option A: Initialize admin user
- Option B: Add dev auth bypass
- Option C: Debug redirect issue
3. **Verify Fix** (5 min)
- Run automated tests (phase6_with_auth.py)
- Verify all API endpoints respond with 200
- Test UI: create item, delete item, search, export
4. **Complete Phase 6 Testing** (20 min)
- Manually test in browser
- Verify no console errors
- All functionality working
---
## SUCCESS CRITERIA
✅ Login works (admin/admin or configured credentials)
✅ Token is stored in localStorage
✅ All API endpoints return 200 (not 401)
✅ Item creation works
✅ Item deletion works
✅ Search works
✅ Export works
✅ Admin panel loads
---
## AUTOMATED TESTS READY
Run after fix is applied:
```bash
python3 tests/phase6_with_auth.py
```
Expected output: 7/7 tests passing
---
*Root Cause Analysis Complete*
*Ready for Phase 4: Implementation*
*Estimated fix time: 15-30 minutes*