Fix new services implementation 11

This commit is contained in:
Urtzi Alfaro
2025-08-16 08:43:35 +02:00
parent 119beb541f
commit 995a51e285
8 changed files with 114 additions and 71 deletions

View File

@@ -224,6 +224,7 @@ export const useDashboard = () => {
return {
...dashboardData,
tenantId,
isLoading: isLoading || salesLoading || inventoryLoading || externalLoading || forecastLoading,
error: error || salesError || inventoryError || externalError || forecastError,
reload: () => tenantId ? loadDashboardData(tenantId) : Promise.resolve(),

View File

@@ -32,13 +32,16 @@ const SUPPLIERS: Record<string, string> = {
'Bolsas papel': 'Distribuciones Madrid',
};
export const useOrderSuggestions = () => {
export const useOrderSuggestions = (providedTenantId?: string | null) => {
const [dailyOrders, setDailyOrders] = useState<DailyOrderItem[]>([]);
const [weeklyOrders, setWeeklyOrders] = useState<WeeklyOrderItem[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const { tenantId, isLoading: tenantLoading, error: tenantError } = useTenantId();
const { tenantId: hookTenantId, isLoading: tenantLoading, error: tenantError } = useTenantId();
// Use provided tenant ID if available, otherwise use hook tenant ID
const tenantId = providedTenantId !== undefined ? providedTenantId : hookTenantId;
console.log('🏢 OrderSuggestions: Tenant info:', { tenantId, tenantLoading, tenantError });
const {
@@ -65,43 +68,32 @@ export const useOrderSuggestions = () => {
console.log('📊 OrderSuggestions: Generating daily suggestions for tenant:', tenantId);
// Get products list from backend
let products: string[] = [];
try {
products = await getProductsList(tenantId);
console.log('📋 OrderSuggestions: Products list:', products);
} catch (error) {
console.error('❌ OrderSuggestions: Failed to get products list:', error);
throw error;
}
const productsList = await getProductsList(tenantId);
const products = productsList.map(p => p.name);
console.log('📋 OrderSuggestions: Products list:', products);
// Filter for daily bakery products (case insensitive)
const dailyProductKeywords = ['pan', 'baguette', 'croissant', 'magdalena'];
const dailyProducts = products.filter(p =>
['Pan de Molde', 'Baguettes', 'Croissants', 'Magdalenas'].includes(p)
dailyProductKeywords.some(keyword =>
p.toLowerCase().includes(keyword.toLowerCase())
)
);
console.log('🥖 OrderSuggestions: Daily products:', dailyProducts);
// Get quick forecasts for these products
let quickForecasts: any[] = [];
try {
quickForecasts = await getQuickForecasts(tenantId);
console.log('🔮 OrderSuggestions: Quick forecasts:', quickForecasts);
} catch (error) {
console.error('❌ OrderSuggestions: Failed to get quick forecasts:', error);
throw error;
}
const quickForecasts = await getQuickForecasts(tenantId);
console.log('🔮 OrderSuggestions: Quick forecasts:', quickForecasts);
// Get weather data to determine urgency
let weather: any = null;
try {
weather = await getCurrentWeather(tenantId, 40.4168, -3.7038);
console.log('🌤️ OrderSuggestions: Weather data:', weather);
} catch (error) {
console.error('❌ OrderSuggestions: Failed to get current weather:', error);
throw error;
}
const weather = await getCurrentWeather(tenantId, 40.4168, -3.7038);
console.log('🌤️ OrderSuggestions: Weather data:', weather);
const suggestions: DailyOrderItem[] = [];
console.log('🔄 OrderSuggestions: Processing daily products:', dailyProducts);
for (const product of dailyProducts) {
console.log('🔄 OrderSuggestions: Processing product:', product);
// Find forecast for this product
const forecast = quickForecasts.find(f =>
f.product_name === product || f.inventory_product_id === product
@@ -145,14 +137,15 @@ export const useOrderSuggestions = () => {
};
suggestions.push(orderItem);
console.log(' OrderSuggestions: Added daily suggestion:', orderItem);
}
}
console.log('🎯 OrderSuggestions: Final daily suggestions:', suggestions);
return suggestions;
} catch (error) {
console.error('❌ OrderSuggestions: Error generating daily suggestions, using fallback:', error);
// Return mock data as fallback
return getMockDailyOrders();
console.error('❌ OrderSuggestions: Error in generateDailyOrderSuggestions:', error);
return [];
}
}, [tenantId, getProductsList, getQuickForecasts, getCurrentWeather]);
@@ -160,21 +153,14 @@ export const useOrderSuggestions = () => {
const generateWeeklyOrderSuggestions = useCallback(async (): Promise<WeeklyOrderItem[]> => {
if (!tenantId) return [];
try {
console.log('📊 OrderSuggestions: Generating weekly suggestions for tenant:', tenantId);
console.log('📊 OrderSuggestions: Generating weekly suggestions for tenant:', tenantId);
// Get sales analytics for the past month
const endDate = new Date().toISOString();
const startDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString();
let analytics: any = null;
try {
analytics = await getSalesAnalytics(tenantId, startDate, endDate);
console.log('📈 OrderSuggestions: Sales analytics:', analytics);
} catch (error) {
console.error('❌ OrderSuggestions: Failed to get sales analytics:', error);
throw error;
}
const analytics = await getSalesAnalytics(tenantId, startDate, endDate);
console.log('📈 OrderSuggestions: Sales analytics:', analytics);
// Weekly products (ingredients and supplies)
const weeklyProducts = [
@@ -221,11 +207,6 @@ export const useOrderSuggestions = () => {
}
return suggestions.sort((a, b) => a.stockDays - b.stockDays); // Sort by urgency
} catch (error) {
console.error('❌ OrderSuggestions: Error generating weekly suggestions, using fallback:', error);
// Return mock data as fallback
return getMockWeeklyOrders();
}
}, [tenantId, getSalesAnalytics]);
// Load order suggestions
@@ -233,10 +214,7 @@ export const useOrderSuggestions = () => {
console.log('🔍 OrderSuggestions: loadOrderSuggestions called, tenantId:', tenantId);
if (!tenantId) {
console.log('❌ OrderSuggestions: No tenantId available, loading mock data');
// Load mock data when tenant ID is not available
setDailyOrders(getMockDailyOrders());
setWeeklyOrders(getMockWeeklyOrders());
console.log('❌ OrderSuggestions: No tenantId available, skipping load');
return;
}
@@ -245,15 +223,21 @@ export const useOrderSuggestions = () => {
try {
console.log('📊 OrderSuggestions: Starting to generate suggestions...');
console.log('📊 OrderSuggestions: About to call generateDailyOrderSuggestions');
const [daily, weekly] = await Promise.all([
generateDailyOrderSuggestions(),
generateWeeklyOrderSuggestions()
]);
const dailyPromise = generateDailyOrderSuggestions();
console.log('📊 OrderSuggestions: About to call generateWeeklyOrderSuggestions');
const weeklyPromise = generateWeeklyOrderSuggestions();
console.log('📊 OrderSuggestions: Waiting for both promises to resolve...');
const [daily, weekly] = await Promise.all([dailyPromise, weeklyPromise]);
console.log('✅ OrderSuggestions: Generated suggestions:', {
dailyCount: daily.length,
weeklyCount: weekly.length
weeklyCount: weekly.length,
dailyData: daily,
weeklyData: weekly
});
setDailyOrders(daily);
@@ -268,9 +252,13 @@ export const useOrderSuggestions = () => {
// Load on mount and when tenant changes
useEffect(() => {
console.log('🔄 OrderSuggestions: useEffect triggered, tenantId:', tenantId);
loadOrderSuggestions();
}, [loadOrderSuggestions]);
console.log('🔄 OrderSuggestions: useEffect triggered, tenantId:', tenantId, 'tenantLoading:', tenantLoading);
// Only load if we have a tenantId or if tenant loading is complete
if (tenantId || !tenantLoading) {
loadOrderSuggestions();
}
}, [tenantId, tenantLoading, loadOrderSuggestions]);
return {
dailyOrders,