From 020acc4691505833e8d813b6032ae55b8b89094d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 10 Nov 2025 07:19:05 +0000 Subject: [PATCH] docs: Add comprehensive frontend/backend API alignment analysis Research findings for wizard improvements including: - Backend model analysis for all 6 services (Recipe, Customer, Supplier, Inventory, Quality Template, Customer Order) - Required vs optional fields identification - Frontend API types and hooks alignment check - Critical misalignment issues identified (PaymentTerms enum, API response types, field naming) - UX research for advanced options implementation This analysis supports the wizard enhancement effort to ensure proper field handling and identify areas for improvement. --- FRONTEND_API_ANALYSIS_SUMMARY.md | 241 +++++ FRONTEND_API_TYPES_ANALYSIS.md | 1741 ++++++++++++++++++++++++++++++ 2 files changed, 1982 insertions(+) create mode 100644 FRONTEND_API_ANALYSIS_SUMMARY.md create mode 100644 FRONTEND_API_TYPES_ANALYSIS.md diff --git a/FRONTEND_API_ANALYSIS_SUMMARY.md b/FRONTEND_API_ANALYSIS_SUMMARY.md new file mode 100644 index 00000000..790eb9bf --- /dev/null +++ b/FRONTEND_API_ANALYSIS_SUMMARY.md @@ -0,0 +1,241 @@ +# Frontend API Analysis - Executive Summary + +## Document Location +Complete analysis: `/home/user/bakery_ia/FRONTEND_API_TYPES_ANALYSIS.md` (1,741 lines) + +## Quick Overview + +### 1. RECIPE API +**File**: `/home/user/bakery_ia/frontend/src/api/types/recipes.ts` +**Hooks**: `/home/user/bakery_ia/frontend/src/api/hooks/recipes.ts` + +Key Types: RecipeCreate, RecipeUpdate, RecipeResponse, RecipeIngredientResponse, RecipeQualityConfiguration + +Key Hooks: +- Query: useRecipe, useRecipes, useInfiniteRecipes, useRecipeStatistics, useRecipeCategories, useRecipeFeasibility +- Mutation: useCreateRecipe, useUpdateRecipe, useDeleteRecipe, useArchiveRecipe, useDuplicateRecipe, useActivateRecipe + +--- + +### 2. SUPPLIER API +**File**: `/home/user/bakery_ia/frontend/src/api/types/suppliers.ts` +**Hooks**: `/home/user/bakery_ia/frontend/src/api/hooks/suppliers.ts` + +Key Types: +- Supplier: SupplierCreate, SupplierResponse, SupplierPriceListResponse +- Purchase Order: PurchaseOrderCreate, PurchaseOrderResponse +- Delivery: DeliveryCreate, DeliveryResponse +- Performance: PerformanceMetric, Alert, Scorecard + +Key Hooks: +- Supplier (8 query hooks): useSuppliers, useSupplier, useSupplierStatistics, useActiveSuppliers, etc. +- Purchase Orders (2 query hooks): usePurchaseOrders, usePurchaseOrder +- Deliveries (2 query hooks): useDeliveries, useDelivery +- Performance (2 query hooks): useSupplierPerformanceMetrics, usePerformanceAlerts +- Mutations (12 hooks): CRUD operations for all entities + +--- + +### 3. INVENTORY/PRODUCT API +**File**: `/home/user/bakery_ia/frontend/src/api/types/inventory.ts` +**Hooks**: `/home/user/bakery_ia/frontend/src/api/hooks/inventory.ts` + +Key Types: +- Ingredient: IngredientCreate, IngredientResponse +- Stock: StockCreate, StockResponse +- Stock Movement: StockMovementCreate, StockMovementResponse +- Transformation: ProductTransformationCreate, ProductTransformationResponse +- Food Safety: TemperatureLogResponse, FoodSafetyAlertResponse, FoodSafetyComplianceResponse +- Dashboard: InventoryDashboardSummary, InventoryAnalytics + +Key Hooks: +- Ingredients (4 query hooks): useIngredients, useIngredient, useIngredientsByCategory, useLowStockIngredients +- Stock (6 query hooks): useStock, useStockByIngredient, useExpiringStock, useExpiredStock, useStockMovements, useStockAnalytics +- Transformations (5 query hooks): useTransformations, useTransformation, useTransformationSummary, etc. +- Mutations (13 hooks): CRUD + specialized operations like useStockOperations, useTransformationOperations + +--- + +### 4. QUALITY TEMPLATE API +**File**: `/home/user/bakery_ia/frontend/src/api/types/qualityTemplates.ts` +**Hooks**: `/home/user/bakery_ia/frontend/src/api/hooks/qualityTemplates.ts` + +Key Types: +- QualityCheckTemplate, QualityCheckTemplateCreate, QualityCheckTemplateUpdate +- QualityCheckExecutionRequest, QualityCheckExecutionResponse +- ProcessStageQualityConfig, RecipeQualityConfiguration + +Key Hooks: +- Query (5 hooks): useQualityTemplates, useQualityTemplate, useQualityTemplatesForStage, useQualityTemplatesForRecipe, useDefaultQualityTemplates +- Mutation (6 hooks): useCreateQualityTemplate, useUpdateQualityTemplate, useDeleteQualityTemplate, useDuplicateQualityTemplate, useExecuteQualityCheck, useValidateQualityTemplate + +--- + +### 5. CUSTOMER ORDER API +**File**: `/home/user/bakery_ia/frontend/src/api/types/orders.ts` +**Hooks**: `/home/user/bakery_ia/frontend/src/api/hooks/orders.ts` + +Key Types: +- Customer: CustomerCreate, CustomerResponse +- Order: OrderCreate, OrderUpdate, OrderResponse +- OrderItem: OrderItemCreate, OrderItemResponse +- Dashboard: OrdersDashboardSummary +- Analytics: DemandRequirements, BusinessModelDetection + +Key Hooks: +- Query (7 hooks): useOrders, useOrder, useCustomers, useCustomer, useOrdersDashboard, useDemandRequirements, useBusinessModelDetection +- Mutation (4 hooks): useCreateOrder, useUpdateOrderStatus, useCreateCustomer, useUpdateCustomer +- Utility (1 hook): useInvalidateOrders + +--- + +## CRITICAL MISALIGNMENTS IDENTIFIED + +### 1. PAYMENT TERMS ENUM CONFLICT +Location: `suppliers.ts` vs `orders.ts` + +**Suppliers PaymentTerms:** +- COD, NET_15, NET_30, NET_45, NET_60, PREPAID, CREDIT_TERMS + +**Orders PaymentTerms:** +- IMMEDIATE, NET_30, NET_60 + +**Impact**: Two different enums with same name in different contexts could cause confusion and data inconsistency. + +**Recommendation**: Unify these enums or clarify their separate domains. + +--- + +### 2. DECIMAL VS NUMBER TYPE +**Affected APIs**: Suppliers, Orders + +**Issue**: Backend uses `Decimal` for monetary values: +- supplier.credit_limit +- supplier.total_spent +- customer.total_spent +- customer.average_order_value + +**Frontend**: Uses `number` type + +**Impact**: Floating-point precision loss for currency calculations (e.g., $1.23 - $1.20 != $0.03) + +**Recommendation**: Implement a Decimal wrapper type for all currency fields. + +--- + +### 3. STOCK FIELD NAME INCONSISTENCY +**Locations**: +- `StockCreate` interface defines: `unit_cost?: number` +- `useStockOperations` hook uses: `unit_price` parameter + +**Impact**: Potential API validation errors if hook sends wrong field name. + +**Recommendation**: Audit backend to verify correct field name and update frontend accordingly. + +--- + +### 4. PROCESS STAGE VS PRODUCTION STAGE CONFUSION +**Quality Templates Define:** +- MIXING, PROOFING, SHAPING, BAKING, COOLING, PACKAGING, FINISHING + +**Inventory Defines:** +- RAW_INGREDIENT, PAR_BAKED, FULLY_BAKED, PREPARED_DOUGH, FROZEN_PRODUCT + +**Note**: These are intentionally different (quality control vs production) - correctly separated but documentation needed. + +--- + +### 5. RECORD OVERUSE +Multiple type definitions use `Record` for flexibility: +- instructions +- parameters +- thresholds +- scoring_criteria +- custom_requirements +- allergen_warnings + +**Risk**: Loose typing defeats TypeScript's safety benefits. + +**Recommendation**: Define specific interfaces for complex nested structures. + +--- + +### 6. CREATED_BY FIELD HANDLING +**Quality Templates**: `QualityCheckTemplateCreate` requires `created_by: string` + +**Issue**: Forms typically auto-fill from authenticated user context, not user input. + +**Recommendation**: Verify API makes this optional or frontend passes authenticated user ID. + +--- + +### 7. PRODUCT CLASSIFICATION +**Location**: inventory.ts - ProductSuggestionResponse, BatchClassificationResponse + +**Potential Issue**: These suggest AI-based classification but exact API endpoints may differ from implementation. + +**Recommendation**: Verify API contract matches suggestion response structure. + +--- + +## STATISTICS + +Total TypeScript type definitions: **150+** +Total React hooks: **80+** +Total enums: **40+** + +### By Domain: +- Recipes: 20 types, 10 hooks +- Suppliers: 35 types, 25 hooks +- Inventory: 25 types, 20 hooks +- Quality Templates: 12 types, 6 hooks +- Orders/Customers: 18 types, 7 hooks + +--- + +## KEY SERVICES LOCATION + +All services are located in: `/home/user/bakery_ia/frontend/src/api/services/` + +Main service files: +- recipes.ts +- suppliers.ts +- inventory.ts +- qualityTemplates.ts +- orders.ts +- procurement-service.ts +- purchase_orders.ts +- production.ts + +--- + +## RECOMMENDATIONS FOR CLEANUP + +1. **Priority 1 (Critical)** + - Unify PaymentTerms enums + - Fix Decimal type handling for currencies + - Verify stock field names (unit_cost vs unit_price) + +2. **Priority 2 (Important)** + - Replace Record with specific types + - Add validators matching backend + - Document ProcessStage vs ProductionStage distinction + +3. **Priority 3 (Nice to Have)** + - Create shared enum definitions + - Add JSDoc comments for all type fields + - Implement Decimal wrapper for all monetary values + - Create type guards for enum validation + +--- + +## FILES FOR FURTHER REVIEW + +Backend schema files (for comparison): +- `/home/user/bakery_ia/services/recipes/app/schemas/recipes.py` +- `/home/user/bakery_ia/services/orders/app/schemas/order_schemas.py` +- `/home/user/bakery_ia/services/production/app/schemas/quality_templates.py` +- `/home/user/bakery_ia/services/suppliers/app/schemas/suppliers.py` +- `/home/user/bakery_ia/services/suppliers/app/schemas/performance.py` +- `/home/user/bakery_ia/services/inventory/app/schemas/inventory.py` + diff --git a/FRONTEND_API_TYPES_ANALYSIS.md b/FRONTEND_API_TYPES_ANALYSIS.md new file mode 100644 index 00000000..7ce10235 --- /dev/null +++ b/FRONTEND_API_TYPES_ANALYSIS.md @@ -0,0 +1,1741 @@ +# Frontend API Types, Services, and Hooks - Complete Analysis + +## Overview +This document provides a comprehensive analysis of all frontend API types, services, and hooks across 6 major domains in the Bakery IA application, along with identified misalignments with the backend. + +--- + +## 1. RECIPE API + +### Frontend Type Definitions + +#### Enums +```typescript +export enum RecipeStatus { + DRAFT = 'draft', + ACTIVE = 'active', + TESTING = 'testing', + ARCHIVED = 'archived', + DISCONTINUED = 'discontinued' +} + +export enum MeasurementUnit { + GRAMS = 'g', + KILOGRAMS = 'kg', + MILLILITERS = 'ml', + LITERS = 'l', + CUPS = 'cups', + TABLESPOONS = 'tbsp', + TEASPOONS = 'tsp', + UNITS = 'units', + PIECES = 'pieces', + PERCENTAGE = '%' +} + +export enum ProductionStatus { + PLANNED = 'planned', + IN_PROGRESS = 'in_progress', + COMPLETED = 'completed', + FAILED = 'failed', + CANCELLED = 'cancelled' +} +``` + +#### Quality Configuration Types +```typescript +export interface QualityStageConfiguration { + template_ids?: string[]; + required_checks?: string[]; + optional_checks?: string[]; + blocking_on_failure?: boolean; + min_quality_score?: number | null; +} + +export interface RecipeQualityConfiguration { + stages?: Record; + overall_quality_threshold?: number; // Default: 7.0 + critical_stage_blocking?: boolean; + auto_create_quality_checks?: boolean; + quality_manager_approval_required?: boolean; +} + +export interface RecipeQualityConfigurationUpdate { + stages?: Record | null; + overall_quality_threshold?: number | null; + critical_stage_blocking?: boolean | null; + auto_create_quality_checks?: boolean | null; + quality_manager_approval_required?: boolean | null; +} +``` + +#### Recipe Ingredient Types +```typescript +export interface RecipeIngredientCreate { + ingredient_id: string; + quantity: number; // gt=0 + unit: MeasurementUnit; + alternative_quantity?: number | null; + alternative_unit?: MeasurementUnit | null; + preparation_method?: string | null; + ingredient_notes?: string | null; + is_optional?: boolean; + ingredient_order: number; // ge=1 + ingredient_group?: string | null; + substitution_options?: Record | null; + substitution_ratio?: number | null; +} + +export interface RecipeIngredientUpdate { + ingredient_id?: string | null; + quantity?: number | null; + unit?: MeasurementUnit | null; + alternative_quantity?: number | null; + alternative_unit?: MeasurementUnit | null; + preparation_method?: string | null; + ingredient_notes?: string | null; + is_optional?: boolean | null; + ingredient_order?: number | null; + ingredient_group?: string | null; + substitution_options?: Record | null; + substitution_ratio?: number | null; +} + +export interface RecipeIngredientResponse { + id: string; + tenant_id: string; + recipe_id: string; + ingredient_id: string; + quantity: number; + unit: string; + quantity_in_base_unit?: number | null; + alternative_quantity?: number | null; + alternative_unit?: string | null; + preparation_method?: string | null; + ingredient_notes?: string | null; + is_optional: boolean; + ingredient_order: number; + ingredient_group?: string | null; + substitution_options?: Record | null; + substitution_ratio?: number | null; + unit_cost?: number | null; + total_cost?: number | null; + cost_updated_at?: string | null; +} +``` + +#### Recipe CRUD Types +```typescript +export interface RecipeCreate { + name: string; // min_length=1, max_length=255 + recipe_code?: string | null; + version?: string; // Default: "1.0" + finished_product_id: string; + description?: string | null; + category?: string | null; + cuisine_type?: string | null; + difficulty_level?: number; // Default: 1, ge=1, le=5 + yield_quantity: number; // gt=0 + yield_unit: MeasurementUnit; + prep_time_minutes?: number | null; + cook_time_minutes?: number | null; + total_time_minutes?: number | null; + rest_time_minutes?: number | null; + instructions?: Record | null; + preparation_notes?: string | null; + storage_instructions?: string | null; + quality_standards?: string | null; + quality_check_configuration?: RecipeQualityConfiguration | null; + serves_count?: number | null; + nutritional_info?: Record | null; + allergen_info?: Record | null; + dietary_tags?: Record | null; + batch_size_multiplier?: number; // Default: 1.0, gt=0 + minimum_batch_size?: number | null; + maximum_batch_size?: number | null; + optimal_production_temperature?: number | null; + optimal_humidity?: number | null; + quality_check_points?: Record | null; + common_issues?: Record | null; + is_seasonal?: boolean; + season_start_month?: number | null; + season_end_month?: number | null; + is_signature_item?: boolean; + target_margin_percentage?: number | null; + ingredients: RecipeIngredientCreate[]; // min_items=1 +} + +export interface RecipeUpdate { + name?: string | null; + recipe_code?: string | null; + version?: string | null; + description?: string | null; + category?: string | null; + cuisine_type?: string | null; + difficulty_level?: number | null; + yield_quantity?: number | null; + yield_unit?: MeasurementUnit | null; + prep_time_minutes?: number | null; + cook_time_minutes?: number | null; + total_time_minutes?: number | null; + rest_time_minutes?: number | null; + instructions?: Record | null; + preparation_notes?: string | null; + storage_instructions?: string | null; + quality_standards?: string | null; + quality_check_configuration?: RecipeQualityConfigurationUpdate | null; + serves_count?: number | null; + nutritional_info?: Record | null; + allergen_info?: Record | null; + dietary_tags?: Record | null; + batch_size_multiplier?: number | null; + minimum_batch_size?: number | null; + maximum_batch_size?: number | null; + optimal_production_temperature?: number | null; + optimal_humidity?: number | null; + quality_check_points?: Record | null; + common_issues?: Record | null; + status?: RecipeStatus | null; + is_seasonal?: boolean | null; + season_start_month?: number | null; + season_end_month?: number | null; + is_signature_item?: boolean | null; + target_margin_percentage?: number | null; + ingredients?: RecipeIngredientCreate[] | null; +} + +export interface RecipeResponse { + id: string; + tenant_id: string; + name: string; + recipe_code?: string | null; + version: string; + finished_product_id: string; + description?: string | null; + category?: string | null; + cuisine_type?: string | null; + difficulty_level: number; + yield_quantity: number; + yield_unit: string; + prep_time_minutes?: number | null; + cook_time_minutes?: number | null; + total_time_minutes?: number | null; + rest_time_minutes?: number | null; + estimated_cost_per_unit?: number | null; + last_calculated_cost?: number | null; + cost_calculation_date?: string | null; + target_margin_percentage?: number | null; + suggested_selling_price?: number | null; + instructions?: Record | null; + preparation_notes?: string | null; + storage_instructions?: string | null; + quality_standards?: string | null; + quality_check_configuration?: RecipeQualityConfiguration | null; + serves_count?: number | null; + nutritional_info?: Record | null; + allergen_info?: Record | null; + dietary_tags?: Record | null; + batch_size_multiplier: number; + minimum_batch_size?: number | null; + maximum_batch_size?: number | null; + optimal_production_temperature?: number | null; + optimal_humidity?: number | null; + quality_check_points?: Record | null; + common_issues?: Record | null; + status: string; + is_seasonal: boolean; + season_start_month?: number | null; + season_end_month?: number | null; + is_signature_item: boolean; + created_at: string; + updated_at: string; + created_by?: string | null; + updated_by?: string | null; + ingredients?: RecipeIngredientResponse[] | null; +} + +export interface RecipeSearchRequest { + search_term?: string | null; + status?: RecipeStatus | null; + category?: string | null; + is_seasonal?: boolean | null; + is_signature?: boolean | null; + difficulty_level?: number | null; + limit?: number; // Default: 100 + offset?: number; // Default: 0 +} + +export interface RecipeFeasibilityResponse { + recipe_id: string; + recipe_name: string; + batch_multiplier: number; + feasible: boolean; + missing_ingredients: Array>; + insufficient_ingredients: Array>; +} + +export interface RecipeStatisticsResponse { + total_recipes: number; + active_recipes: number; + signature_recipes: number; + seasonal_recipes: number; + category_breakdown: Array>; +} +``` + +### Recipe Hooks +```typescript +// Query Hooks +useRecipe(tenantId, recipeId) - Fetch single recipe +useRecipes(tenantId, filters) - Search/list recipes with filters +useInfiniteRecipes(tenantId, filters) - Infinite query for pagination +useRecipeStatistics(tenantId) - Get recipe statistics +useRecipeCategories(tenantId) - Get available categories +useRecipeFeasibility(tenantId, recipeId, batchMultiplier) - Check feasibility +useRecipeDeletionSummary(tenantId, recipeId) - Get deletion summary + +// Mutation Hooks +useCreateRecipe(tenantId) - Create new recipe +useUpdateRecipe(tenantId) - Update existing recipe +useDeleteRecipe(tenantId) - Delete recipe +useArchiveRecipe(tenantId) - Soft delete +useDuplicateRecipe(tenantId) - Duplicate recipe +useActivateRecipe(tenantId) - Activate recipe +``` + +--- + +## 2. SUPPLIER API + +### Frontend Type Definitions + +#### Enums +```typescript +export enum SupplierType { + INGREDIENTS = 'ingredients', + PACKAGING = 'packaging', + EQUIPMENT = 'equipment', + SERVICES = 'services', + UTILITIES = 'utilities', + MULTI = 'multi' +} + +export enum SupplierStatus { + ACTIVE = 'active', + INACTIVE = 'inactive', + PENDING_APPROVAL = 'pending_approval', + SUSPENDED = 'suspended', + BLACKLISTED = 'blacklisted' +} + +export enum PaymentTerms { + COD = 'cod', + NET_15 = 'net_15', + NET_30 = 'net_30', + NET_45 = 'net_45', + NET_60 = 'net_60', + PREPAID = 'prepaid', + CREDIT_TERMS = 'credit_terms' +} + +export enum PurchaseOrderStatus { + DRAFT = 'draft', + PENDING_APPROVAL = 'pending_approval', + APPROVED = 'approved', + SENT_TO_SUPPLIER = 'sent_to_supplier', + CONFIRMED = 'confirmed', + PARTIALLY_RECEIVED = 'partially_received', + COMPLETED = 'completed', + CANCELLED = 'cancelled', + DISPUTED = 'disputed' +} + +export enum DeliveryStatus { + SCHEDULED = 'scheduled', + IN_TRANSIT = 'in_transit', + OUT_FOR_DELIVERY = 'out_for_delivery', + DELIVERED = 'delivered', + PARTIALLY_DELIVERED = 'partially_delivered', + FAILED_DELIVERY = 'failed_delivery', + RETURNED = 'returned' +} + +export enum QualityRating { + EXCELLENT = 5, + GOOD = 4, + AVERAGE = 3, + POOR = 2, + VERY_POOR = 1 +} + +export enum DeliveryRating { + EXCELLENT = 5, + GOOD = 4, + AVERAGE = 3, + POOR = 2, + VERY_POOR = 1 +} + +export enum InvoiceStatus { + PENDING = 'pending', + APPROVED = 'approved', + PAID = 'paid', + OVERDUE = 'overdue', + DISPUTED = 'disputed', + CANCELLED = 'cancelled' +} + +export enum OrderPriority { + NORMAL = 'normal', + HIGH = 'high', + URGENT = 'urgent' +} + +export enum AlertSeverity { + CRITICAL = 'CRITICAL', + HIGH = 'HIGH', + MEDIUM = 'MEDIUM', + LOW = 'LOW', + INFO = 'INFO' +} + +export enum AlertType { + POOR_QUALITY = 'POOR_QUALITY', + LATE_DELIVERY = 'LATE_DELIVERY', + PRICE_INCREASE = 'PRICE_INCREASE', + LOW_PERFORMANCE = 'LOW_PERFORMANCE', + CONTRACT_EXPIRY = 'CONTRACT_EXPIRY', + COMPLIANCE_ISSUE = 'COMPLIANCE_ISSUE', + FINANCIAL_RISK = 'FINANCIAL_RISK', + COMMUNICATION_ISSUE = 'COMMUNICATION_ISSUE', + CAPACITY_CONSTRAINT = 'CAPACITY_CONSTRAINT', + CERTIFICATION_EXPIRY = 'CERTIFICATION_EXPIRY' +} + +export enum AlertStatus { + ACTIVE = 'ACTIVE', + ACKNOWLEDGED = 'ACKNOWLEDGED', + IN_PROGRESS = 'IN_PROGRESS', + RESOLVED = 'RESOLVED', + DISMISSED = 'DISMISSED' +} + +export enum PerformanceMetricType { + DELIVERY_PERFORMANCE = 'DELIVERY_PERFORMANCE', + QUALITY_SCORE = 'QUALITY_SCORE', + PRICE_COMPETITIVENESS = 'PRICE_COMPETITIVENESS', + COMMUNICATION_RATING = 'COMMUNICATION_RATING', + ORDER_ACCURACY = 'ORDER_ACCURACY', + RESPONSE_TIME = 'RESPONSE_TIME', + COMPLIANCE_SCORE = 'COMPLIANCE_SCORE', + FINANCIAL_STABILITY = 'FINANCIAL_STABILITY' +} + +export enum PerformancePeriod { + DAILY = 'DAILY', + WEEKLY = 'WEEKLY', + MONTHLY = 'MONTHLY', + QUARTERLY = 'QUARTERLY', + YEARLY = 'YEARLY' +} +``` + +#### Supplier Types +```typescript +export interface SupplierCreate { + name: string; // min_length=1, max_length=255 + supplier_code?: string | null; + tax_id?: string | null; + registration_number?: string | null; + supplier_type: SupplierType; + contact_person?: string | null; + email?: string | null; + phone?: string | null; + mobile?: string | null; + website?: string | null; + address_line1?: string | null; + address_line2?: string | null; + city?: string | null; + state_province?: string | null; + postal_code?: string | null; + country?: string | null; + payment_terms?: PaymentTerms; // Default: net_30 + credit_limit?: number | null; + currency?: string; // Default: "EUR" + standard_lead_time?: number; // Default: 3 + minimum_order_amount?: number | null; + delivery_area?: string | null; + notes?: string | null; + certifications?: Record | null; + business_hours?: Record | null; + specializations?: Record | null; +} + +export interface SupplierResponse { + id: string; + tenant_id: string; + name: string; + supplier_code: string | null; + tax_id: string | null; + registration_number: string | null; + supplier_type: SupplierType; + status: SupplierStatus; + contact_person: string | null; + email: string | null; + phone: string | null; + mobile: string | null; + website: string | null; + address_line1: string | null; + address_line2: string | null; + city: string | null; + state_province: string | null; + postal_code: string | null; + country: string | null; + payment_terms: PaymentTerms; + credit_limit: number | null; + currency: string; + standard_lead_time: number; + minimum_order_amount: number | null; + delivery_area: string | null; + quality_rating: number | null; + delivery_rating: number | null; + total_orders: number; + total_amount: number; + approved_by: string | null; + approved_at: string | null; + rejection_reason: string | null; + notes: string | null; + certifications: Record | null; + business_hours: Record | null; + specializations: Record | null; + created_at: string; + updated_at: string; + created_by: string; + updated_by: string; +} + +export interface SupplierPriceListCreate { + inventory_product_id: string; + product_code?: string | null; + unit_price: number; // gt=0 + unit_of_measure: string; + minimum_order_quantity?: number | null; + price_per_unit: number; + tier_pricing?: Record | null; + effective_date?: string; + expiry_date?: string | null; + is_active?: boolean; + brand?: string | null; + packaging_size?: string | null; + origin_country?: string | null; + shelf_life_days?: number | null; + storage_requirements?: string | null; + quality_specs?: Record | null; + allergens?: Record | null; +} + +export interface SupplierPriceListResponse { + id: string; + tenant_id: string; + supplier_id: string; + inventory_product_id: string; + product_code: string | null; + unit_price: number; + unit_of_measure: string; + minimum_order_quantity: number | null; + price_per_unit: number; + tier_pricing: Record | null; + effective_date: string; + expiry_date: string | null; + is_active: boolean; + brand: string | null; + packaging_size: string | null; + origin_country: string | null; + shelf_life_days: number | null; + storage_requirements: string | null; + quality_specs: Record | null; + allergens: Record | null; + created_at: string; + updated_at: string; + created_by: string; + updated_by: string; +} +``` + +#### Purchase Order Types +```typescript +export interface PurchaseOrderItemCreate { + inventory_product_id: string; + product_code?: string | null; + ordered_quantity: number; // gt=0 + unit_of_measure: string; + unit_price: number; // gt=0 + quality_requirements?: string | null; + item_notes?: string | null; +} + +export interface PurchaseOrderCreate { + supplier_id: string; + items: PurchaseOrderItemCreate[]; // min_items=1 + reference_number?: string | null; + priority?: string; // Default: "normal" + required_delivery_date?: string | null; + delivery_address?: string | null; + delivery_instructions?: string | null; + delivery_contact?: string | null; + delivery_phone?: string | null; + tax_amount?: number; + shipping_cost?: number; + discount_amount?: number; + notes?: string | null; + internal_notes?: string | null; + terms_and_conditions?: string | null; +} + +export interface PurchaseOrderResponse { + id: string; + tenant_id: string; + supplier_id: string; + po_number: string; + status: PurchaseOrderStatus; + order_date: string; + reference_number: string | null; + priority: string; + required_delivery_date: string | null; + estimated_delivery_date: string | null; + subtotal: number; + tax_amount: number; + shipping_cost: number; + discount_amount: number; + total_amount: number; + currency: string; + delivery_address: string | null; + delivery_instructions: string | null; + delivery_contact: string | null; + delivery_phone: string | null; + requires_approval: boolean; + approved_by: string | null; + approved_at: string | null; + rejection_reason: string | null; + sent_to_supplier_at: string | null; + supplier_confirmation_date: string | null; + supplier_reference: string | null; + notes: string | null; + internal_notes: string | null; + terms_and_conditions: string | null; + created_at: string; + updated_at: string; + created_by: string; + updated_by: string; + supplier?: SupplierSummary | null; + items?: PurchaseOrderItemResponse[] | null; +} +``` + +#### Delivery Types +```typescript +export interface DeliveryItemCreate { + purchase_order_item_id: string; + inventory_product_id: string; + ordered_quantity: number; // gt=0 + delivered_quantity: number; // ge=0 + accepted_quantity: number; // ge=0 + rejected_quantity?: number; // Default: 0 + batch_lot_number?: string | null; + expiry_date?: string | null; + quality_grade?: string | null; + quality_issues?: string | null; + rejection_reason?: string | null; + item_notes?: string | null; +} + +export interface DeliveryCreate { + purchase_order_id: string; + supplier_id: string; + items: DeliveryItemCreate[]; // min_items=1 + supplier_delivery_note?: string | null; + scheduled_date?: string | null; + estimated_arrival?: string | null; + delivery_address?: string | null; + delivery_contact?: string | null; + delivery_phone?: string | null; + carrier_name?: string | null; + tracking_number?: string | null; + notes?: string | null; +} + +export interface DeliveryResponse { + id: string; + tenant_id: string; + purchase_order_id: string; + supplier_id: string; + delivery_number: string; + status: DeliveryStatus; + scheduled_date: string | null; + estimated_arrival: string | null; + actual_arrival: string | null; + completed_at: string | null; + supplier_delivery_note: string | null; + delivery_address: string | null; + delivery_contact: string | null; + delivery_phone: string | null; + carrier_name: string | null; + tracking_number: string | null; + inspection_passed: boolean | null; + inspection_notes: string | null; + quality_issues: Record | null; + received_by: string | null; + received_at: string | null; + notes: string | null; + photos: Record | null; + created_at: string; + updated_at: string; + created_by: string; + supplier?: SupplierSummary | null; + purchase_order?: PurchaseOrderSummary | null; + items?: DeliveryItemResponse[] | null; +} +``` + +#### Performance Types +```typescript +export interface PerformanceMetricCreate { + supplier_id: string; + metric_type: PerformanceMetricType; + period: PerformancePeriod; + period_start: string; + period_end: string; + metric_value: number; // ge=0, le=100 + target_value?: number | null; + total_orders?: number; + total_deliveries?: number; + on_time_deliveries?: number; + late_deliveries?: number; + quality_issues?: number; + total_amount?: number; + notes?: string | null; + metrics_data?: Record | null; + external_factors?: Record | null; +} + +export interface PerformanceMetric extends PerformanceMetricCreate { + id: string; + tenant_id: string; + previous_value: number | null; + trend_direction: string | null; + trend_percentage: number | null; + calculated_at: string; +} + +export interface AlertCreate { + supplier_id: string; + alert_type: AlertType; + severity: AlertSeverity; + title: string; + message: string; + description?: string | null; + trigger_value?: number | null; + threshold_value?: number | null; + metric_type?: PerformanceMetricType | null; + purchase_order_id?: string | null; + delivery_id?: string | null; + performance_metric_id?: string | null; + recommended_actions?: Array> | null; + auto_resolve?: boolean; + priority_score?: number; + business_impact?: string | null; + tags?: string[] | null; +} + +export interface Alert extends Omit { + id: string; + tenant_id: string; + status: AlertStatus; + triggered_at: string; + acknowledged_at: string | null; + acknowledged_by: string | null; + resolved_at: string | null; + resolved_by: string | null; + actions_taken: Array> | null; + resolution_notes: string | null; + escalated: boolean; + escalated_at: string | null; + notification_sent: boolean; + created_at: string; +} + +export interface ScorecardCreate { + supplier_id: string; + scorecard_name: string; + period: PerformancePeriod; + period_start: string; + period_end: string; + overall_score: number; + quality_score: number; + delivery_score: number; + cost_score: number; + service_score: number; + on_time_delivery_rate: number; + quality_rejection_rate: number; + order_accuracy_rate: number; + response_time_hours: number; + cost_variance_percentage: number; + total_orders_processed?: number; + total_amount_processed?: number; + average_order_value?: number; + cost_savings_achieved?: number; + strengths?: string[] | null; + improvement_areas?: string[] | null; + recommended_actions?: Array> | null; + notes?: string | null; +} + +export interface Scorecard extends ScorecardCreate { + id: string; + tenant_id: string; + overall_rank: number | null; + category_rank: number | null; + total_suppliers_evaluated: number | null; + score_trend: string | null; + score_change_percentage: number | null; + is_final: boolean; + approved_by: string | null; + approved_at: string | null; + attachments: Record | null; + generated_at: string; + generated_by: string | null; +} +``` + +### Supplier Hooks +```typescript +// Supplier Query Hooks +useSuppliers(tenantId, queryParams) - List suppliers +useSupplier(tenantId, supplierId) - Get single supplier +useSupplierStatistics(tenantId) - Get supplier statistics +useActiveSuppliers(tenantId, queryParams) - Get active suppliers +useTopSuppliers(tenantId) - Get top performing suppliers +usePendingApprovalSuppliers(tenantId) - Get pending approval suppliers +useSuppliersByType(tenantId, supplierType, queryParams) - Filter by type + +// Purchase Order Query Hooks +usePurchaseOrders(tenantId, queryParams) - List purchase orders +usePurchaseOrder(tenantId, orderId) - Get single purchase order + +// Delivery Query Hooks +useDeliveries(tenantId, queryParams) - List deliveries +useDelivery(tenantId, deliveryId) - Get single delivery + +// Supplier Price List Query Hooks +useSupplierPriceLists(tenantId, supplierId, isActive) - Get price lists +useSupplierPriceList(tenantId, supplierId, priceListId) - Get single price list + +// Performance Query Hooks +useSupplierPerformanceMetrics(tenantId, supplierId) - Get performance metrics +usePerformanceAlerts(tenantId, supplierId) - Get performance alerts + +// Supplier Mutation Hooks +useCreateSupplier() - Create supplier +useUpdateSupplier() - Update supplier +useApproveSupplier() - Approve supplier +useDeleteSupplier() - Delete supplier +useHardDeleteSupplier() - Hard delete supplier + +// Purchase Order Mutation Hooks +useCreatePurchaseOrder() - Create PO +useUpdatePurchaseOrder() - Update PO +useApprovePurchaseOrder() - Approve PO + +// Delivery Mutation Hooks +useCreateDelivery() - Create delivery +useUpdateDelivery() - Update delivery +useConfirmDeliveryReceipt() - Confirm delivery receipt + +// Supplier Price List Mutation Hooks +useCreateSupplierPriceList() - Create price list +useUpdateSupplierPriceList() - Update price list +useDeleteSupplierPriceList() - Delete price list + +// Performance Mutation Hooks +useCalculateSupplierPerformance() - Calculate performance +useEvaluatePerformanceAlerts() - Evaluate alerts +``` + +--- + +## 3. INVENTORY/PRODUCT API + +### Frontend Type Definitions + +#### Enums +```typescript +export enum ProductType { + INGREDIENT = 'ingredient', + FINISHED_PRODUCT = 'finished_product' +} + +export enum ProductionStage { + RAW_INGREDIENT = 'raw_ingredient', + PAR_BAKED = 'par_baked', + FULLY_BAKED = 'fully_baked', + PREPARED_DOUGH = 'prepared_dough', + FROZEN_PRODUCT = 'frozen_product' +} + +export enum UnitOfMeasure { + KILOGRAMS = 'kg', + GRAMS = 'g', + LITERS = 'l', + MILLILITERS = 'ml', + UNITS = 'units', + PIECES = 'pcs', + PACKAGES = 'pkg', + BAGS = 'bags', + BOXES = 'boxes' +} + +export enum IngredientCategory { + FLOUR = 'flour', + YEAST = 'yeast', + DAIRY = 'dairy', + EGGS = 'eggs', + SUGAR = 'sugar', + FATS = 'fats', + SALT = 'salt', + SPICES = 'spices', + ADDITIVES = 'additives', + PACKAGING = 'packaging', + CLEANING = 'cleaning', + OTHER = 'other' +} + +export enum ProductCategory { + BREAD = 'bread', + CROISSANTS = 'croissants', + PASTRIES = 'pastries', + CAKES = 'cakes', + COOKIES = 'cookies', + MUFFINS = 'muffins', + SANDWICHES = 'sandwiches', + SEASONAL = 'seasonal', + BEVERAGES = 'beverages', + OTHER_PRODUCTS = 'other_products' +} + +export enum StockMovementType { + PURCHASE = 'PURCHASE', + PRODUCTION_USE = 'PRODUCTION_USE', + ADJUSTMENT = 'ADJUSTMENT', + WASTE = 'WASTE', + TRANSFER = 'TRANSFER', + RETURN = 'RETURN', + INITIAL_STOCK = 'INITIAL_STOCK', + TRANSFORMATION = 'TRANSFORMATION' +} +``` + +#### Ingredient Types +```typescript +export interface IngredientCreate { + name: string; + product_type?: ProductType; + sku?: string | null; + barcode?: string | null; + category?: string | null; + subcategory?: string | null; + description?: string | null; + brand?: string | null; + unit_of_measure: UnitOfMeasure | string; + package_size?: number | null; + standard_cost?: number | null; + low_stock_threshold?: number | null; + reorder_point?: number | null; + reorder_quantity?: number | null; + max_stock_level?: number | null; + shelf_life_days?: number | null; + is_perishable?: boolean; + allergen_info?: Record | null; +} + +export interface IngredientResponse { + id: string; + tenant_id: string; + name: string; + product_type: ProductType; + sku: string | null; + barcode: string | null; + category: string | null; + subcategory: string | null; + description: string | null; + brand: string | null; + unit_of_measure: UnitOfMeasure | string; + package_size: number | null; + average_cost: number | null; + last_purchase_price: number | null; + standard_cost: number | null; + low_stock_threshold: number | null; + reorder_point: number | null; + reorder_quantity: number | null; + max_stock_level: number | null; + shelf_life_days: number | null; + is_active: boolean; + is_perishable: boolean; + allergen_info: Record | null; + created_at: string; + updated_at: string; + created_by: string | null; + current_stock?: number | null; + is_low_stock?: boolean | null; + needs_reorder?: boolean | null; +} +``` + +#### Stock Types +```typescript +export interface StockCreate { + ingredient_id: string; + supplier_id?: string | null; + batch_number?: string | null; + lot_number?: string | null; + supplier_batch_ref?: string | null; + production_stage?: ProductionStage; + transformation_reference?: string | null; + current_quantity: number; + received_date?: string | null; + expiration_date?: string | null; + best_before_date?: string | null; + original_expiration_date?: string | null; + transformation_date?: string | null; + final_expiration_date?: string | null; + unit_cost?: number | null; + storage_location?: string | null; + warehouse_zone?: string | null; + shelf_position?: string | null; + quality_status?: string; + requires_refrigeration?: boolean; + requires_freezing?: boolean; + storage_temperature_min?: number | null; + storage_temperature_max?: number | null; + storage_humidity_max?: number | null; + shelf_life_days?: number | null; + storage_instructions?: string | null; +} + +export interface StockResponse { + id: string; + tenant_id: string; + ingredient_id: string; + supplier_id: string | null; + batch_number: string | null; + lot_number: string | null; + supplier_batch_ref: string | null; + production_stage: ProductionStage; + transformation_reference: string | null; + current_quantity: number; + reserved_quantity: number; + available_quantity: number; + received_date: string | null; + expiration_date: string | null; + best_before_date: string | null; + original_expiration_date: string | null; + transformation_date: string | null; + final_expiration_date: string | null; + unit_cost: number | null; + total_cost: number | null; + storage_location: string | null; + warehouse_zone: string | null; + shelf_position: string | null; + is_available: boolean; + is_expired: boolean; + quality_status: string; + requires_refrigeration: boolean; + requires_freezing: boolean; + storage_temperature_min: number | null; + storage_temperature_max: number | null; + storage_humidity_max: number | null; + shelf_life_days: number | null; + storage_instructions: string | null; + created_at: string; + updated_at: string; + ingredient?: IngredientResponse | null; +} +``` + +#### Stock Movement Types +```typescript +export interface StockMovementCreate { + ingredient_id: string; + stock_id?: string | null; + movement_type: StockMovementType; + quantity: number; + unit_cost?: number | null; + reference_number?: string | null; + supplier_id?: string | null; + notes?: string | null; + reason_code?: string | null; + movement_date?: string | null; +} + +export interface StockMovementResponse { + id: string; + tenant_id: string; + ingredient_id: string; + stock_id: string | null; + movement_type: StockMovementType; + quantity: number; + unit_cost: number | null; + total_cost: number | null; + quantity_before: number | null; + quantity_after: number | null; + reference_number: string | null; + supplier_id: string | null; + notes: string | null; + reason_code: string | null; + movement_date: string; + created_at: string; + created_by: string | null; + ingredient?: IngredientResponse | null; +} +``` + +#### Product Transformation Types +```typescript +export interface ProductTransformationCreate { + source_ingredient_id: string; + target_ingredient_id: string; + source_stage: ProductionStage; + target_stage: ProductionStage; + source_quantity: number; + target_quantity: number; + conversion_ratio?: number | null; + expiration_calculation_method?: string; // Default: "days_from_transformation" + expiration_days_offset?: number | null; // Default: 1 + process_notes?: string | null; + target_batch_number?: string | null; + source_stock_ids?: string[] | null; +} + +export interface ProductTransformationResponse { + id: string; + tenant_id: string; + transformation_reference: string; + source_ingredient_id: string; + target_ingredient_id: string; + source_stage: ProductionStage; + target_stage: ProductionStage; + source_quantity: number; + target_quantity: number; + conversion_ratio: number; + expiration_calculation_method: string; + expiration_days_offset: number | null; + transformation_date: string; + process_notes: string | null; + performed_by: string | null; + source_batch_numbers: string | null; + target_batch_number: string | null; + is_completed: boolean; + is_reversed: boolean; + created_at: string; + created_by: string | null; + source_ingredient?: IngredientResponse | null; + target_ingredient?: IngredientResponse | null; +} +``` + +### Inventory Hooks +```typescript +// Ingredient Query Hooks +useIngredients(tenantId, filter) - List ingredients +useIngredient(tenantId, ingredientId) - Get single ingredient +useIngredientsByCategory(tenantId) - Get ingredients grouped by category +useLowStockIngredients(tenantId) - Get low stock items + +// Stock Query Hooks +useStock(tenantId, filter) - Get all stock items (paginated) +useStockByIngredient(tenantId, ingredientId, includeUnavailable) - Get stock for ingredient +useExpiringStock(tenantId, withinDays) - Get expiring items +useExpiredStock(tenantId) - Get expired items +useStockMovements(tenantId, ingredientId, limit, offset) - Get movement history +useStockAnalytics(tenantId, startDate, endDate) - Get stock analytics + +// Ingredient Mutation Hooks +useCreateIngredient() - Create ingredient +useUpdateIngredient() - Update ingredient +useSoftDeleteIngredient() - Soft delete ingredient +useHardDeleteIngredient() - Hard delete ingredient + +// Stock Mutation Hooks +useAddStock() - Add stock +useUpdateStock() - Update stock +useConsumeStock() - Consume stock (FIFO/LIFO) +useCreateStockMovement() - Create movement record + +// Transformation Query Hooks +useTransformations(tenantId, options) - List transformations +useTransformation(tenantId, transformationId) - Get single transformation +useTransformationSummary(tenantId, daysBack) - Get transformation summary +useTransformationsByIngredient(tenantId, ingredientId, limit) - By source/target +useTransformationsByStage(tenantId, sourceStage, targetStage, limit) - By stages + +// Transformation Mutation Hooks +useCreateTransformation() - Create transformation +useParBakeTransformation() - Par-bake transformation +useClassifyBatch() - Classify batch of products + +// Custom Operation Hooks +useStockOperations(tenantId) - Returns addStock, consumeStock, adjustStock +useTransformationOperations(tenantId) - Returns various transformation operations +``` + +--- + +## 4. QUALITY TEMPLATE API + +### Frontend Type Definitions + +#### Enums +```typescript +export enum QualityCheckType { + VISUAL = 'visual', + MEASUREMENT = 'measurement', + TEMPERATURE = 'temperature', + WEIGHT = 'weight', + BOOLEAN = 'boolean', + TIMING = 'timing', + CHECKLIST = 'checklist' +} + +export enum ProcessStage { + MIXING = 'mixing', + PROOFING = 'proofing', + SHAPING = 'shaping', + BAKING = 'baking', + COOLING = 'cooling', + PACKAGING = 'packaging', + FINISHING = 'finishing' +} +``` + +#### Quality Template Types +```typescript +export interface QualityCheckTemplate { + id: string; + tenant_id: string; + name: string; + template_code?: string; + check_type: QualityCheckType; + category?: string; + description?: string; + instructions?: string; + parameters?: Record; + thresholds?: Record; + scoring_criteria?: Record; + is_active: boolean; + is_required: boolean; + is_critical: boolean; + weight: number; + min_value?: number; + max_value?: number; + target_value?: number; + unit?: string; + tolerance_percentage?: number; + applicable_stages?: ProcessStage[]; + created_by: string; + created_at: string; + updated_at: string; +} + +export interface QualityCheckTemplateCreate { + name: string; + template_code?: string; + check_type: QualityCheckType; + category?: string; + description?: string; + instructions?: string; + parameters?: Record; + thresholds?: Record; + scoring_criteria?: Record; + is_active?: boolean; + is_required?: boolean; + is_critical?: boolean; + weight?: number; + min_value?: number; + max_value?: number; + target_value?: number; + unit?: string; + tolerance_percentage?: number; + applicable_stages?: ProcessStage[]; + created_by: string; +} + +export interface QualityCheckTemplateUpdate { + name?: string; + template_code?: string; + check_type?: QualityCheckType; + category?: string; + description?: string; + instructions?: string; + parameters?: Record; + thresholds?: Record; + scoring_criteria?: Record; + is_active?: boolean; + is_required?: boolean; + is_critical?: boolean; + weight?: number; + min_value?: number; + max_value?: number; + target_value?: number; + unit?: string; + tolerance_percentage?: number; + applicable_stages?: ProcessStage[]; +} + +export interface QualityCheckResult { + criterion_id: string; + value: number | string | boolean; + score: number; + notes?: string; + photos?: string[]; + pass_check: boolean; + timestamp: string; +} + +export interface QualityCheckExecutionRequest { + template_id: string; + batch_id: string; + process_stage: ProcessStage; + checker_id?: string; + results: QualityCheckResult[]; + final_notes?: string; + photos?: string[]; +} + +export interface QualityCheckExecutionResponse { + check_id: string; + overall_score: number; + overall_pass: boolean; + critical_failures: string[]; + corrective_actions: string[]; + timestamp: string; +} +``` + +### Quality Template Hooks +```typescript +// Query Hooks +useQualityTemplates(tenantId, params) - List templates with filters +useQualityTemplate(tenantId, templateId) - Get single template +useQualityTemplatesForStage(tenantId, stage, isActive) - Templates for process stage +useQualityTemplatesForRecipe(tenantId, recipeId) - Templates for recipe configuration +useDefaultQualityTemplates(tenantId, productCategory) - Get default templates by category + +// Mutation Hooks +useCreateQualityTemplate(tenantId) - Create template +useUpdateQualityTemplate(tenantId) - Update template +useDeleteQualityTemplate(tenantId) - Delete template +useDuplicateQualityTemplate(tenantId) - Duplicate template +useExecuteQualityCheck(tenantId) - Execute quality check +useValidateQualityTemplate(tenantId) - Validate template configuration +``` + +--- + +## 5. CUSTOMER ORDER API + +### Frontend Type Definitions + +#### Enums +```typescript +export enum CustomerType { + INDIVIDUAL = 'individual', + BUSINESS = 'business', + CENTRAL_BAKERY = 'central_bakery' +} + +export enum DeliveryMethod { + DELIVERY = 'delivery', + PICKUP = 'pickup' +} + +export enum PaymentTerms { + IMMEDIATE = 'immediate', + NET_30 = 'net_30', + NET_60 = 'net_60' +} + +export enum PaymentMethod { + CASH = 'cash', + CARD = 'card', + BANK_TRANSFER = 'bank_transfer', + ACCOUNT = 'account' +} + +export enum PaymentStatus { + PENDING = 'pending', + PARTIAL = 'partial', + PAID = 'paid', + FAILED = 'failed', + REFUNDED = 'refunded' +} + +export enum CustomerSegment { + VIP = 'vip', + REGULAR = 'regular', + WHOLESALE = 'wholesale' +} + +export enum PriorityLevel { + HIGH = 'high', + NORMAL = 'normal', + LOW = 'low' +} + +export enum OrderType { + STANDARD = 'standard', + RUSH = 'rush', + RECURRING = 'recurring', + SPECIAL = 'special' +} + +export enum OrderStatus { + PENDING = 'pending', + CONFIRMED = 'confirmed', + IN_PRODUCTION = 'in_production', + READY = 'ready', + OUT_FOR_DELIVERY = 'out_for_delivery', + DELIVERED = 'delivered', + CANCELLED = 'cancelled', + FAILED = 'failed' +} + +export enum OrderSource { + MANUAL = 'manual', + ONLINE = 'online', + PHONE = 'phone', + APP = 'app', + API = 'api' +} + +export enum SalesChannel { + DIRECT = 'direct', + WHOLESALE = 'wholesale', + RETAIL = 'retail' +} + +export enum BusinessModel { + INDIVIDUAL_BAKERY = 'individual_bakery', + CENTRAL_BAKERY = 'central_bakery' +} +``` + +#### Customer Types +```typescript +export interface CustomerBase { + name: string; + business_name?: string; + customer_type: CustomerType; + email?: string; + phone?: string; + address_line1?: string; + address_line2?: string; + city?: string; + state?: string; + postal_code?: string; + country: string; + is_active: boolean; + preferred_delivery_method: DeliveryMethod; + payment_terms: PaymentTerms; + credit_limit?: number; + discount_percentage: number; + customer_segment: CustomerSegment; + priority_level: PriorityLevel; + special_instructions?: string; + delivery_preferences?: Record; + product_preferences?: Record; +} + +export interface CustomerCreate extends CustomerBase { + customer_code: string; + tenant_id: string; +} + +export interface CustomerResponse extends CustomerBase { + id: string; + tenant_id: string; + customer_code: string; + total_orders: number; + total_spent: number; + average_order_value: number; + last_order_date?: string; + created_at: string; + updated_at: string; +} +``` + +#### Order Item Types +```typescript +export interface OrderItemBase { + product_id: string; + product_name: string; + product_sku?: string; + product_category?: string; + quantity: number; + unit_of_measure: string; + weight?: number; + unit_price: number; + line_discount: number; + product_specifications?: Record; + customization_details?: string; + special_instructions?: string; + recipe_id?: string; +} + +export interface OrderItemCreate extends OrderItemBase {} + +export interface OrderItemResponse extends OrderItemBase { + id: string; + order_id: string; + line_total: number; + status: string; + created_at: string; + updated_at: string; +} +``` + +#### Order Types +```typescript +export interface OrderBase { + customer_id: string; + order_type: OrderType; + priority: PriorityLevel; + requested_delivery_date: string; + delivery_method: DeliveryMethod; + delivery_address?: Record; + delivery_instructions?: string; + delivery_window_start?: string; + delivery_window_end?: string; + discount_percentage: number; + delivery_fee: number; + payment_method?: PaymentMethod; + payment_terms: PaymentTerms; + special_instructions?: string; + custom_requirements?: Record; + allergen_warnings?: Record; + order_source: OrderSource; + sales_channel: SalesChannel; + order_origin?: string; + communication_preferences?: Record; +} + +export interface OrderCreate extends OrderBase { + tenant_id: string; + items: OrderItemCreate[]; +} + +export interface OrderUpdate { + status?: OrderStatus; + priority?: PriorityLevel; + requested_delivery_date?: string; + confirmed_delivery_date?: string; + delivery_method?: DeliveryMethod; + delivery_address?: Record; + delivery_instructions?: string; + delivery_window_start?: string; + delivery_window_end?: string; + payment_method?: PaymentMethod; + payment_status?: PaymentStatus; + special_instructions?: string; + custom_requirements?: Record; + allergen_warnings?: Record; +} + +export interface OrderResponse extends OrderBase { + id: string; + tenant_id: string; + order_number: string; + status: OrderStatus; + order_date: string; + confirmed_delivery_date?: string; + actual_delivery_date?: string; + subtotal: number; + discount_amount: number; + tax_amount: number; + total_amount: number; + payment_status: PaymentStatus; + business_model?: string; + estimated_business_model?: string; + production_batch_id?: string; + quality_score?: number; + customer_rating?: number; + created_at: string; + updated_at: string; + items: OrderItemResponse[]; +} + +export interface OrdersDashboardSummary { + total_orders_today: number; + total_orders_this_week: number; + total_orders_this_month: number; + revenue_today: number; + revenue_this_week: number; + revenue_this_month: number; + pending_orders: number; + confirmed_orders: number; + in_production_orders: number; + ready_orders: number; + delivered_orders: number; + total_customers: number; + new_customers_this_month: number; + repeat_customers_rate: number; + average_order_value: number; + order_fulfillment_rate: number; + on_time_delivery_rate: number; + business_model?: string; + business_model_confidence?: number; + recent_orders: OrderResponse[]; + high_priority_orders: OrderResponse[]; +} + +export interface DemandRequirements { + date: string; + tenant_id: string; + product_demands: Record[]; + total_orders: number; + total_quantity: number; + total_value: number; + business_model?: string; + rush_orders_count: number; + special_requirements: string[]; + earliest_delivery: string; + latest_delivery: string; + average_lead_time_hours: number; +} +``` + +### Orders/Customer Hooks +```typescript +// Order Query Hooks +useOrders(params) - List orders +useOrder(tenantId, orderId) - Get single order + +// Customer Query Hooks +useCustomers(params) - List customers +useCustomer(tenantId, customerId) - Get single customer + +// Dashboard Query Hooks +useOrdersDashboard(tenantId) - Get dashboard summary +useDemandRequirements(params) - Get demand requirements +useBusinessModelDetection(tenantId) - Detect business model +useOrdersServiceStatus(tenantId) - Get service status + +// Order Mutation Hooks +useCreateOrder() - Create order +useUpdateOrderStatus() - Update order status + +// Customer Mutation Hooks +useCreateCustomer() - Create customer +useUpdateCustomer() - Update customer + +// Utility Hooks +useInvalidateOrders() - Provides cache invalidation utilities +``` + +--- + +## IDENTIFIED MISALIGNMENTS BETWEEN FRONTEND AND BACKEND + +### 1. Recipe Types +**Misalignment**: UUID vs String representation +- Backend uses `UUID` type from Python +- Frontend uses `string` type +- **Impact**: Frontend needs to handle UUID string conversion + +**Misalignment**: Datetime vs ISO String +- Backend returns `datetime` objects +- Frontend expects ISO 8601 strings +- **Impact**: Properly handled via serialization, but worth noting + +### 2. Supplier Types +**Misalignment**: Decimal vs Number +- Backend uses `Decimal` for monetary values (credit_limit, total_spent, discount_percentage) +- Frontend uses `number` type +- **Impact**: Precision loss possible with floating point, needs attention for currency calculations + +**Potential Issue**: Payment Terms enum +- Backend: `PaymentTerms` with values like 'net_15', 'net_30', etc. +- Frontend: Matches correctly in suppliers.ts but DIFFERENT in orders.ts (has IMMEDIATE, NET_30, NET_60) +- **CRITICAL MISALIGNMENT**: Different PaymentTerms enums in different contexts! + - Suppliers use NET_15, NET_30, NET_45, NET_60, COD, PREPAID, CREDIT_TERMS + - Customers/Orders use IMMEDIATE, NET_30, NET_60 + - These should probably be unified or clarified + +### 3. Inventory Types +**Potential Issue**: unit_price vs different field names +- StockCreate in frontend has `unit_cost` +- But StockOperations hook uses `unit_price` when calling API +- This might cause inconsistencies + +**Misalignment**: StockMovementType inconsistency +- Frontend uses string type StockMovementType enum +- But in useStockOperations, it hardcodes 'ADJUSTMENT' as `'ADJUSTMENT' as any` +- Should properly type this + +### 4. Quality Templates +**Minor Issue**: ProcessStage different between quality_templates and inventory +- Quality templates define: MIXING, PROOFING, SHAPING, BAKING, COOLING, PACKAGING, FINISHING +- Inventory defines: RAW_INGREDIENT, PAR_BAKED, FULLY_BAKED, PREPARED_DOUGH, FROZEN_PRODUCT +- These are DIFFERENT concept layers - one is quality control stages, other is production stages +- This is CORRECT design, but important to understand they're distinct + +**Potential Issue**: Backend backend validator function +- Frontend QualityCheckType might need to validate dependent on check_type +- Backend has validators that clear measurement values for non-measurement types +- Frontend might not enforce this, leading to invalid data being sent + +### 5. Orders/Customers +**CRITICAL MISALIGNMENT**: PaymentTerms enum (mentioned above) +- Suppliers module and Orders module use different PaymentTerms +- This is a serious inconsistency + +**Potential Issue**: Customer fields not in schema +- CustomerResponse has `total_spent` and `total_spent` as number +- Backend schema shows `Decimal` type +- Same precision issue as suppliers + +**Misalignment**: Missing enum in frontend for DeliveryStatus +- Backend has `DeliveryStatus` enum imported in order_schemas.py +- Frontend orders.ts doesn't define it (it's in suppliers.ts as part of delivery system) +- But OrderResponse might contain delivery status information +- Unclear if this is needed or not + +### 6. Service Integration Issues +**Issue**: Quality Check Creation form requires `created_by` field +- Frontend QualityCheckTemplateCreate requires `created_by: string` +- But UI components likely auto-fill this with current user +- Worth verifying the API actually accepts this + +**Issue**: Inventory "unit_price" vs "unit_cost" +- StockCreate interface shows `unit_cost?: number | null;` +- But useStockOperations hook uses `unit_price` parameter name +- This could be a field naming inconsistency with the backend + +--- + +## RECOMMENDATIONS + +1. **Unify PaymentTerms Enums**: Create a single PaymentTerms enum that works for both suppliers and customers, or clarify why they differ. + +2. **Use Decimal for Money**: Consider implementing a Decimal type wrapper in TypeScript for currency fields to maintain precision. + +3. **Fix Stock Field Names**: Verify whether stock uses `unit_cost` or `unit_price` and make consistent across frontend. + +4. **Add Quality Template Validation**: Frontend should implement backend-style validators to prevent invalid data. + +5. **Clarify ProcessStage vs ProductionStage**: Document which stages apply to which operations. + +6. **Type Consistency Review**: Audit all `Record` fields - these indicate potential schema mismatches. + +7. **UUID Handling**: Implement consistent UUID validation and serialization across frontend. + +8. **Add Missing Enums**: Ensure DeliveryStatus is properly imported in orders types if needed. + +---