All files / src/pages/suppliers/dialogs/CreateSupplierDialog useCreateSupplierForm.ts

99.31% Statements 146/147
63.63% Branches 7/11
100% Functions 3/3
99.31% Lines 146/147

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 1481x 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 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 2x 2x 2x 2x 2x 2x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 6x 6x 6x 6x 6x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 3x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x  
/**
 * @file useCreateSupplierForm.ts
 * @module dialogs/CreateSupplierDialog/useCreateSupplierForm
 *
 * @summary
 * Form logic for creating a new supplier.
 * Handles validation, submission, and error mapping.
 *
 * @enterprise
 * - React Hook Form + Zod for type-safe validation
 * - Server error mapping to field-level errors
 * - Tolerant error handling (no throws)
 */
 
import * as React from 'react';
import { useForm, type UseFormReturn } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import type { Resolver } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { createSupplier, createSupplierSchema, type CreateSupplierForm } from '../../../../api/suppliers';
 
/**
 * Hook return type for CreateSupplierForm.
 * 
 * @interface UseCreateSupplierFormReturn
 */
export interface UseCreateSupplierFormReturn {
  // React Hook Form methods
  register: UseFormReturn<CreateSupplierForm>['register'];
  handleSubmit: UseFormReturn<CreateSupplierForm>['handleSubmit'];
  formState: UseFormReturn<CreateSupplierForm>['formState'];
  reset: UseFormReturn<CreateSupplierForm>['reset'];
 
  // Custom state
  formError: string | null;
  setFormError: (error: string | null) => void;
 
  // Handlers
  onSubmit: (data: CreateSupplierForm) => Promise<{ success: boolean }>;
}
 
/**
 * Hook for supplier creation form logic.
 * 
 * Handles:
 * - Form validation with Zod schema
 * - Server error mapping to field/form errors
 * - Submission to backend
 * - Success/failure notification
 * 
 * @param onCreated - Callback when supplier is successfully created
 * @returns Form methods and submission handler
 */
export const useCreateSupplierForm = (
  onCreated: () => void
): UseCreateSupplierFormReturn => {
  const { t } = useTranslation(['common', 'suppliers', 'errors']);
  const [formError, setFormError] = React.useState<string | null>(null);
 
  const {
    register,
    handleSubmit,
    setError,
    formState,
    reset,
  } = useForm<CreateSupplierForm>({
    resolver: zodResolver(createSupplierSchema) as Resolver<CreateSupplierForm>,
    defaultValues: {
      name: '',
      contactName: '',
      phone: '',
      email: '',
    },
  });
 
  /**
   * Map backend error messages to field or form errors.
   * Uses heuristics to improve UX by pinpointing issues.
   */
  const applyServerError = (message?: string | null): void => {
    if (!message) return;
    const msg = message.toLowerCase();
 
    // Duplicate name error
    if (
      msg.includes('name') &&
      (msg.includes('duplicate') || msg.includes('exists') || msg.includes('already'))
    ) {
      setError('name', {
        message: t(
          'errors:supplier.businessRules.duplicateName',
          'A supplier with this name already exists'
        ),
      });
      setFormError(
        t('errors:inventory.validationFailed', 'Please fix the highlighted fields.')
      );
      return;
    }
 
    // Generic form error
    setFormError(message);
  };
 
  /**
   * Submit form: validate → POST → notify parent.
   */
  const onSubmit = async (data: CreateSupplierForm): Promise<{ success: boolean }> => {
    setFormError(null);
 
    try {
      const response = await createSupplier({
        name: data.name,
        contactName: data.contactName,
        phone: data.phone,
        email: data.email,
      });
 
      if (!response.success) {
        applyServerError(response.error);
        return { success: false };
      }
 
      // Success: notify parent and reset
      reset();
      onCreated();
      return { success: true };
    } catch (err) {
      const errorMessage =
        err instanceof Error
          ? err.message
          : t('errors:supplier.requests.failedToAddSupplier');
      applyServerError(errorMessage);
      return { success: false };
    }
  };
 
  return {
    register,
    handleSubmit,
    formState,
    reset,
    formError,
    setFormError,
    onSubmit,
  };
};