All files / src/components ProductForm.tsx

89.18% Statements 33/37
75% Branches 12/16
75% Functions 3/4
88.88% Lines 32/36

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                    131x 131x 131x             131x 131x 131x 131x   131x       2x 2x 2x                       2x                 111x 111x       6x 6x 6x 6x   6x   1x 1x 1x     5x                     1x 1x       4x 3x           4x       1x         5x               131x                                   4x                                                                                                                                                                                              
import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
  apiClient,
  type ProductRequest,
  type ProductResponse,
} from "../services/api";
import { type ProductFormData, validateProduct } from "../utils/validation";
 
export const ProductForm: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [formData, setFormData] = useState<ProductFormData>({
    name: "",
    price: "",
    quantity: "",
    description: "",
    category: "",
  });
  const [errors, setErrors] = useState<string[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [successMessage, setSuccessMessage] = useState("");
  const isEditing = !!id;
 
  useEffect(() => {
    if (id) {
      const fetchProduct = async () => {
        try {
          const response = await apiClient.getProductById(Number(id));
          const product = response.data;
          setFormData({
            name: product.name,
            price: product.price.toString(),
            quantity: product.quantity.toString(),
            description: product.description || "",
            category: product.category,
          });
        } catch (error) {
          console.error("Failed to fetch product", error);
          setErrors(["Failed to load product"]);
        }
      };
      fetchProduct();
    }
  }, [id]);
 
  const handleChange = (
    e: React.ChangeEvent<
      HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
    >
  ) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };
 
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setErrors([]);
    setSuccessMessage("");
 
    const validation = validateProduct(formData);
    if (!validation.isValid) {
      setErrors(validation.errors);
      setIsSubmitting(false);
      return;
    }
 
    const productRequest: ProductRequest = {
      name: formData.name,
      price: Number(formData.price),
      quantity: Number(formData.quantity),
      description: formData.description,
      category: formData.category,
    };
 
    try {
      let response: { data: ProductResponse };
      if (isEditing) {
        response = await apiClient.updateProduct(Number(id), productRequest);
        setSuccessMessage(
          `Product updated successfully!: ${JSON.stringify(response)}`
        );
      } else {
        response = await apiClient.createProduct(productRequest);
        setSuccessMessage(
          `Product created successfully!: ${JSON.stringify(response)}`
        );
      }
 
      // Redirect after success
      setTimeout(() => {
        navigate("/products");
      }, 2000);
    } catch (error: any) {
      setErrors([
        error.response?.data?.message ||
          `Failed to ${isEditing ? "update" : "create"} product`,
      ]);
    } finally {
      setIsSubmitting(false);
    }
  };
 
  const handleCancel = () => {
    navigate("/products");
  };
 
  return (
    <div data-testid="product-form-page">
      <h1>{isEditing ? "Edit Product" : "Create Product"}</h1>
 
      {successMessage && (
        <div className="success-message" data-testid="success-message">
          {successMessage}
        </div>
      )}
 
      <form
        onSubmit={handleSubmit}
        className="product-form"
        data-testid="product-form"
      >
        {errors.length > 0 && (
          <ul className="error-list" data-testid="form-errors">
            {errors.map((error, index) => (
              <li key={index}>{error}</li>
            ))}
          </ul>
        )}
 
        <div className="form-group">
          <label htmlFor="name">Product Name *</label>
          <input
            type="text"
            id="name"
            name="name"
            value={formData.name}
            onChange={handleChange}
            data-testid="product-name-input"
          />
        </div>
 
        <div className="form-group">
          <label htmlFor="price">Price *</label>
          <input
            type="number"
            id="price"
            name="price"
            value={formData.price}
            onChange={handleChange}
            data-testid="product-price-input"
          />
        </div>
 
        <div className="form-group">
          <label htmlFor="quantity">Quantity *</label>
          <input
            type="number"
            id="quantity"
            name="quantity"
            value={formData.quantity}
            onChange={handleChange}
            data-testid="product-quantity-input"
          />
        </div>
 
        <div className="form-group">
          <label htmlFor="category">Category *</label>
          <select
            id="category"
            name="category"
            value={formData.category}
            onChange={handleChange}
            data-testid="product-category-input"
          >
            <option value="">Select a category</option>
            <option value="Electronics">Electronics</option>
            <option value="Books">Books</option>
            <option value="Clothing">Clothing</option>
            <option value="Home">Home</option>
            <option value="Sports">Sports</option>
          </select>
        </div>
 
        <div className="form-group">
          <label htmlFor="description">Description</label>
          <textarea
            id="description"
            name="description"
            value={formData.description}
            onChange={handleChange}
            rows={4}
            data-testid="product-description-input"
          />
        </div>
 
        <div className="form-actions">
          <button
            type="submit"
            disabled={isSubmitting}
            data-testid="submit-product"
          >
            {isSubmitting
              ? "Saving..."
              : isEditing
              ? "Update Product"
              : "Create Product"}
          </button>
          <button
            type="button"
            onClick={handleCancel}
            data-testid="cancel-product"
          >
            Cancel
          </button>
        </div>
      </form>
    </div>
  );
};