Start integrating the onboarding flow with backend 12

This commit is contained in:
Urtzi Alfaro
2025-09-07 17:25:30 +02:00
parent 9005286ada
commit b73f3b4993
32 changed files with 3172 additions and 3087 deletions

View File

@@ -6,10 +6,7 @@ import { classificationService } from '../services/classification';
import {
ProductClassificationRequest,
BatchClassificationRequest,
ProductSuggestionResponse,
BusinessModelAnalysisResponse,
ClassificationApprovalRequest,
ClassificationApprovalResponse,
ProductSuggestionResponse
} from '../types/classification';
import { ApiError } from '../client';
@@ -28,48 +25,6 @@ export const classificationKeys = {
},
} as const;
// Queries
export const usePendingSuggestions = (
tenantId: string,
options?: Omit<UseQueryOptions<ProductSuggestionResponse[], ApiError>, 'queryKey' | 'queryFn'>
) => {
return useQuery<ProductSuggestionResponse[], ApiError>({
queryKey: classificationKeys.suggestions.pending(tenantId),
queryFn: () => classificationService.getPendingSuggestions(tenantId),
enabled: !!tenantId,
staleTime: 30 * 1000, // 30 seconds
...options,
});
};
export const useSuggestionHistory = (
tenantId: string,
limit: number = 50,
offset: number = 0,
options?: Omit<UseQueryOptions<{ items: ProductSuggestionResponse[]; total: number }, ApiError>, 'queryKey' | 'queryFn'>
) => {
return useQuery<{ items: ProductSuggestionResponse[]; total: number }, ApiError>({
queryKey: classificationKeys.suggestions.history(tenantId, limit, offset),
queryFn: () => classificationService.getSuggestionHistory(tenantId, limit, offset),
enabled: !!tenantId,
staleTime: 2 * 60 * 1000, // 2 minutes
...options,
});
};
export const useBusinessModelAnalysis = (
tenantId: string,
options?: Omit<UseQueryOptions<BusinessModelAnalysisResponse, ApiError>, 'queryKey' | 'queryFn'>
) => {
return useQuery<BusinessModelAnalysisResponse, ApiError>({
queryKey: classificationKeys.analysis.businessModel(tenantId),
queryFn: () => classificationService.getBusinessModelAnalysis(tenantId),
enabled: !!tenantId,
staleTime: 10 * 60 * 1000, // 10 minutes
...options,
});
};
// Mutations
export const useClassifyProduct = (
options?: UseMutationOptions<
@@ -117,84 +72,4 @@ export const useClassifyProductsBatch = (
},
...options,
});
};
export const useApproveClassification = (
options?: UseMutationOptions<
ClassificationApprovalResponse,
ApiError,
{ tenantId: string; approvalData: ClassificationApprovalRequest }
>
) => {
const queryClient = useQueryClient();
return useMutation<
ClassificationApprovalResponse,
ApiError,
{ tenantId: string; approvalData: ClassificationApprovalRequest }
>({
mutationFn: ({ tenantId, approvalData }) =>
classificationService.approveClassification(tenantId, approvalData),
onSuccess: (data, { tenantId }) => {
// Invalidate suggestions lists
queryClient.invalidateQueries({ queryKey: classificationKeys.suggestions.pending(tenantId) });
queryClient.invalidateQueries({ queryKey: classificationKeys.suggestions.history(tenantId) });
// If approved and ingredient was created, invalidate inventory queries
if (data.approved && data.created_ingredient) {
queryClient.invalidateQueries({ queryKey: ['inventory', 'ingredients'] });
}
},
...options,
});
};
export const useUpdateSuggestion = (
options?: UseMutationOptions<
ProductSuggestionResponse,
ApiError,
{ tenantId: string; suggestionId: string; updateData: Partial<ProductSuggestionResponse> }
>
) => {
const queryClient = useQueryClient();
return useMutation<
ProductSuggestionResponse,
ApiError,
{ tenantId: string; suggestionId: string; updateData: Partial<ProductSuggestionResponse> }
>({
mutationFn: ({ tenantId, suggestionId, updateData }) =>
classificationService.updateSuggestion(tenantId, suggestionId, updateData),
onSuccess: (data, { tenantId }) => {
// Invalidate suggestions lists
queryClient.invalidateQueries({ queryKey: classificationKeys.suggestions.pending(tenantId) });
queryClient.invalidateQueries({ queryKey: classificationKeys.suggestions.history(tenantId) });
},
...options,
});
};
export const useDeleteSuggestion = (
options?: UseMutationOptions<
{ message: string },
ApiError,
{ tenantId: string; suggestionId: string }
>
) => {
const queryClient = useQueryClient();
return useMutation<
{ message: string },
ApiError,
{ tenantId: string; suggestionId: string }
>({
mutationFn: ({ tenantId, suggestionId }) =>
classificationService.deleteSuggestion(tenantId, suggestionId),
onSuccess: (data, { tenantId }) => {
// Invalidate suggestions lists
queryClient.invalidateQueries({ queryKey: classificationKeys.suggestions.pending(tenantId) });
queryClient.invalidateQueries({ queryKey: classificationKeys.suggestions.history(tenantId) });
},
...options,
});
};

View File

@@ -1,9 +1,19 @@
/**
* Onboarding Service - Mirror backend onboarding endpoints
* Frontend and backend step names now match directly!
*/
import { apiClient } from '../client';
import { UserProgress, UpdateStepRequest } from '../types/onboarding';
// Frontend step order for navigation (matches backend ONBOARDING_STEPS)
export const FRONTEND_STEP_ORDER = [
'setup', // Step 1: Basic bakery setup and tenant creation
'smart-inventory-setup', // Step 2: Sales data upload and inventory configuration
'suppliers', // Step 3: Suppliers configuration (optional)
'ml-training', // Step 4: AI model training
'completion' // Step 5: Onboarding completed
];
export class OnboardingService {
private readonly baseUrl = '/users/me/onboarding';
@@ -71,6 +81,65 @@ export class OnboardingService {
// This endpoint exists in backend
return apiClient.post(`${this.baseUrl}/complete`);
}
/**
* Helper method to mark a step as completed (now direct mapping)
*/
async markStepAsCompleted(
stepId: string,
data?: Record<string, any>
): Promise<UserProgress> {
try {
return await this.markStepCompleted('', stepId, data);
} catch (error) {
console.error(`Error marking step ${stepId} as completed:`, error);
throw error;
}
}
/**
* Helper method to get the next step based on backend progress
*/
async getNextStepId(): Promise<string> {
try {
const result = await this.getNextStep();
return result.step || 'setup';
} catch (error) {
console.error('Error getting next step:', error);
return 'setup';
}
}
/**
* Helper method to determine which step the user should resume from
*/
async getResumeStep(): Promise<{ stepId: string; stepIndex: number }> {
try {
const progress = await this.getUserProgress('');
// If fully completed, go to completion
if (progress.fully_completed) {
return { stepId: 'completion', stepIndex: FRONTEND_STEP_ORDER.indexOf('completion') };
}
// Get the current step from backend
const currentStep = progress.current_step;
// If current step is user_registered, start from setup
const resumeStep = currentStep === 'user_registered' ? 'setup' : currentStep;
// Find the step index in our frontend order
let stepIndex = FRONTEND_STEP_ORDER.indexOf(resumeStep);
if (stepIndex === -1) {
stepIndex = 0; // Default to first step
}
return { stepId: FRONTEND_STEP_ORDER[stepIndex], stepIndex };
} catch (error) {
console.error('Error determining resume step:', error);
return { stepId: 'setup', stepIndex: 0 };
}
}
}
export const onboardingService = new OnboardingService();

View File

@@ -26,4 +26,10 @@ export interface ProductSuggestionResponse {
is_seasonal: boolean;
suggested_supplier?: string;
notes?: string;
sales_data?: {
total_quantity: number;
average_daily_sales: number;
peak_day: string;
frequency: number;
};
}