All files / src/pages/inventory/dialogs/ItemFormDialog useItemForm.ts

100% Statements 270/270
89.36% Branches 42/47
100% Functions 4/4
100% Lines 270/270

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 2711x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 13x 13x 13x 46x 46x 46x 46x 46x 46x 46x 14x 13x 14x 14x 14x 14x 14x 14x 14x 14x 14x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 6x 5x 5x 5x 6x 1x 1x 1x 1x 1x 1x 6x 2x 2x 2x 2x 2x 2x 6x 1x 1x 1x 1x 1x 1x 6x 6x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 9x 9x 9x 9x 9x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 9x 2x 2x 2x 9x 6x 6x 46x 46x 46x 46x 46x 46x 46x 3x 3x 3x 3x 3x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x  
/**
 * useItemForm - Orchestrator hook for create/edit item workflow
 * 
 * @module dialogs/ItemFormDialog/useItemForm
 * @description
 * Manages all state, queries, and form handling for item creation/editing:
 * supplier selection → item details → validation → API submission.
 * 
 * Composes three specialized concerns:
 * - State: supplier, form values, errors, controlled Autocomplete value
 * - Queries: suppliers with 5-minute cache via useSuppliersQuery
 * - Handlers: form submission with error mapping and demo mode support
 */
 
import * as React from 'react';
import { useForm, type Control, type UseFormStateReturn, type UseFormSetValue, type UseFormRegister, type UseFormSetError, type UseFormClearErrors, type UseFormWatch, type UseFormHandleSubmit } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useTranslation } from 'react-i18next';
import { useToast } from '../../../../context/toast';
import { upsertItem } from '../../../../api/inventory/mutations';
import { itemFormSchema, type UpsertItemForm } from '../../../../api/inventory/validation';
import type { UpsertItemRequest, InventoryRow } from '../../../../api/inventory';
import type { SupplierOption } from '../../../../api/analytics/types';
import { useSuppliersQuery } from '../../../../api/inventory/hooks/useInventoryData';
 
/**
 * Complete item form state and handlers
 * 
 * @interface UseItemFormReturn
 */
export interface UseItemFormReturn {
  // State
  supplierValue: SupplierOption | null;
  formError: string | null;
 
  // Setters
  setSupplierValue: (supplier: SupplierOption | null) => void;
  setFormError: (error: string | null) => void;
 
  // Query
  suppliers: SupplierOption[];
 
  // Form methods
  register: UseFormRegister<UpsertItemForm>;
  control: Control<UpsertItemForm>;
  formState: UseFormStateReturn<UpsertItemForm>;
  setValue: UseFormSetValue<UpsertItemForm>;
  setError: UseFormSetError<UpsertItemForm>;
  clearErrors: UseFormClearErrors<UpsertItemForm>;
  watch: UseFormWatch<UpsertItemForm>;
  handleSubmit: UseFormHandleSubmit<UpsertItemForm>;
 
  // Handlers
  onSubmit: () => Promise<void>;
  handleClose: () => void;
}
 
/**
 * Orchestrator hook managing item form workflow
 * 
 * @param params.isOpen - Whether dialog is currently open (controls query firing)
 * @param params.initial - Initial item data for edit mode (undefined for create)
 * @param params.onClose - Callback when dialog closes
 * @param params.onSaved - Optional callback after successful save
 * @param params.readOnly - Demo mode flag (disables submission)
 * @returns Complete form state and handlers
 * 
 * @enterprise
 * - Smart supplier loading with 5-minute cache via useSuppliersQuery
 * - Controlled Autocomplete to prevent UI/RHF desync
 * - Intelligent error mapping: detects duplicate name/code and fields supplier issues
 * - Form state resets on dialog open to ensure clean state
 * - Supplier alignment effect handles race conditions when list loads late
 */
export function useItemForm({
  isOpen,
  initial,
  onClose,
  onSaved = () => {},
  readOnly = false,
}: {
  isOpen: boolean;
  initial?: InventoryRow | null;
  onClose: () => void;
  onSaved?: () => void;
  readOnly?: boolean;
}): UseItemFormReturn {
  const { t } = useTranslation(['common', 'inventory', 'errors']);
  const toast = useToast();
 
  // ================================
  // State Management
  // ================================
 
  const [supplierValue, setSupplierValue] = React.useState<SupplierOption | null>(null);
  const [formError, setFormError] = React.useState<string | null>(null);
 
  // ================================
  // Data Query
  // ================================
 
  const { data: suppliers = [] } = useSuppliersQuery(isOpen);
 
  // ================================
  // Form Management
  // ================================
 
  const {
    register,
    control,
    handleSubmit: rhfHandleSubmit,
    formState,
    reset,
    setValue,
    setError,
    clearErrors,
    watch,
  } = useForm<UpsertItemForm>({
    resolver: zodResolver(itemFormSchema),
    defaultValues: {
      name: initial?.name ?? '',
      code: initial?.code ?? '',
      supplierId: initial?.supplierId ?? '',
      quantity: initial?.onHand ?? 0,
      price: 0,
      reason: 'INITIAL_STOCK',
    },
  });
 
  // ================================
  // Effects
  // ================================
 
  /**
   * Align controlled Autocomplete with initial supplierId when suppliers load
   * Prevents race condition where suppliers arrive after defaultValues set
   */
  React.useEffect(() => {
    if (!suppliers.length) return;
    const match = suppliers.find((s) => String(s.id) === String(initial?.supplierId)) ?? null;
    setSupplierValue(match);
  }, [suppliers, initial?.supplierId]);
 
  /**
   * Reset form state when dialog opens with different initial data
   * Ensures predictable state for Create vs Edit flows
   */
  React.useEffect(() => {
    if (!isOpen) return;
    reset({
      name: initial?.name ?? '',
      code: initial?.code ?? '',
      supplierId: (initial?.supplierId as UpsertItemForm['supplierId']) ?? '',
      quantity: initial?.onHand ?? 0,
      price: 0,
      reason: 'INITIAL_STOCK',
    });
    setFormError(null);
    clearErrors();
  }, [isOpen, initial, reset, clearErrors]);
 
  // ================================
  // Handlers
  // ================================
 
  /**
   * Convert generic backend error string into field or form errors
   * Uses readable heuristics (duplicate name/code, supplier issues)
   * Can be replaced by structured fieldErrors in future
   */
  function applyServerError(message?: string | null): void {
    if (!message) return;
    const msg = message.toLowerCase();
 
    // Heuristics for duplicates
    if (msg.includes('name') && (msg.includes('duplicate') || msg.includes('exists'))) {
      setError('name', {
        message: t('errors:inventory.conflicts.duplicateName', 'An item with this name already exists.'),
      });
      setFormError(t('errors:inventory.validationFailed', 'Please fix the highlighted fields.'));
      return;
    }
    if ((msg.includes('code') || msg.includes('sku')) && (msg.includes('duplicate') || msg.includes('exists'))) {
      setError('code', {
        message: t('errors:inventory.conflicts.duplicateCode', 'An item with this code already exists.'),
      });
      setFormError(t('errors:inventory.validationFailed', 'Please fix the highlighted fields.'));
      return;
    }
    if (msg.includes('supplier')) {
      setError('supplierId', { message });
      setFormError(t('errors:inventory.validationFailed', 'Please fix the highlighted fields.'));
      return;
    }
 
    // Generic fallback
    setFormError(message || t('errors:inventory.server.serverError', 'Something went wrong. Please try again.'));
  }
 
  /**
   * Submit form with validation and API call
   * 
   * @enterprise
   * - Honors readOnly (demo mode) flag
   * - Maps form values to UpsertItemRequest (reason → notes, onHand → quantity)
   * - Auto-sets minQty to 5 and createdBy to 'user'
   * - Maps field-level and generic errors from backend
   * - Triggers onSaved callback and closes on success
   */
  const onSubmit = rhfHandleSubmit(async (values: UpsertItemForm) => {
    setFormError(null);
    clearErrors();
 
    // Demo guard
    if (readOnly) {
      setFormError(t('common:demoDisabled', 'This action is disabled in demo mode.'));
      return;
    }
 
    // Map form values to backend request shape
    const requestData: UpsertItemRequest = {
      name: values.name,
      code: values.code,
      supplierId: values.supplierId,
      quantity: values.quantity,
      price: values.price,
      minQty: 5,
      notes: values.reason,
      createdBy: 'user',
    };
 
    const res = await upsertItem(requestData);
    if (res.ok) {
      toast(t('inventory:status.itemSaved', 'Item saved successfully!'), 'success');
      onSaved();
      handleClose();
    } else {
      applyServerError(res.error ?? t('errors:inventory.server.serverError', 'Something went wrong. Please try again.'));
    }
  });
 
  /**
   * Close dialog with complete state cleanup
   * Prevents state pollution between sessions
   */
  const handleClose = () => {
    setSupplierValue(null);
    setFormError(null);
    reset();
    onClose();
  };
 
  return {
    supplierValue,
    formError,
    setSupplierValue,
    setFormError,
    suppliers,
    register,
    control,
    formState,
    setValue,
    setError,
    clearErrors,
    watch,
    handleSubmit: rhfHandleSubmit,
    onSubmit,
    handleClose,
  };
}