2025-09-03 18:29:56 +02:00
|
|
|
import { useEffect } from 'react';
|
2025-09-05 17:49:48 +02:00
|
|
|
import { useIsAuthenticated } from './auth.store';
|
2025-10-03 14:09:34 +02:00
|
|
|
import { useTenantActions, useAvailableTenants, useCurrentTenant } from './tenant.store';
|
|
|
|
|
import { useIsDemoMode, useDemoSessionId, useDemoAccountType } from '../hooks/useAccessControl';
|
2025-09-03 18:29:56 +02:00
|
|
|
|
|
|
|
|
/**
|
2025-10-03 14:09:34 +02:00
|
|
|
* Hook to automatically initialize tenant data when user is authenticated or in demo mode
|
2025-09-03 18:29:56 +02:00
|
|
|
* This should be used at the app level to ensure tenant data is loaded
|
|
|
|
|
*/
|
|
|
|
|
export const useTenantInitializer = () => {
|
|
|
|
|
const isAuthenticated = useIsAuthenticated();
|
2025-10-03 14:09:34 +02:00
|
|
|
const isDemoMode = useIsDemoMode();
|
|
|
|
|
const demoSessionId = useDemoSessionId();
|
|
|
|
|
const demoAccountType = useDemoAccountType();
|
2025-09-03 18:29:56 +02:00
|
|
|
const availableTenants = useAvailableTenants();
|
2025-10-03 14:09:34 +02:00
|
|
|
const currentTenant = useCurrentTenant();
|
|
|
|
|
const { loadUserTenants, setCurrentTenant } = useTenantActions();
|
2025-09-03 18:29:56 +02:00
|
|
|
|
2025-10-03 14:09:34 +02:00
|
|
|
// Load tenants for authenticated users
|
2025-09-03 18:29:56 +02:00
|
|
|
useEffect(() => {
|
|
|
|
|
if (isAuthenticated && !availableTenants) {
|
|
|
|
|
loadUserTenants();
|
|
|
|
|
}
|
|
|
|
|
}, [isAuthenticated, availableTenants, loadUserTenants]);
|
|
|
|
|
|
2025-10-03 14:09:34 +02:00
|
|
|
// Set up mock tenant for demo mode
|
2025-09-03 18:29:56 +02:00
|
|
|
useEffect(() => {
|
2025-10-03 14:09:34 +02:00
|
|
|
if (isDemoMode && demoSessionId) {
|
|
|
|
|
const demoTenantId = localStorage.getItem('demo_tenant_id') || 'demo-tenant-id';
|
|
|
|
|
|
|
|
|
|
// Check if current tenant is the demo tenant and is properly set
|
|
|
|
|
const isValidDemoTenant = currentTenant &&
|
|
|
|
|
typeof currentTenant === 'object' &&
|
|
|
|
|
currentTenant.id === demoTenantId;
|
|
|
|
|
|
|
|
|
|
if (!isValidDemoTenant) {
|
|
|
|
|
const accountTypeName = demoAccountType === 'individual_bakery'
|
|
|
|
|
? 'Panadería San Pablo - Demo'
|
|
|
|
|
: 'Panadería La Espiga - Demo';
|
|
|
|
|
|
|
|
|
|
// Create a mock tenant object matching TenantResponse structure
|
|
|
|
|
const mockTenant = {
|
|
|
|
|
id: demoTenantId,
|
|
|
|
|
name: accountTypeName,
|
|
|
|
|
subdomain: `demo-${demoSessionId.slice(0, 8)}`,
|
|
|
|
|
plan_type: 'professional', // Use a valid plan type
|
|
|
|
|
is_active: true,
|
|
|
|
|
created_at: new Date().toISOString(),
|
|
|
|
|
updated_at: new Date().toISOString(),
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Set the demo tenant as current
|
|
|
|
|
setCurrentTenant(mockTenant);
|
|
|
|
|
}
|
2025-09-03 18:29:56 +02:00
|
|
|
}
|
2025-10-03 14:09:34 +02:00
|
|
|
}, [isDemoMode, demoSessionId, demoAccountType, currentTenant, setCurrentTenant]);
|
2025-09-03 18:29:56 +02:00
|
|
|
};
|