Improve demo tennat and user get

This commit is contained in:
Urtzi Alfaro
2026-01-17 09:19:42 +01:00
parent 4b65817b3e
commit fbc670ddb3
9 changed files with 225 additions and 88 deletions

View File

@@ -1,5 +1,5 @@
import { useEffect } from 'react';
import { useIsAuthenticated } from './auth.store';
import { useIsAuthenticated, useAuthStore } from './auth.store';
import { useTenantActions, useAvailableTenants, useCurrentTenant, useParentTenant } from './tenant.store';
import { useIsDemoMode, useDemoSessionId, useDemoAccountType } from '../hooks/useAccessControl';
import { useSubscription } from '../api/hooks/subscription';
@@ -19,29 +19,19 @@ const getDemoTierForAccountType = (accountType: string | null): SubscriptionTier
};
/**
* Defines appropriate tenant characteristics based on account type
* Gets tenant data from localStorage (set by DemoPage from backend response)
* Returns null if not available - caller must handle this case
*/
const getTenantDetailsForAccountType = (accountType: string | null) => {
// These details match the fixture files:
// professional: shared/demo/fixtures/professional/01-tenant.json
// enterprise: shared/demo/fixtures/enterprise/parent/01-tenant.json
const details = {
professional: {
name: 'Panadería Artesana Madrid - Demo',
business_type: 'bakery',
business_model: 'professional',
description: 'Professional tier demo tenant for bakery operations'
},
enterprise: {
name: 'Panadería Artesana España - Central',
business_type: 'bakery',
business_model: 'enterprise',
description: 'Central production facility and parent tenant for Panadería Artesana España multi-location bakery chain'
const getTenantDataFromStorage = (): Record<string, any> | null => {
const storedTenantData = localStorage.getItem('demo_tenant_data');
if (storedTenantData) {
try {
return JSON.parse(storedTenantData);
} catch (e) {
console.error('Failed to parse stored tenant data:', e);
}
};
const defaultDetails = details.professional;
return details[accountType as keyof typeof details] || defaultDetails;
}
return null;
};
/**
@@ -58,6 +48,8 @@ export const useTenantInitializer = () => {
const parentTenant = useParentTenant(); // Track if we're viewing a child tenant
const { loadUserTenants, loadChildTenants, setCurrentTenant, setAvailableTenants } = useTenantActions();
const { subscriptionInfo } = useSubscription();
// Use reactive hook for user to ensure re-run when auth store rehydrates
const authUser = useAuthStore((state) => state.user);
// Load tenants for authenticated users (but not demo users - they have special initialization below)
useEffect(() => {
@@ -101,30 +93,40 @@ export const useTenantInitializer = () => {
typeof currentTenant === 'object' &&
currentTenant.id === virtualTenantId;
// Determine the appropriate subscription tier based on stored value or account type
const subscriptionTier = storedTier as SubscriptionTier || getDemoTierForAccountType(demoAccountType);
// Get tenant data from localStorage (set by DemoPage from backend)
const tenantData = getTenantDataFromStorage();
// Use reactive authUser from hook instead of getState() to ensure re-run when user is available
const userId = authUser?.id;
// Get appropriate tenant details based on account type
const tenantDetails = getTenantDetailsForAccountType(demoAccountType);
// Guard: If no tenant data or user is available, skip tenant setup
// This means the demo session wasn't properly initialized or auth store hasn't rehydrated yet
if (!tenantData || !userId) {
console.log('[useTenantInitializer] Waiting for tenant data or user - tenantData:', !!tenantData, 'userId:', userId);
return;
}
// Create a complete tenant object matching TenantResponse structure
// Determine the appropriate subscription tier
const subscriptionTier = storedTier as SubscriptionTier || tenantData.subscription_tier || getDemoTierForAccountType(demoAccountType);
// Create a complete tenant object using data from backend response
const mockTenant = {
id: virtualTenantId,
name: tenantDetails.name,
subdomain: `demo-${demoSessionId.slice(0, 8)}`,
business_type: tenantDetails.business_type,
business_model: tenantDetails.business_model,
description: tenantDetails.description,
id: tenantData.id || virtualTenantId,
name: tenantData.name,
subdomain: tenantData.subdomain,
business_type: tenantData.business_type,
business_model: tenantData.business_model,
description: tenantData.description,
address: 'Demo Address',
city: 'Madrid',
postal_code: '28001',
phone: null,
is_active: true,
is_active: tenantData.is_active,
subscription_plan: subscriptionTier,
subscription_tier: subscriptionTier,
tenant_type: tenantData.tenant_type,
ml_model_trained: false,
last_training_date: null,
owner_id: 'demo-user',
owner_id: userId,
created_at: new Date().toISOString(),
};
@@ -179,5 +181,5 @@ export const useTenantInitializer = () => {
});
}
}
}, [isDemoMode, demoSessionId, demoAccountType, currentTenant, availableTenants, parentTenant, setCurrentTenant, setAvailableTenants]);
}, [isDemoMode, demoSessionId, demoAccountType, currentTenant, availableTenants, parentTenant, setCurrentTenant, setAvailableTenants, authUser]);
};