Files
bakery-ia/frontend/src/hooks/business/onboarding/services/useTenantCreation.ts

70 lines
2.2 KiB
TypeScript
Raw Normal View History

/**
* Tenant creation service - Clean, standardized implementation
*/
import { useCallback } from 'react';
import { useRegisterBakery } from '../../../../api';
import { useTenantStore } from '../../../../stores/tenant.store';
import { useOnboardingStore } from '../core/store';
import { createServiceHook } from '../utils/createServiceHook';
import type { TenantCreationState } from '../core/types';
import type { BakeryRegistration, TenantResponse } from '../../../../api';
const useTenantCreationService = createServiceHook<TenantCreationState>({
initialState: {
tenantData: null,
},
});
export const useTenantCreation = () => {
const service = useTenantCreationService();
const registerBakeryMutation = useRegisterBakery();
const { setCurrentTenant, loadUserTenants } = useTenantStore();
const { setStepData } = useOnboardingStore();
const createTenant = useCallback(async (bakeryData: BakeryRegistration): Promise<boolean> => {
if (!bakeryData) {
service.setError('Los datos de la panadería son requeridos');
return false;
}
const result = await service.executeAsync(async () => {
// Call API to register bakery
const tenantResponse: TenantResponse = await registerBakeryMutation.mutateAsync(bakeryData);
// Update tenant store
console.log('useTenantCreation - Setting current tenant:', tenantResponse);
setCurrentTenant(tenantResponse);
// Reload user tenants
await loadUserTenants();
// Update onboarding data
setStepData('setup', {
bakery: {
...bakeryData,
tenantCreated: true,
tenant_id: tenantResponse.id,
} as any,
});
console.log('useTenantCreation - Tenant created and set successfully');
return tenantResponse;
});
return result.success;
}, [service, registerBakeryMutation, setCurrentTenant, loadUserTenants, setStepData]);
return {
// State
isLoading: service.isLoading,
error: service.error,
isSuccess: service.isSuccess,
tenantData: service.tenantData,
// Actions
createTenant,
clearError: service.clearError,
reset: service.reset,
};
};