This commit adds complete documentation and tooling for migrating from
local development (Kind/Colima on macOS) to production deployment
(MicroK8s on Ubuntu VPS at Clouding.io).
Documentation added:
- K8S-MIGRATION-GUIDE.md: Comprehensive step-by-step migration guide
covering all phases from VPS setup to post-deployment operations
- MIGRATION-CHECKLIST.md: Quick reference checklist for migration tasks
- MIGRATION-SUMMARY.md: High-level overview and key changes summary
Configuration updates:
- Added storage-patch.yaml for MicroK8s storage class compatibility
(changes from 'standard' to 'microk8s-hostpath')
- Updated prod/kustomization.yaml to include storage patch
Helper scripts:
- deploy-production.sh: Interactive deployment script with validation
- tag-and-push-images.sh: Automated image tagging and registry push
- backup-databases.sh: Database backup script for production
Key differences addressed:
- Ingress: MicroK8s addon vs custom NGINX
- Storage: MicroK8s hostpath vs Kind standard storage
- Registry: Container registry configuration for production
- SSL: Let's Encrypt production certificates
- Domains: Real domain configuration vs localhost
- Resources: Production-grade resource limits and scaling
The migration guide covers:
- VPS setup and MicroK8s installation
- Configuration adaptations required
- Container registry setup options
- SSL certificate configuration
- Monitoring and backup setup
- Troubleshooting common issues
- Security hardening checklist
- Rollback procedures
All existing Kubernetes manifests remain unchanged and compatible.
Clear auth store when exiting demo session to prevent unauthorized page redirect.
## Problem
When users clicked "Salir" (Exit) from the demo session, they were redirected to the unauthorized page (`/unauthorized`) instead of the demo landing page (`/demo`).
## Root Cause
The `handleExpiration()` function in DemoBanner.tsx was clearing localStorage and navigating to `/demo`, but was NOT clearing the auth store. This created an inconsistent state:
- `isDemoMode = false` (localStorage cleared)
- `demoSessionId = null` (localStorage cleared)
- `isAuthenticated = true` (auth store NOT cleared - still has demo user)
The `useHasAccess()` hook checks:
```typescript
return isAuthenticated || (isDemoMode && !!demoSessionId);
```
After clearing localStorage but not auth:
- `isAuthenticated = true` but the demo session is invalid
- `isDemoMode = false` and `demoSessionId = null`
- Result: `useHasAccess()` returns `false`
When navigating to `/demo`, the ProtectedRoute checked access and found it was `false`, redirecting to `/unauthorized`.
## Solution
Call `logout()` on the auth store before navigating to clear the demo user session completely. This ensures:
- Auth store is cleared (`isAuthenticated = false`)
- User is properly logged out from demo session
- Navigation to `/demo` succeeds without authentication check
## Additional Improvements
- Also clear `virtual_tenant_id` and `subscription_tier` from localStorage
- Updated comment to clarify navigation intent
## Files Changed
- frontend/src/components/layout/DemoBanner/DemoBanner.tsx:73-74
- Added auth store logout before navigation
- Added clearing of virtual_tenant_id and subscription_tier
- Updated comment for clarity
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Prevent loadUserTenants from being called too early for demo sessions by excluding demo mode from the authenticated user auto-load logic.
## Problem
In enterprise demo sessions, loadUserTenants() was being called BEFORE child tenants were created, resulting in only the parent tenant (1 tenant) being returned instead of all 6 tenants (parent + 5 children).
Timeline of the race condition:
- 15:37:20: Session created, parent tenant cloning started
- 15:37:21: loadUserTenants() called by first useEffect → returned 1 tenant ❌
- 15:37:22: Child tenants created (5 tenants)
- 15:38:03: Session status changed to 'ready'
The first useEffect (for authenticated users) triggered immediately when isAuthenticated became true, calling loadUserTenants() at 15:37:21. This happened BEFORE the session polling logic in the second useEffect could wait for status='ready' and BEFORE child tenants were created.
## Solution
Added `!isDemoMode` condition to the first useEffect that auto-loads tenants for authenticated users. This ensures demo sessions use only the special initialization logic with session status polling (second useEffect), which waits for the session to be fully ready before loading tenants.
## Files Changed
- frontend/src/stores/useTenantInitializer.ts:61
- Added `&& !isDemoMode` to prevent early tenant loading for demo users
- Added dependency `isDemoMode` to useEffect dependency array
- Updated comment to clarify demo users have separate initialization
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
The gateway middleware was not including demo_account_type in the
request.state.user context, causing the tenant API to filter with
an empty account type.
## The Bug:
Gateway middleware set:
- demo_session_id ✅
- is_demo ✅
- demo_account_type ❌ MISSING!
This caused get_virtual_tenants_for_session() to be called with
demo_account_type="" (empty string), which returned only the parent
tenant instead of parent + 5 children.
## Log Evidence:
Before fix:
Demo session detected for get_user_tenants
demo_account_type= ← EMPTY!
tenant_count=1 ← Only parent!
After fix (expected):
Demo session detected for get_user_tenants
demo_account_type=enterprise
tenant_count=6 ← Parent + 5 children!
## Fix:
Added line 211 in gateway/app/middleware/demo_middleware.py:
"demo_account_type": session_info.get("demo_account_type", "professional")
This ensures the tenant service knows whether it's an enterprise or
professional demo session and returns the correct tenant list.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Implemented polling mechanism to wait for demo session to be fully ready
before attempting to load tenant list.
## The Problem:
Frontend was calling GET /tenants/user/demo-user/tenants immediately after
session creation, but tenant cloning is asynchronous and takes 5-10 seconds.
This caused the API to return empty array [] even though it returned 200 OK.
## The Solution:
Added pollSessionStatus() function that:
1. Polls /api/v1/demo-sessions/{session_id}/status every 1 second
2. Waits for status to become 'ready' (max 30 seconds)
3. Only loads tenants after session is confirmed ready
4. Logs detailed status updates for debugging
## Flow (Before):
User clicks demo → Session created → API called immediately → Empty []
## Flow (After):
User clicks demo → Session created → Poll status (1s interval) →
Status: initializing → cloning_data → ready → Load tenants → Success!
## Benefits:
✅ No more empty tenant lists due to timing
✅ Clear console logs showing progress
✅ Handles session failures gracefully
✅ Timeout protection (30 seconds max)
✅ Works for both enterprise (6 tenants) and professional (1 tenant)
## Console Output Example:
⏳ Session status poll 1/30: initializing
⏳ Session status poll 2/30: cloning_data
⏳ Session status poll 8/30: ready
✅ Demo session is ready!
🔄 Loading available tenants for enterprise demo...
📋 Loaded available tenants: 6
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Added detailed logging to help diagnose empty tenant list issues:
- Log demo_session_id, demo_account_type, and tenant_count
- Log actual tenant IDs returned
- Log when demo user detected but no session ID
This will help identify:
1. If demo_session_id is being passed correctly from gateway
2. If tenants exist in DB for the session
3. Timing issues (API called before session fully initialized)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit fixes a critical security issue where multiple concurrent demo
sessions would see each other's data due to sharing the same demo user IDs.
## The Problem:
When two enterprise demo sessions run simultaneously:
- Session A: user_id=Director, tenants=[parent_A, child_A1, child_A2]
- Session B: user_id=Director, tenants=[parent_B, child_B1, child_B2]
The endpoint /api/v1/tenants/user/{user_id}/tenants was querying by user_id
only, so Session A would see BOTH its own tenants AND Session B's tenants!
## The Solution:
Added demo_session_id filtering to get_user_tenants endpoint:
- For demo sessions, use get_virtual_tenants_for_session(demo_session_id)
- This filters tenants by the demo_session_id field (set during cloning)
- Each session now sees ONLY its own virtual tenants
## Implementation:
services/tenant/app/api/tenants.py (lines 180-194):
- Check if user is_demo
- Extract demo_session_id from current_user context (set by gateway)
- Call get_virtual_tenants_for_session() instead of get_user_tenants()
- This method filters by: demo_session_id + is_active + account_type
## Database Schema:
The tenants table has a demo_session_id column (indexed) that links
each virtual tenant to its specific demo session. This is set during
tenant cloning in internal_demo.py.
## Impact:
✅ Complete isolation between concurrent demo sessions
✅ Users only see their own session's data
✅ No performance impact (demo_session_id is indexed)
✅ Backward compatible (non-demo users unchanged)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
When the frontend requests tenants with user_id='demo-user' in demo mode,
the backend now correctly maps this to the actual demo owner ID from the
current_user context (set by the gateway middleware).
This fixes the issue where the tenant list API was returning empty results
even though it returned 200 OK, because it was looking for a user with
id='demo-user' which doesn't exist in the database.
The actual user IDs are:
- Professional: c1a2b3c4-d5e6-47a8-b9c0-d1e2f3a4b5c6 (María García López)
- Enterprise: d2e3f4a5-b6c7-48d9-e0f1-a2b3c4d5e6f7 (Director)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit refactors the demo session architecture to consolidate all demo
configuration data into the fixture files, removing redundant metadata files.
## Changes Made:
### 1. Data Consolidation
- **Removed**: `shared/demo/metadata/demo_users.json`
- **Removed**: `shared/demo/metadata/tenant_configs.json`
- **Updated**: Merged all user data into `02-auth.json` files
- **Updated**: Merged all tenant config data into `01-tenant.json` files
### 2. Enterprise Parent Tenant Updates
- Updated owner name to "Director" (matching auth fixtures)
- Added description field matching tenant_configs.json
- Added `base_tenant_id` to all child tenant entries
- Now includes all 5 child locations (Madrid, Barcelona, Valencia, Seville, Bilbao)
### 3. Professional Tenant Updates
- Added description field from tenant_configs.json
- Ensured consistency with auth fixtures
### 4. Code Updates
- **services/tenant/app/api/internal_demo.py**:
- Fixed child tenant staff members to use enterprise parent users
- Changed from professional staff IDs to enterprise staff IDs (Laura López, José Martínez, Francisco Moreno)
- **services/demo_session/app/core/config.py**:
- Updated DEMO_ACCOUNTS configuration with all 5 child outlets
- Updated enterprise tenant name and email to match fixtures
- Added descriptions for all child locations
- **gateway/app/middleware/demo_middleware.py**:
- Updated comments to reference fixture files as source of truth
- Clarified that owner IDs come from 01-tenant.json files
- **frontend/src/stores/useTenantInitializer.ts**:
- Updated tenant names and descriptions to match fixture files
- Added comments linking to source fixture files
## Benefits:
1. **Single Source of Truth**: All demo data now lives in fixture files
2. **Consistency**: No more sync issues between metadata and fixtures
3. **Maintainability**: Easier to update demo data (one place per tenant type)
4. **Clarity**: Clear separation between template data (fixtures) and runtime config
## Enterprise Demo Fix:
The enterprise owner is now correctly added as a member of all child tenants, fixing
the issue where the tenant switcher didn't show parent/child tenants and the
establishments page didn't load tenants for the demo enterprise user.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Documentation:
- FINAL_IMPLEMENTATION_SUMMARY.md: Executive summary of all work completed
* 8 critical bugs fixed across 5 services
* 11 documentation files created
* Complete testing and verification guide
* Performance metrics and lessons learned
- GIT_COMMIT_SUMMARY.md: Detailed breakdown of all 6 commits
* Commit-by-commit analysis with file changes
* Statistics and impact analysis
* Next steps and verification checklist
Summary:
This completes the AI insights implementation work. All identified issues
have been fixed, documented, and committed. After Docker image rebuild,
demo sessions will reliably generate 2-3 AI insights per session.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>