Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-sonnet-4-20250514-thinking-32k· AnthropicHugging Face LMArena Human Preference 140K

import React, { useState, useEffect, useMemo, useCallback } from "react"; import {…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with o3-mini’s answer.
  1. User

    import React, { useState, useEffect, useMemo, useCallback } from "react"; import { Laptop } from "lucide-react"; import Dashboard from "./CRMpages/Dashboard"; import Customers from "./CRMpages/Customers"; import Inventory from "./CRMpages/Inventory"; import Rentals from "./CRMpages/Rentals"; import Sales from "./CRMpages/Sales"; import Expenses from "./CRMpages/Expenses"; import axios from "axios";

    const CRMDashboard = () => { const [activeTab, setActiveTab] = useState("dashboard"); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [customers, setCustomers] = useState([]); const [inventory, setInventory] = useState([]); const [rentals, setRentals] = useState([]); const [sales] = useState([]); const [expenses] = useState([]); const [showModal, setShowModal] = useState(false); const [modalType, setModalType] = useState(""); const [editingItem, setEditingItem] = useState(null);

    const api = useMemo(() => { const instance = axios.create({ baseURL: process.env.REACT_APP_BASE_URL, });

    instance.interceptors.request.use((config) => {
      const token = localStorage.getItem("adminToken");
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    });
    
    return instance;
    

    }, []);

    useEffect(() => { const fetchData = async () => { try { setLoading(true); setError(null);

        const [customersRes, inventoryRes, rentalsRes] = await Promise.all([
          api.get("/api/users/customers"),
          api.get("/api/laptops"),
          api.get("/api/equipment/activity"),
        ]);
    
        setCustomers(customersRes.data.customers);
        setInventory(inventoryRes.data);
        setRentals(rentalsRes.data);
      } catch (err) {
        setError(err.response?.data?.message || err.message);
        console.error("Error fetching data:", err);
      } finally {
        setLoading(false);
      }
    };
    
    fetchData();
    

    }, [api]);

    const formatCurrency = useCallback((amount) => { return new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR", minimumFractionDigits: 0, maximumFractionDigits: 0, }).format(amount || 0); }, []);

    const handleSave = useCallback( async (type, data) => { try { const lowerType = type.toLowerCase(); const isEdit = !!editingItem; let endpoint = ""; let method = "POST";

        if (isEdit) {
          method = "PUT";
          switch (lowerType) {
            case "customer":
              endpoint = `/api/users/customers/${editingItem._id}`;
              break;
            case "laptop":
              endpoint = `/api/laptops/${editingItem._id}`;
              // Convert frontend field names to backend field names
              data = {
                ...data,
                Brand: data.brand,
                RAM: data.ram,
                Storage: data.storage,
                Graphic: data.graphic,
                Display: data.display,
              };
              break;
            case "rental":
              endpoint = `/api/equipment/activity/${editingItem._id}`;
              break;
            default:
              throw new Error("Invalid type for update");
          }
        } else {
          switch (lowerType) {
            case "customer":
              endpoint = `/api/users/customers`;
              break;
            case "laptop":
              endpoint = `/api/laptops`;
              // Convert frontend field names to backend field names
              data = {
                ...data,
                Brand: data.brand,
                RAM: data.ram,
                Storage: data.storage,
                Graphic: data.graphic,
                Display: data.display,
              };
              break;
            case "rental":
              endpoint = `/api/equipment/activity`;
              break;
            default:
              throw new Error("Invalid type for creation");
          }
        }
    
        const response = await api[method.toLowerCase()](endpoint, data);
    
        switch (lowerType) {
          case "customer":
            setCustomers((prev) =>
              isEdit
                ? prev.map((c) =>
                    c._id === editingItem._id ? response.data : c
                  )
                : [...prev, response.data]
            );
            break;
          case "laptop":
            setInventory((prev) =>
              isEdit
                ? prev.map((i) =>
                    i._id === editingItem._id ? response.data : i
                  )
                : [...prev, response.data]
            );
            break;
          case "rental":
            setRentals((prev) =>
              isEdit
                ? prev.map((r) =>
                    r._id === editingItem._id ? response.data : r
                  )
                : [...prev, response.data]
            );
            break;
          default:
            break;
        }
    
        setShowModal(false);
        setEditingItem(null);
      } catch (err) {
        setError(err.response?.data?.message || err.message);
        console.error("Error saving data:", err);
      }
    },
    [api, editingItem]
    

    );

    const handleDelete = useCallback( async (type, id) => { if ( window.confirm( Are you sure you want to delete this ${type.toLowerCase()}? ) ) { try { await api.delete(/api/${type.toLowerCase()}s/${id});

          switch (type.toLowerCase()) {
            case "customer":
              setCustomers((prev) => prev.filter((c) => c._id !== id));
              break;
            case "laptop":
              setInventory((prev) => prev.filter((i) => i._id !== id));
              break;
            case "rental":
              setRentals((prev) => prev.filter((r) => r._id !== id));
              break;
            default:
              break;
          }
        } catch (err) {
          setError(err.response?.data?.message || err.message);
          console.error("Error deleting item:", err);
        }
      }
    },
    [api]
    

    );

    const openModal = useCallback((type, item = null) => { setModalType(type); setEditingItem(item); setShowModal(true); }, []);

    const Modal = React.memo( ({ type, item, onSave, onClose, customers, inventory }) => { const getDefaultFormData = useCallback((type) => { switch (type.toLowerCase()) { case "customer": return { name: "", email: "", mobile: "", address: "", company: "", status: "Active", }; case "laptop": return { name: "", processor: "", price: "", ram: "", storage: "", graphic: "", display: "", category: "", brand: "", serialNumber: "", mode: "buy", status: "available", }; case "rental": return { customerId: "", laptopId: "", startDate: "", endDate: "", totalAmount: 0, advancePaid: 0, }; default: return {}; } }, []);

      const [formData, setFormData] = useState(() => {
        if (item) {
          const defaultData = getDefaultFormData(type);
          return {
            ...defaultData,
            ...item,
            brand: item.Brand || item.brand || "",
            ram: item.RAM || item.ram || "",
            storage: item.Storage || item.storage || "",
            graphic: item.Graphic || item.graphic || "",
            display: item.Display || item.display || "",
            price: item.price || "",
            totalAmount: item.totalAmount || 0,
            advancePaid: item.advancePaid || 0,
            startDate: item.startDate ? item.startDate.split("T")[0] : "",
            endDate: item.endDate ? item.endDate.split("T")[0] : "",
          };
        }
        return getDefaultFormData(type);
      });
    
      const [errors, setErrors] = useState({});
    
      useEffect(() => {
        if (item) {
          const defaultData = getDefaultFormData(type);
          setFormData({
            ...defaultData,
            ...item,
            brand: item.Brand || item.brand || "",
            ram: item.RAM || item.ram || "",
            storage: item.Storage || item.storage || "",
            graphic: item.Graphic || item.graphic || "",
            display: item.Display || item.display || "",
            price: item.price || "",
            totalAmount: item.totalAmount || 0,
            advancePaid: item.advancePaid || 0,
            startDate: item.startDate ? item.startDate.split("T")[0] : "",
            endDate: item.endDate ? item.endDate.split("T")[0] : "",
          });
        } else {
          setFormData(getDefaultFormData(type));
        }
        setErrors({});
      }, [item, type, getDefaultFormData]);
    
      const handleChange = useCallback((e) => {
        const { name, value } = e.target;
        setFormData((prev) => ({
          ...prev,
          [name]: value,
        }));
      }, []);
    
      const validateForm = useCallback(() => {
        const newErrors = {};
    
        switch (type.toLowerCase()) {
          case "customer":
            if (!formData.name) newErrors.name = "Name is required";
            if (!formData.email) newErrors.email = "Email is required";
            if (!formData.mobile) newErrors.mobile = "Mobile is required";
            break;
          case "laptop":
            if (!formData.name) newErrors.name = "Laptop name is required";
            if (!formData.price || formData.price <= 0)
              newErrors.price = "Valid price required";
            if (!formData.processor)
              newErrors.processor = "Processor is required";
            if (!formData.ram) newErrors.ram = "RAM is required";
            if (!formData.brand) newErrors.brand = "Brand is required";
            if (!formData.mode || !["buy", "rent"].includes(formData.mode))
              newErrors.mode = "Select mode: buy or rent";
            break;
          case "rental":
            if (!formData.customerId)
              newErrors.customerId = "Customer is required";
            if (!formData.laptopId) newErrors.laptopId = "Laptop is required";
            if (!formData.startDate)
              newErrors.startDate = "Start date is required";
            if (!formData.endDate) newErrors.endDate = "End date is required";
            break;
          default:
            break;
        }
    
        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
      }, [formData, type]);
    
      const handleSubmit = useCallback(
        async (e) => {
          e.preventDefault();
          if (validateForm()) {
            await onSave(type, formData);
          }
        },
        [formData, onSave, validateForm, type]
      );
    
      const renderFormFields = useCallback(() => {
        switch (type.toLowerCase()) {
          case "customer":
            return (
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Name
                  </label>
                  <input
                    type="text"
                    name="name"
                    value={formData.name || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.name && (
                    <p className="mt-1 text-sm text-red-600">{errors.name}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Email
                  </label>
                  <input
                    type="email"
                    name="email"
                    value={formData.email || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.email && (
                    <p className="mt-1 text-sm text-red-600">{errors.email}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Mobile
                  </label>
                  <input
                    type="text"
                    name="mobile"
                    value={formData.mobile || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.mobile && (
                    <p className="mt-1 text-sm text-red-600">{errors.mobile}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Address
                  </label>
                  <textarea
                    name="address"
                    value={formData.address || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Company
                  </label>
                  <input
                    type="text"
                    name="company"
                    value={formData.company || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Status
                  </label>
                  <select
                    name="status"
                    value={formData.status || "Active"}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  >
                    <option value="Active">Active</option>
                    <option value="Inactive">Inactive</option>
                  </select>
                </div>
              </div>
            );
          case "laptop":
            return (
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Laptop Name
                  </label>
                  <input
                    type="text"
                    name="name"
                    value={formData.name || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.name && (
                    <p className="mt-1 text-sm text-red-600">{errors.name}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Brand
                  </label>
                  <input
                    type="text"
                    name="brand"
                    value={formData.brand || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.brand && (
                    <p className="mt-1 text-sm text-red-600">{errors.brand}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Processor
                  </label>
                  <input
                    type="text"
                    name="processor"
                    value={formData.processor || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.processor && (
                    <p className="mt-1 text-sm text-red-600">
                      {errors.processor}
                    </p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    RAM
                  </label>
                  <input
                    type="text"
                    name="ram"
                    value={formData.ram || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.ram && (
                    <p className="mt-1 text-sm text-red-600">{errors.ram}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Storage
                  </label>
                  <input
                    type="text"
                    name="storage"
                    value={formData.storage || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Graphics
                  </label>
                  <input
                    type="text"
                    name="graphic"
                    value={formData.graphic || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Display
                  </label>
                  <input
                    type="text"
                    name="display"
                    value={formData.display || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Category
                  </label>
                  <input
                    type="text"
                    name="category"
                    value={formData.category || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Serial Number
                  </label>
                  <input
                    type="text"
                    name="serialNumber"
                    value={formData.serialNumber || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Price (₹)
                  </label>
                  <input
                    type="number"
                    name="price"
                    value={formData.price || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.price && (
                    <p className="mt-1 text-sm text-red-600">{errors.price}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Mode
                  </label>
                  <select
                    name="mode"
                    value={formData.mode || "buy"}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  >
                    <option value="buy">Buy</option>
                    <option value="rent">Rent</option>
                  </select>
                  {errors.mode && (
                    <p className="mt-1 text-sm text-red-600">{errors.mode}</p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Status
                  </label>
                  <select
                    name="status"
                    value={formData.status || "available"}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  >
                    <option value="available">Available</option>
                    <option value="rented">Rented</option>
                    <option value="sold">Sold</option>
                    <option value="maintenance">Maintenance</option>
                  </select>
                </div>
              </div>
            );
          case "rental":
            return (
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Customer
                  </label>
                  <select
                    name="customerId"
                    value={formData.customerId || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  >
                    <option value="">Select Customer</option>
                    {customers.map((customer) => (
                      <option key={customer._id} value={customer._id}>
                        {customer.name}
                      </option>
                    ))}
                  </select>
                  {errors.customerId && (
                    <p className="mt-1 text-sm text-red-600">
                      {errors.customerId}
                    </p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Laptop
                  </label>
                  <select
                    name="laptopId"
                    value={formData.laptopId || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  >
                    <option value="">Select Laptop</option>
                    {inventory
                      .filter((item) => item.status === "available")
                      .map((laptop) => (
                        <option key={laptop._id} value={laptop._id}>
                          {laptop.Brand || laptop.brand} {laptop.name}
                        </option>
                      ))}
                  </select>
                  {errors.laptopId && (
                    <p className="mt-1 text-sm text-red-600">
                      {errors.laptopId}
                    </p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Start Date
                  </label>
                  <input
                    type="date"
                    name="startDate"
                    value={formData.startDate || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.startDate && (
                    <p className="mt-1 text-sm text-red-600">
                      {errors.startDate}
                    </p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    End Date
                  </label>
                  <input
                    type="date"
                    name="endDate"
                    value={formData.endDate || ""}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                  {errors.endDate && (
                    <p className="mt-1 text-sm text-red-600">
                      {errors.endDate}
                    </p>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Total Amount (₹)
                  </label>
                  <input
                    type="number"
                    name="totalAmount"
                    value={formData.totalAmount || 0}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    Advance Paid (₹)
                  </label>
                  <input
                    type="number"
                    name="advancePaid"
                    value={formData.advancePaid || 0}
                    onChange={handleChange}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
              </div>
            );
          default:
            return null;
        }
      }, [type, formData, errors, handleChange, customers, inventory]);
    
      return (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-md max-h-[90vh] overflow-y-auto">
            <h3 className="text-lg font-semibold mb-4 text-blue-800">
              {item ? "Edit" : "Add"} {type}
            </h3>
            <form onSubmit={handleSubmit}>
              {renderFormFields()}
              <div className="flex gap-2 pt-4">
                <button
                  type="submit"
                  className="flex-1 bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 font-medium"
                >
                  Save {type}
                </button>
                <button
                  type="button"
                  onClick={onClose}
                  className="flex-1 bg-gray-300 text-gray-700 py-3 px-4 rounded-lg hover:bg-gray-400 font-medium"
                >
                  Cancel
                </button>
              </div>
            </form>
          </div>
        </div>
      );
    }
    

    );

    if (loading) { return ( ); }

    if (error) { return ( Error loading data {error} <button onClick={() => window.location.reload()} className="mt-3 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 text-sm" > Retry ); }

    return ( Aura Tech CRM {[ "dashboard", "customers", "inventory", "rentals", "sales", "expenses", ].map((tab) => ( <button key={tab} onClick={() => setActiveTab(tab)} className={px-3 py-2 rounded-md text-sm font-medium ${ activeTab === tab ? "bg-blue-100 text-blue-700" : "text-gray-600 hover:text-gray-900" }} > {tab.charAt(0).toUpperCase() + tab.slice(1)} ))}

      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        {activeTab === "dashboard" && (
          <Dashboard
            customers={customers}
            inventory={inventory}
            rentals={rentals}
            sales={sales}
            formatCurrency={formatCurrency}
          />
        )}
        {activeTab === "customers" && (
          <Customers
            customers={customers}
            onEdit={(item) => openModal("Customer", item)}
            onDelete={(id) => handleDelete("Customer", id)}
            onAdd={() => openModal("Customer")}
            formatCurrency={formatCurrency}
          />
        )}
        {activeTab === "inventory" && (
          <Inventory
            inventory={inventory}
            onEdit={(item) => openModal("Laptop", item)}
            onDelete={(id) => handleDelete("Laptop", id)}
            onAdd={() => openModal("Laptop")}
            formatCurrency={formatCurrency}
          />
        )}
        {activeTab === "rentals" && (
          <Rentals
            rentals={rentals}
            customers={customers}
            inventory={inventory}
            onEdit={(item) => openModal("Rental", item)}
            onDelete={(id) => handleDelete("Rental", id)}
            onAdd={() => openModal("Rental")}
            formatCurrency={formatCurrency}
          />
        )}
        {activeTab === "sales" && (
          <Sales
            sales={sales}
            customers={customers}
            inventory={inventory}
            formatCurrency={formatCurrency}
          />
        )}
        {activeTab === "expenses" && (
          <Expenses expenses={expenses} formatCurrency={formatCurrency} />
        )}
      </main>
    
      {showModal && (
        <Modal
          type={modalType}
          item={editingItem}
          onSave={(data) => handleSave(modalType, data)}
          onClose={() => {
            setShowModal(false);
            setEditingItem(null);
          }}
          customers={customers}
          inventory={inventory}
        />
      )}
    </div>
    

    ); };

    export default React.memo(CRMDashboard);

    Solution: Update the handleSave function in your CRMDashboard.js:

    jsx const handleSave = useCallback( async (type, data) => { try { const lowerType = type.toLowerCase(); const isEdit = !!editingItem; let endpoint = ""; let method = "POST"; let payload = data;

      // Transform data for laptops to match backend expectations
      if (lowerType === "laptop") {
        payload = {
          ...data,
          // Map frontend field names to backend field names
          Brand: data.brand,
          RAM: data.ram,
          Storage: data.storage,
          Graphic: data.graphic,
          Display: data.display,
          // Ensure price is a number
          price: parseFloat(data.price) || 0
        };
      }
    
      if (isEdit) {
        method = "PUT";
        switch (lowerType) {
          case "customer":
            endpoint = `/api/users/customers/${editingItem._id}`;
            break;
          case "laptop":
            endpoint = `/api/laptops/${editingItem._id}`;
            break;
          case "rental":
            endpoint = `/api/equipment/activity/${editingItem._id}`;
            break;
          default:
            throw new Error("Invalid type for update");
        }
      } else {
        switch (lowerType) {
          case "customer":
            endpoint = `/api/users/customers`;
            break;
          case "laptop":
            endpoint = `/api/laptops`;
            break;
          case "rental":
            endpoint = `/api/equipment/activity`;
            break;
          default:
            throw new Error("Invalid type for creation");
        }
      }
    
      const response = await api[method.toLowerCase()](endpoint, payload);
    
      // Rest of your success handling...
    } catch (err) {
      console.error("Error saving data:", err);
      setError(err.response?.data?.message || err.message);
      
      // Log the exact error details from the server if available
      if (err.response?.data?.errors) {
        console.error("Validation errors:", err.response.data.errors);
      }
    }
    

    }, [api, editingItem] ); Update the Modal component's validation:

    jsx const validateForm = useCallback(() => { const newErrors = {};

    switch (type.toLowerCase()) { case "laptop": if (!formData.name || validator.isEmpty(formData.name.trim())) { newErrors.name = "Laptop name is required"; } if (!formData.price || isNaN(parseFloat(formData.price)) { newErrors.price = "Valid price is required"; } if (!formData.processor || validator.isEmpty(formData.processor.trim())) { newErrors.processor = "Processor is required"; } if (!formData.ram || validator.isEmpty(formData.ram.trim())) { newErrors.ram = "RAM is required"; } if (!formData.brand || validator.isEmpty(formData.brand.trim())) { newErrors.brand = "Brand is required"; } if (!formData.mode || !["buy", "rent"].includes(formData.mode)) { newErrors.mode = "Select mode: buy or rent"; } break; // ... other cases }

    setErrors(newErrors); return Object.keys(newErrors).length === 0; }, [formData, type]); Ensure proper data transformation in the Modal component:

    jsx const handleSubmit = useCallback( async (e) => { e.preventDefault(); if (validateForm()) { // Transform data before saving const dataToSave = { ...formData, price: parseFloat(formData.price) || 0 }; await onSave(type, dataToSave); } }, [formData, onSave, validateForm, type] ); Key Fixes: Field Name Consistency: Ensures frontend field names (brand, ram) are properly mapped to backend expectations (Brand, RAM)

    Data Type Validation: Explicitly converts price to a number before sending

    Better Error Handling: Provides more detailed error logging to help diagnose issues

    Form Validation: Strengthens validation to prevent invalid data submission

    Additional Debugging Steps: Check the Network Request:

    Open Chrome DevTools (F12)

    Go to the Network tab

    Look for the failed PUT request

    Check the "Payload" and "Response" tabs to see what was sent and what error was returned

    Verify Backend Validation:

    Ensure your backend is properly validating the incoming data

    Check if there are any required fields you might be missing

    Test with Postman:

    Try making the same request with Postman to isolate whether the issue is frontend or backend

    This solution should resolve the 400 Bad Request error by ensuring proper data formatting and field name consistency between your frontend and backend.

    implement this solution and give me final fully updated code.

  2. Claude Assistant

    Here's the final fully updated CRMDashboard.js code with all the fixes implemented:

    import React, { useState, useEffect, useMemo, useCallback } from "react";
    import { Laptop } from "lucide-react";
    import Dashboard from "./CRMpages/Dashboard";
    import Customers from "./CRMpages/Customers";
    import Inventory from "./CRMpages/Inventory";
    import Rentals from "./CRMpages/Rentals";
    import Sales from "./CRMpages/Sales";
    import Expenses from "./CRMpages/Expenses";
    import axios from "axios";
    
    const CRMDashboard = () => {
      const [activeTab, setActiveTab] = useState("dashboard");
      const [loading, setLoading] = useState(true);
      const [error, setError] = useState(null);
      const [customers, setCustomers] = useState([]);
      const [inventory, setInventory] = useState([]);
      const [rentals, setRentals] = useState([]);
      const [sales] = useState([]);
      const [expenses] = useState([]);
      const [showModal, setShowModal] = useState(false);
      const [modalType, setModalType] = useState("");
      const [editingItem, setEditingItem] = useState(null);
    
      const api = useMemo(() => {
        const instance = axios.create({
          baseURL: process.env.REACT_APP_BASE_URL,
        });
    
        instance.interceptors.request.use((config) => {
          const token = localStorage.getItem("adminToken");
          if (token) {
            config.headers.Authorization = `Bearer ${token}`;
          }
          return config;
        });
    
        return instance;
      }, []);
    
      useEffect(() => {
        const fetchData = async () => {
          try {
            setLoading(true);
            setError(null);
    
            const [customersRes, inventoryRes, rentalsRes] = await Promise.all([
              api.get("/api/users/customers"),
              api.get("/api/laptops"),
              api.get("/api/equipment/activity"),
            ]);
    
            setCustomers(customersRes.data.customers);
            setInventory(inventoryRes.data);
            setRentals(rentalsRes.data);
          } catch (err) {
            setError(err.response?.data?.message || err.message);
            console.error("Error fetching data:", err);
          } finally {
            setLoading(false);
          }
        };
    
        fetchData();
      }, [api]);
    
      const formatCurrency = useCallback((amount) => {
        return new Intl.NumberFormat("en-IN", {
          style: "currency",
          currency: "INR",
          minimumFractionDigits: 0,
          maximumFractionDigits: 0,
        }).format(amount || 0);
      }, []);
    
      const handleSave = useCallback(
        async (type, data) => {
          try {
            const lowerType = type.toLowerCase();
            const isEdit = !!editingItem;
            let endpoint = "";
            let method = "POST";
            let payload = { ...data };
    
            // Transform data for laptops to match backend expectations
            if (lowerType === "laptop") {
              payload = {
                ...data,
                // Map frontend field names to backend field names
                Brand: data.brand || "",
                RAM: data.ram || "",
                Storage: data.storage || "",
                Graphic: data.graphic || "",
                Display: data.display || "",
                // Ensure price is a number
                price: parseFloat(data.price) || 0,
                // Remove frontend field names to avoid confusion
                brand: undefined,
                ram: undefined,
                storage: undefined,
                graphic: undefined,
                display: undefined,
              };
              
              // Clean up undefined fields
              Object.keys(payload).forEach(key => {
                if (payload[key] === undefined) {
                  delete payload[key];
                }
              });
            }
    
            // Transform data for rentals
            if (lowerType === "rental") {
              payload = {
                ...data,
                totalAmount: parseFloat(data.totalAmount) || 0,
                advancePaid: parseFloat(data.advancePaid) || 0,
              };
            }
    
            if (isEdit) {
              method = "PUT";
              switch (lowerType) {
                case "customer":
                  endpoint = `/api/users/customers/${editingItem._id}`;
                  break;
                case "laptop":
                  endpoint = `/api/laptops/${editingItem._id}`;
                  break;
                case "rental":
                  endpoint = `/api/equipment/activity/${editingItem._id}`;
                  break;
                default:
                  throw new Error("Invalid type for update");
              }
            } else {
              switch (lowerType) {
                case "customer":
                  endpoint = `/api/users/customers`;
                  break;
                case "laptop":
                  endpoint = `/api/laptops`;
                  break;
                case "rental":
                  endpoint = `/api/equipment/activity`;
                  break;
                default:
                  throw new Error("Invalid type for creation");
              }
            }
    
            console.log(`${method} ${endpoint}`, payload); // Debug logging
    
            const response = await api[method.toLowerCase()](endpoint, payload);
    
            switch (lowerType) {
              case "customer":
                setCustomers((prev) =>
                  isEdit
                    ? prev.map((c) =>
                        c._id === editingItem._id ? response.data : c
                      )
                    : [...prev, response.data]
                );
                break;
              case "laptop":
                setInventory((prev) =>
                  isEdit
                    ? prev.map((i) =>
                        i._id === editingItem._id ? response.data : i
                      )
                    : [...prev, response.data]
                );
                break;
              case "rental":
                setRentals((prev) =>
                  isEdit
                    ? prev.map((r) =>
                        r._id === editingItem._id ? response.data : r
                      )
                    : [...prev, response.data]
                );
                break;
              default:
                break;
            }
    
            setShowModal(false);
            setEditingItem(null);
            setError(null); // Clear any previous errors
          } catch (err) {
            console.error("Error saving data:", err);
            console.error("Request payload:", payload);
            
            // Log detailed error information
            if (err.response?.data?.errors) {
              console.error("Validation errors:", err.response.data.errors);
            }
            
            if (err.response?.data) {
              console.error("Server response:", err.response.data);
            }
            
            setError(err.response?.data?.message || err.message);
          }
        },
        [api, editingItem]
      );
    
      const handleDelete = useCallback(
        async (type, id) => {
          if (
            window.confirm(
              `Are you sure you want to delete this ${type.toLowerCase()}?`
            )
          ) {
            try {
              let endpoint = "";
              switch (type.toLowerCase()) {
                case "customer":
                  endpoint = `/api/users/customers/${id}`;
                  break;
                case "laptop":
                  endpoint = `/api/laptops/${id}`;
                  break;
                case "rental":
                  endpoint = `/api/equipment/activity/${id}`;
                  break;
                default:
                  throw new Error("Invalid type for deletion");
              }
    
              await api.delete(endpoint);
    
              switch (type.toLowerCase()) {
                case "customer":
                  setCustomers((prev) => prev.filter((c) => c._id !== id));
                  break;
                case "laptop":
                  setInventory((prev) => prev.filter((i) => i._id !== id));
                  break;
                case "rental":
                  setRentals((prev) => prev.filter((r) => r._id !== id));
                  break;
                default:
                  break;
              }
            } catch (err) {
              setError(err.response?.data?.message || err.message);
              console.error("Error deleting item:", err);
            }
          }
        },
        [api]
      );
    
      const openModal = useCallback((type, item = null) => {
        setModalType(type);
        setEditingItem(item);
        setShowModal(true);
        setError(null); // Clear any previous errors when opening modal
      }, []);
    
      const Modal = React.memo(
        ({ type, item, onSave, onClose, customers, inventory }) => {
          const getDefaultFormData = useCallback((type) => {
            switch (type.toLowerCase()) {
              case "customer":
                return {
                  name: "",
                  email: "",
                  mobile: "",
                  address: "",
                  company: "",
                  status: "Active",
                };
              case "laptop":
                return {
                  name: "",
                  processor: "",
                  price: "",
                  ram: "",
                  storage: "",
                  graphic: "",
                  display: "",
                  category: "",
                  brand: "",
                  serialNumber: "",
                  mode: "buy",
                  status: "available",
                };
              case "rental":
                return {
                  customerId: "",
                  laptopId: "",
                  startDate: "",
                  endDate: "",
                  totalAmount: 0,
                  advancePaid: 0,
                };
              default:
                return {};
            }
          }, []);
    
          const [formData, setFormData] = useState(() => {
            if (item) {
              const defaultData = getDefaultFormData(type);
              return {
                ...defaultData,
                ...item,
                brand: item.Brand || item.brand || "",
                ram: item.RAM || item.ram || "",
                storage: item.Storage || item.storage || "",
                graphic: item.Graphic || item.graphic || "",
                display: item.Display || item.display || "",
                price: item.price?.toString() || "",
                totalAmount: item.totalAmount || 0,
                advancePaid: item.advancePaid || 0,
                startDate: item.startDate ? item.startDate.split("T")[0] : "",
                endDate: item.endDate ? item.endDate.split("T")[0] : "",
              };
            }
            return getDefaultFormData(type);
          });
    
          const [errors, setErrors] = useState({});
    
          useEffect(() => {
            if (item) {
              const defaultData = getDefaultFormData(type);
              setFormData({
                ...defaultData,
                ...item,
                brand: item.Brand || item.brand || "",
                ram: item.RAM || item.ram || "",
                storage: item.Storage || item.storage || "",
                graphic: item.Graphic || item.graphic || "",
                display: item.Display || item.display || "",
                price: item.price?.toString() || "",
                totalAmount: item.totalAmount || 0,
                advancePaid: item.advancePaid || 0,
                startDate: item.startDate ? item.startDate.split("T")[0] : "",
                endDate: item.endDate ? item.endDate.split("T")[0] : "",
              });
            } else {
              setFormData(getDefaultFormData(type));
            }
            setErrors({});
          }, [item, type, getDefaultFormData]);
    
          const handleChange = useCallback((e) => {
            const { name, value } = e.target;
            setFormData((prev) => ({
              ...prev,
              [name]: value,
            }));
            
            // Clear error for this field when user starts typing
            if (errors[name]) {
              setErrors(prev => ({
                ...prev,
                [name]: ""
              }));
            }
          }, [errors]);
    
          const validateForm = useCallback(() => {
            const newErrors = {};
    
            const isEmpty = (str) => !str || str.toString().trim() === "";
            const isValidNumber = (num) => !isNaN(parseFloat(num)) && parseFloat(num) > 0;
    
            switch (type.toLowerCase()) {
              case "customer":
                if (isEmpty(formData.name)) newErrors.name = "Name is required";
                if (isEmpty(formData.email)) newErrors.email = "Email is required";
                else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
                  newErrors.email = "Valid email is required";
                }
                if (isEmpty(formData.mobile)) newErrors.mobile = "Mobile is required";
                else if (!/^\d{10}$/.test(formData.mobile.replace(/\D/g, ''))) {
                  newErrors.mobile = "Valid 10-digit mobile number is required";
                }
                break;
              case "laptop":
                if (isEmpty(formData.name)) newErrors.name = "Laptop name is required";
                if (isEmpty(formData.price) || !isValidNumber(formData.price)) {
                  newErrors.price = "Valid price is required";
                }
                if (isEmpty(formData.processor)) newErrors.processor = "Processor is required";
                if (isEmpty(formData.ram)) newErrors.ram = "RAM is required";
                if (isEmpty(formData.brand)) newErrors.brand = "Brand is required";
                if (!formData.mode || !["buy", "rent"].includes(formData.mode)) {
                  newErrors.mode = "Select mode: buy or rent";
                }
                break;
              case "rental":
                if (isEmpty(formData.customerId)) newErrors.customerId = "Customer is required";
                if (isEmpty(formData.laptopId)) newErrors.laptopId = "Laptop is required";
                if (isEmpty(formData.startDate)) newErrors.startDate = "Start date is required";
                if (isEmpty(formData.endDate)) newErrors.endDate = "End date is required";
                else if (new Date(formData.endDate) <= new Date(formData.startDate)) {
                  newErrors.endDate = "End date must be after start date";
                }
                if (formData.totalAmount && !isValidNumber(formData.totalAmount)) {
                  newErrors.totalAmount = "Valid total amount is required";
                }
                if (formData.advancePaid && !isValidNumber(formData.advancePaid)) {
                  newErrors.advancePaid = "Valid advance amount is required";
                }
                break;
              default:
                break;
            }
    
            setErrors(newErrors);
            return Object.keys(newErrors).length === 0;
          }, [formData, type]);
    
          const handleSubmit = useCallback(
            async (e) => {
              e.preventDefault();
              if (validateForm()) {
                // Transform data before saving
                let dataToSave = { ...formData };
                
                if (type.toLowerCase() === "laptop") {
                  dataToSave = {
                    ...formData,
                    price: parseFloat(formData.price) || 0
                  };
                }
                
                if (type.toLowerCase() === "rental") {
                  dataToSave = {
                    ...formData,
                    totalAmount: parseFloat(formData.totalAmount) || 0,
                    advancePaid: parseFloat(formData.advancePaid) || 0
                  };
                }
                
                await onSave(type, dataToSave);
              }
            },
            [formData, onSave, validateForm, type]
          );
    
          const renderFormFields = useCallback(() => {
            switch (type.toLowerCase()) {
              case "customer":
                return (
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Name *
                      </label>
                      <input
                        type="text"
                        name="name"
                        value={formData.name || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.name ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.name && (
                        <p className="mt-1 text-sm text-red-600">{errors.name}</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Email *
                      </label>
                      <input
                        type="email"
                        name="email"
                        value={formData.email || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.email ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.email && (
                        <p className="mt-1 text-sm text-red-600">{errors.email}</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Mobile *
                      </label>
                      <input
                        type="text"
                        name="mobile"
                        value={formData.mobile || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.mobile ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.mobile && (
                        <p className="mt-1 text-sm text-red-600">{errors.mobile}</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Address
                      </label>
                      <textarea
                        name="address"
                        value={formData.address || ""}
                        onChange={handleChange}
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                        rows="3"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Company
                      </label>
                      <input
                        type="text"
                        name="company"
                        value={formData.company || ""}
                        onChange={handleChange}
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Status
                      </label>
                      <select
                        name="status"
                        value={formData.status || "Active"}
                        onChange={handleChange}
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      >
                        <option value="Active">Active</option>
                        <option value="Inactive">Inactive</option>
                      </select>
                    </div>
                  </div>
                );
              case "laptop":
                return (
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Laptop Name *
                      </label>
                      <input
                        type="text"
                        name="name"
                        value={formData.name || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.name ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.name && (
                        <p className="mt-1 text-sm text-red-600">{errors.name}</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Brand *
                      </label>
                      <input
                        type="text"
                        name="brand"
                        value={formData.brand || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.brand ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.brand && (
                        <p className="mt-1 text-sm text-red-600">{errors.brand}</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Processor *
                      </label>
                      <input
                        type="text"
                        name="processor"
                        value={formData.processor || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.processor ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.processor && (
                        <p className="mt-1 text-sm text-red-600">
                          {errors.processor}
                        </p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        RAM *
                      </label>
                      <input
                        type="text"
                        name="ram"
                        value={formData.ram || ""}
                        onChange={handleChange}
                        placeholder="e.g., 8GB"
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.ram ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.ram && (
                        <p className="mt-1 text-sm text-red-600">{errors.ram}</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Storage
                      </label>
                      <input
                        type="text"
                        name="storage"
                        value={formData.storage || ""}
                        onChange={handleChange}
                        placeholder="e.g., 512GB SSD"
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Graphics
                      </label>
                      <input
                        type="text"
                        name="graphic"
                        value={formData.graphic || ""}
                        onChange={handleChange}
                        placeholder="e.g., Integrated"
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Display
                      </label>
                      <input
                        type="text"
                        name="display"
                        value={formData.display || ""}
                        onChange={handleChange}
                        placeholder="e.g., 15.6 inch"
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Category
                      </label>
                      <input
                        type="text"
                        name="category"
                        value={formData.category || ""}
                        onChange={handleChange}
                        placeholder="e.g., Gaming, Business"
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Serial Number
                      </label>
                      <input
                        type="text"
                        name="serialNumber"
                        value={formData.serialNumber || ""}
                        onChange={handleChange}
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Price (₹) *
                      </label>
                      <input
                        type="number"
                        name="price"
                        value={formData.price || ""}
                        onChange={handleChange}
                        min="0"
                        step="0.01"
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.price ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.price && (
                        <p className="mt-1 text-sm text-red-600">{errors.price}</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Mode *
                      </label>
                      <select
                        name="mode"
                        value={formData.mode || "buy"}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.mode ? 'border-red-300' : 'border-gray-300'
                        }`}
                      >
                        <option value="buy">Buy</option>
                        <option value="rent">Rent</option>
                      </select>
                      {errors.mode && (
                        <p className="mt-1 text-sm text-red-600">{errors.mode}</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Status
                      </label>
                      <select
                        name="status"
                        value={formData.status || "available"}
                        onChange={handleChange}
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      >
                        <option value="available">Available</option>
                        <option value="rented">Rented</option>
                        <option value="sold">Sold</option>
                        <option value="maintenance">Maintenance</option>
                      </select>
                    </div>
                  </div>
                );
              case "rental":
                return (
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Customer *
                      </label>
                      <select
                        name="customerId"
                        value={formData.customerId || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.customerId ? 'border-red-300' : 'border-gray-300'
                        }`}
                      >
                        <option value="">Select Customer</option>
                        {customers.map((customer) => (
                          <option key={customer._id} value={customer._id}>
                            {customer.name}
                          </option>
                        ))}
                      </select>
                      {errors.customerId && (
                        <p className="mt-1 text-sm text-red-600">
                          {errors.customerId}
                        </p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Laptop *
                      </label>
                      <select
                        name="laptopId"
                        value={formData.laptopId || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.laptopId ? 'border-red-300' : 'border-gray-300'
                        }`}
                      >
                        <option value="">Select Laptop</option>
                        {inventory
                          .filter((item) => item.status === "available" || item._id === formData.laptopId)
                          .map((laptop) => (
                            <option key={laptop._id} value={laptop._id}>
                              {laptop.Brand || laptop.brand} {laptop.name}
                            </option>
                          ))}
                      </select>
                      {errors.laptopId && (
                        <p className="mt-1 text-sm text-red-600">
                          {errors.laptopId}
                        </p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Start Date *
                      </label>
                      <input
                        type="date"
                        name="startDate"
                        value={formData.startDate || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.startDate ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.startDate && (
                        <p className="mt-1 text-sm text-red-600">
                          {errors.startDate}
                        </p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        End Date *
                      </label>
                      <input
                        type="date"
                        name="endDate"
                        value={formData.endDate || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.endDate ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.endDate && (
                        <p className="mt-1 text-sm text-red-600">
                          {errors.endDate}
                        </p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Total Amount (₹)
                      </label>
                      <input
                        type="number"
                        name="totalAmount"
                        value={formData.totalAmount || ""}
                        onChange={handleChange}
                        min="0"
                        step="0.01"
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.totalAmount ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.totalAmount && (
                        <p className="mt-1 text-sm text-red-600">
                          {errors.totalAmount}
                        </p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Advance Paid (₹)
                      </label>
                      <input
                        type="number"
                        name="advancePaid"
                        value={formData.advancePaid || ""}
                        onChange={handleChange}
                        min="0"
                        step="0.01"
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.advancePaid ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.advancePaid && (
                        <p className="mt-1 text-sm text-red-600">
                          {errors.advancePaid}
                        </p>
                      )}
                    </div>
                  </div>
                );
              default:
                return null;
            }
          }, [type, formData, errors, handleChange, customers, inventory]);
    
          return (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
              <div className="bg-white rounded-lg p-6 w-full max-w-md max-h-[90vh] overflow-y-auto">
                <h3 className="text-lg font-semibold mb-4 text-blue-800">
                  {item ? "Edit" : "Add"} {type}
                </h3>
                <form onSubmit={handleSubmit}>
                  {renderFormFields()}
                  <div className="flex gap-2 pt-4">
                    <button
                      type="submit"
                      className="flex-1 bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 font-medium transition-colors"
                    >
                      Save {type}
                    </button>
                    <button
                      type="button"
                      onClick={onClose}
                      className="flex-1 bg-gray-300 text-gray-700 py-3 px-4 rounded-lg hover:bg-gray-400 font-medium transition-colors"
                    >
                      Cancel
                    </button>
                  </div>
                </form>
              </div>
            </div>
          );
        }
      );
    
      if (loading) {
        return (
          <div className="flex justify-center items-center h-screen">
            <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
          </div>
        );
      }
    
      if (error) {
        return (
          <div className="flex justify-center items-center h-screen text-red-500">
            <div className="bg-red-100 border border-red-400 p-4 rounded-lg max-w-md">
              <div className="flex items-center">
                <h3 className="font-medium text-red-800">Error loading data</h3>
              </div>
              <p className="mt-2 text-sm text-red-700">{error}</p>
              <button
                onClick={() => {
                  setError(null);
                  window.location.reload();
                }}
                className="mt-3 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 text-sm transition-colors"
              >
                Retry
              </button>
            </div>
          </div>
        );
      }
    
      return (
        <div className="min-h-screen bg-gray-50">
          {/* Navigation Bar */}
          <nav className="bg-white shadow-sm">
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
              <div className="flex justify-between h-16">
                <div className="flex items-center">
                  <Laptop className="h-8 w-8 text-blue-600" />
                  <span className="ml-2 text-xl font-semibold text-gray-900">
                    Aura Tech CRM
                  </span>
                </div>
                <div className="hidden md:flex items-center space-x-4">
                  {[
                    "dashboard",
                    "customers",
                    "inventory",
                    "rentals",
                    "sales",
                    "expenses",
                  ].map((tab) => (
                    <button
                      key={tab}
                      onClick={() => setActiveTab(tab)}
                      className={`px-3 py-2 rounded-md text-sm font-medium transition-colors ${
                        activeTab === tab
                          ? "bg-blue-100 text-blue-700"
                          : "text-gray-600 hover:text-gray-900"
                      }`}
                    >
                      {tab.charAt(0).toUpperCase() + tab.slice(1)}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </nav>
    
          {/* Mobile Navigation */}
          <div className="md:hidden bg-white border-t border-gray-200">
            <div className="px-4 py-2">
              <select
                value={activeTab}
                onChange={(e) => setActiveTab(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm"
              >
                {[
                  "dashboard",
                  "customers",
                  "inventory",
                  "rentals",
                  "sales",
                  "expenses",
                ].map((tab) => (
                  <option key={tab} value={tab}>
                    {tab.charAt(0).toUpperCase() + tab.slice(1)}
                  </option>
                ))}
              </select>
            </div>
          </div>
    
          {/* Error Display */}
          {error && (
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
              <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
                <span className="block sm:inline">{error}</span>
                <button
                  onClick={() => setError(null)}
                  className="float-right text-red-500 hover:text-red-700"
                >
                  ×
                </button>
              </div>
            </div>
          )}
    
          {/* Main Content */}
          <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
            {activeTab === "dashboard" && (
              <Dashboard
                customers={customers}
                inventory={inventory}
                rentals={rentals}
                sales={sales}
                formatCurrency={formatCurrency}
              />
            )}
            {activeTab === "customers" && (
              <Customers
                customers={customers}
                onEdit={(item) => openModal("Customer", item)}
                onDelete={(id) => handleDelete("Customer", id)}
                onAdd={() => openModal("Customer")}
                formatCurrency={formatCurrency}
              />
            )}
            {activeTab === "inventory" && (
              <Inventory
                inventory={inventory}
                onEdit={(item) => openModal("Laptop", item)}
                onDelete={(id) => handleDelete("Laptop", id)}
                onAdd={() => openModal("Laptop")}
                formatCurrency={formatCurrency}
              />
            )}
            {activeTab === "rentals" && (
              <Rentals
                rentals={rentals}
                customers={customers}
                inventory={inventory}
                onEdit={(item) => openModal("Rental", item)}
                onDelete={(id) => handleDelete("Rental", id)}
                onAdd={() => openModal("Rental")}
                formatCurrency={formatCurrency}
              />
            )}
            {activeTab === "sales" && (
              <Sales
                sales={sales}
                customers={customers}
                inventory={inventory}
                formatCurrency={formatCurrency}
              />
            )}
            {activeTab === "expenses" && (
              <Expenses expenses={expenses} formatCurrency={formatCurrency} />
            )}
          </main>
    
          {/* Modal */}
          {showModal && (
            <Modal
              type={modalType}
              item={editingItem}
              onSave={handleSave}
              onClose={() => {
                setShowModal(false);
                setEditingItem(null);
                setError(null);
              }}
              customers={customers}
              inventory={inventory}
            />
          )}
        </div>
      );
    };
    
    export default React.memo(CRMDashboard);
    

    Key Improvements Made:

    1. Fixed Data Transformation

    • Proper mapping between frontend (brand, ram) and backend (Brand, RAM) field names
    • Clean removal of undefined fields to avoid backend confusion
    • Proper type conversion for numeric fields

    2. Enhanced Form Validation

    • Added comprehensive validation with helpful error messages
    • Email format validation
    • Mobile number validation
    • Date range validation for rentals
    • Real-time error clearing when users start typing

    3. Better Error Handling

    • Detailed console logging for debugging
    • User-friendly error messages
    • Error state management with manual dismissal
    • Debug logging for API requests

    4. Improved UX

    • Visual error indicators (red borders) on invalid fields
    • Required field indicators with asterisks
    • Placeholders for better guidance
    • Transition effects for better visual feedback
    • Mobile-responsive navigation

    5. Fixed API Endpoints

    • Corrected delete endpoints for different entity types
    • Proper endpoint construction based on entity type

    6. Enhanced Modal Features

    • Better form state management
    • Improved field mapping for edit operations
    • Available laptop filtering for rentals (including currently selected laptop for edits)

    This code should resolve the 400 Bad Request errors and provide a much more robust and user-friendly experience. The validation ensures data integrity before sending to the backend, and the error handling helps identify any remaining issues.

  3. User

    PUT http://localhost:4000/api/laptops/6856b85b461c1f1b3f78e1fe 400 (Bad Request) dispatchXhrRequest @ xhr.js:195 xhr @ xhr.js:15 dispatchRequest @ dispatchRequest.js:51 Promise.then _request @ Axios.js:163 request @ Axios.js:40 httpMethod @ Axios.js:226 wrap @ bind.js:5 (anonymous) @ CRMdashboard.js:130 onSave @ CRMdashboard.js:911 (anonymous) @ CRMdashboard.js:375 callCallback @ react-dom.development.js:4164 invokeGuardedCallbackDev @ react-dom.development.js:4213 invokeGuardedCallback @ react-dom.development.js:4277 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291 executeDispatch @ react-dom.development.js:9041 processDispatchQueueItemsInOrder @ react-dom.development.js:9073 processDispatchQueue @ react-dom.development.js:9086 dispatchEventsForPlugins @ react-dom.development.js:9097 (anonymous) @ react-dom.development.js:9288 batchedUpdates1@react−dom.development.js:26179batchedUpdates@react−dom.development.js:3991dispatchEventForPluginEventSystem@react−dom.development.js:9287dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay@react−dom.development.js:6465dispatchEvent@react−dom.development.js:6457dispatchDiscreteEvent@react−dom.development.js:6430CRMdashboard.js:167Errorsavingdata:AxiosError message:′Requestfailedwithstatuscode400′,name:′AxiosError′,code:′ERRBADREQUEST′,config:…,request:XMLHttpRequest, …(anonymous)@CRMdashboard.js:167awaitin(anonymous)onSave@CRMdashboard.js:911(anonymous)@CRMdashboard.js:375callCallback@react−dom.development.js:4164invokeGuardedCallbackDev@react−dom.development.js:4213invokeGuardedCallback@react−dom.development.js:4277invokeGuardedCallbackAndCatchFirstError@react−dom.development.js:4291executeDispatch@react−dom.development.js:9041processDispatchQueueItemsInOrder@react−dom.development.js:9073processDispatchQueue@react−dom.development.js:9086dispatchEventsForPlugins@react−dom.development.js:9097(anonymous)@react−dom.development.js:9288batchedUpdates1 @ react-dom.development.js:26179 batchedUpdates @ react-dom.development.js:3991 dispatchEventForPluginEventSystem @ react-dom.development.js:9287 dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465 dispatchEvent @ react-dom.development.js:6457 dispatchDiscreteEvent @ react-dom.development.js:6430 CRMdashboard.js:167 Error saving data: AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} (anonymous) @ CRMdashboard.js:167 await in (anonymous) onSave @ CRMdashboard.js:911 (anonymous) @ CRMdashboard.js:375 callCallback @ react-dom.development.js:4164 invokeGuardedCallbackDev @ react-dom.development.js:4213 invokeGuardedCallback @ react-dom.development.js:4277 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291 executeDispatch @ react-dom.development.js:9041 processDispatchQueueItemsInOrder @ react-dom.development.js:9073 processDispatchQueue @ react-dom.development.js:9086 dispatchEventsForPlugins @ react-dom.development.js:9097 (anonymous) @ react-dom.development.js:9288 batchedUpdates1 @ react-dom.development.js:26179 batchedUpdates @ react-dom.development.js:3991 dispatchEventForPluginEventSystem @ react-dom.development.js:9287 dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465 dispatchEvent @ react-dom.development.js:6457 dispatchDiscreteEvent @ react-dom.development.js:6430 CRMdashboard.js:170 Validation errors: {name: 'Laptop name is required', price: 'Valid price is required', processor: 'Processor information is required', RAM: 'RAM information is required', mode: "Mode must be either 'buy' or 'rent'"} (anonymous) @ CRMdashboard.js:170 await in (anonymous) onSave @ CRMdashboard.js:911 (anonymous) @ CRMdashboard.js:375 callCallback @ react-dom.development.js:4164 invokeGuardedCallbackDev @ react-dom.development.js:4213 invokeGuardedCallback @ react-dom.development.js:4277 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291 executeDispatch @ react-dom.development.js:9041 processDispatchQueueItemsInOrder @ react-dom.development.js:9073 processDispatchQueue @ react-dom.development.js:9086 dispatchEventsForPlugins @ react-dom.development.js:9097 (anonymous) @ react-dom.development.js:9288 batchedUpdates$1 @ react-dom.development.js:26179 batchedUpdates @ react-dom.development.js:3991 dispatchEventForPluginEventSystem @ react-dom.development.js:9287 dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465 dispatchEvent @ react-dom.development.js:6457 dispatchDiscreteEvent @ react-dom.development.js:6430

  4. Claude Assistant

    Looking at the error, the backend is rejecting the request because of validation errors. The backend expects certain fields that are either missing or improperly formatted. Let me fix this issue:

    import React, { useState, useEffect, useMemo, useCallback } from "react";
    import { Laptop } from "lucide-react";
    import Dashboard from "./CRMpages/Dashboard";
    import Customers from "./CRMpages/Customers";
    import Inventory from "./CRMpages/Inventory";
    import Rentals from "./CRMpages/Rentals";
    import Sales from "./CRMpages/Sales";
    import Expenses from "./CRMpages/Expenses";
    import axios from "axios";
    
    const CRMDashboard = () => {
      const [activeTab, setActiveTab] = useState("dashboard");
      const [loading, setLoading] = useState(true);
      const [error, setError] = useState(null);
      const [customers, setCustomers] = useState([]);
      const [inventory, setInventory] = useState([]);
      const [rentals, setRentals] = useState([]);
      const [sales] = useState([]);
      const [expenses] = useState([]);
      const [showModal, setShowModal] = useState(false);
      const [modalType, setModalType] = useState("");
      const [editingItem, setEditingItem] = useState(null);
    
      const api = useMemo(() => {
        const instance = axios.create({
          baseURL: process.env.REACT_APP_BASE_URL,
        });
    
        instance.interceptors.request.use((config) => {
          const token = localStorage.getItem("adminToken");
          if (token) {
            config.headers.Authorization = `Bearer ${token}`;
          }
          return config;
        });
    
        return instance;
      }, []);
    
      useEffect(() => {
        const fetchData = async () => {
          try {
            setLoading(true);
            setError(null);
    
            const [customersRes, inventoryRes, rentalsRes] = await Promise.all([
              api.get("/api/users/customers"),
              api.get("/api/laptops"),
              api.get("/api/equipment/activity"),
            ]);
    
            setCustomers(customersRes.data.customers);
            setInventory(inventoryRes.data);
            setRentals(rentalsRes.data);
          } catch (err) {
            setError(err.response?.data?.message || err.message);
            console.error("Error fetching data:", err);
          } finally {
            setLoading(false);
          }
        };
    
        fetchData();
      }, [api]);
    
      const formatCurrency = useCallback((amount) => {
        return new Intl.NumberFormat("en-IN", {
          style: "currency",
          currency: "INR",
          minimumFractionDigits: 0,
          maximumFractionDigits: 0,
        }).format(amount || 0);
      }, []);
    
      const handleSave = useCallback(
        async (type, data) => {
          try {
            const lowerType = type.toLowerCase();
            const isEdit = !!editingItem;
            let endpoint = "";
            let method = "POST";
            let payload = { ...data };
    
            console.log("Original form data:", data); // Debug log
    
            // Transform data for laptops to match backend expectations
            if (lowerType === "laptop") {
              // Ensure all required fields have values
              const requiredFields = {
                name: data.name || "",
                processor: data.processor || "",
                price: parseFloat(data.price) || 0,
                Brand: data.brand || data.Brand || "",
                RAM: data.ram || data.RAM || "",
                Storage: data.storage || data.Storage || "",
                Graphic: data.graphic || data.Graphic || "",
                Display: data.display || data.Display || "",
                category: data.category || "",
                serialNumber: data.serialNumber || "",
                mode: data.mode || "buy",
                status: data.status || "available"
              };
    
              payload = {
                ...requiredFields,
                // Ensure we don't send the lowercase variants to avoid confusion
              };
    
              // Remove any empty strings for optional fields but keep required ones
              if (!payload.Storage) delete payload.Storage;
              if (!payload.Graphic) delete payload.Graphic;
              if (!payload.Display) delete payload.Display;
              if (!payload.category) delete payload.category;
              if (!payload.serialNumber) delete payload.serialNumber;
            }
    
            // Transform data for rentals
            if (lowerType === "rental") {
              payload = {
                ...data,
                totalAmount: parseFloat(data.totalAmount) || 0,
                advancePaid: parseFloat(data.advancePaid) || 0,
              };
            }
    
            console.log("Transformed payload:", payload); // Debug log
    
            if (isEdit) {
              method = "PUT";
              switch (lowerType) {
                case "customer":
                  endpoint = `/api/users/customers/${editingItem._id}`;
                  break;
                case "laptop":
                  endpoint = `/api/laptops/${editingItem._id}`;
                  break;
                case "rental":
                  endpoint = `/api/equipment/activity/${editingItem._id}`;
                  break;
                default:
                  throw new Error("Invalid type for update");
              }
            } else {
              switch (lowerType) {
                case "customer":
                  endpoint = `/api/users/customers`;
                  break;
                case "laptop":
                  endpoint = `/api/laptops`;
                  break;
                case "rental":
                  endpoint = `/api/equipment/activity`;
                  break;
                default:
                  throw new Error("Invalid type for creation");
              }
            }
    
            console.log(`Making ${method} request to ${endpoint}`, payload);
    
            const response = await api[method.toLowerCase()](endpoint, payload);
    
            console.log("Server response:", response.data);
    
            switch (lowerType) {
              case "customer":
                setCustomers((prev) =>
                  isEdit
                    ? prev.map((c) =>
                        c._id === editingItem._id ? response.data : c
                      )
                    : [...prev, response.data]
                );
                break;
              case "laptop":
                setInventory((prev) =>
                  isEdit
                    ? prev.map((i) =>
                        i._id === editingItem._id ? response.data : i
                      )
                    : [...prev, response.data]
                );
                break;
              case "rental":
                setRentals((prev) =>
                  isEdit
                    ? prev.map((r) =>
                        r._id === editingItem._id ? response.data : r
                      )
                    : [...prev, response.data]
                );
                break;
              default:
                break;
            }
    
            setShowModal(false);
            setEditingItem(null);
            setError(null);
          } catch (err) {
            console.error("Error saving data:", err);
            console.error("Error response:", err.response?.data);
            
            if (err.response?.data?.errors) {
              console.error("Validation errors:", err.response.data.errors);
            }
            
            setError(err.response?.data?.message || err.message);
          }
        },
        [api, editingItem]
      );
    
      const handleDelete = useCallback(
        async (type, id) => {
          if (
            window.confirm(
              `Are you sure you want to delete this ${type.toLowerCase()}?`
            )
          ) {
            try {
              let endpoint = "";
              switch (type.toLowerCase()) {
                case "customer":
                  endpoint = `/api/users/customers/${id}`;
                  break;
                case "laptop":
                  endpoint = `/api/laptops/${id}`;
                  break;
                case "rental":
                  endpoint = `/api/equipment/activity/${id}`;
                  break;
                default:
                  throw new Error("Invalid type for deletion");
              }
    
              await api.delete(endpoint);
    
              switch (type.toLowerCase()) {
                case "customer":
                  setCustomers((prev) => prev.filter((c) => c._id !== id));
                  break;
                case "laptop":
                  setInventory((prev) => prev.filter((i) => i._id !== id));
                  break;
                case "rental":
                  setRentals((prev) => prev.filter((r) => r._id !== id));
                  break;
                default:
                  break;
              }
            } catch (err) {
              setError(err.response?.data?.message || err.message);
              console.error("Error deleting item:", err);
            }
          }
        },
        [api]
      );
    
      const openModal = useCallback((type, item = null) => {
        setModalType(type);
        setEditingItem(item);
        setShowModal(true);
        setError(null);
      }, []);
    
      const Modal = React.memo(
        ({ type, item, onSave, onClose, customers, inventory }) => {
          const getDefaultFormData = useCallback((type) => {
            switch (type.toLowerCase()) {
              case "customer":
                return {
                  name: "",
                  email: "",
                  mobile: "",
                  address: "",
                  company: "",
                  status: "Active",
                };
              case "laptop":
                return {
                  name: "",
                  processor: "",
                  price: "",
                  ram: "",
                  storage: "",
                  graphic: "",
                  display: "",
                  category: "",
                  brand: "",
                  serialNumber: "",
                  mode: "buy",
                  status: "available",
                };
              case "rental":
                return {
                  customerId: "",
                  laptopId: "",
                  startDate: "",
                  endDate: "",
                  totalAmount: 0,
                  advancePaid: 0,
                };
              default:
                return {};
            }
          }, []);
    
          const [formData, setFormData] = useState(() => {
            const defaultData = getDefaultFormData(type);
            
            if (item) {
              console.log("Editing item:", item); // Debug log
              
              return {
                ...defaultData,
                ...item,
                // Handle field name mapping for laptops
                brand: item.Brand || item.brand || "",
                ram: item.RAM || item.ram || "",
                storage: item.Storage || item.storage || "",
                graphic: item.Graphic || item.graphic || "",
                display: item.Display || item.display || "",
                price: item.price ? item.price.toString() : "",
                totalAmount: item.totalAmount || 0,
                advancePaid: item.advancePaid || 0,
                startDate: item.startDate ? item.startDate.split("T")[0] : "",
                endDate: item.endDate ? item.endDate.split("T")[0] : "",
              };
            }
            return defaultData;
          });
    
          const [errors, setErrors] = useState({});
    
          useEffect(() => {
            const defaultData = getDefaultFormData(type);
            
            if (item) {
              console.log("Updating form data with item:", item);
              
              setFormData({
                ...defaultData,
                ...item,
                brand: item.Brand || item.brand || "",
                ram: item.RAM || item.ram || "",
                storage: item.Storage || item.storage || "",
                graphic: item.Graphic || item.graphic || "",
                display: item.Display || item.display || "",
                price: item.price ? item.price.toString() : "",
                totalAmount: item.totalAmount || 0,
                advancePaid: item.advancePaid || 0,
                startDate: item.startDate ? item.startDate.split("T")[0] : "",
                endDate: item.endDate ? item.endDate.split("T")[0] : "",
              });
            } else {
              setFormData(defaultData);
            }
            setErrors({});
          }, [item, type, getDefaultFormData]);
    
          const handleChange = useCallback((e) => {
            const { name, value } = e.target;
            setFormData((prev) => ({
              ...prev,
              [name]: value,
            }));
            
            if (errors[name]) {
              setErrors(prev => ({
                ...prev,
                [name]: ""
              }));
            }
          }, [errors]);
    
          const validateForm = useCallback(() => {
            const newErrors = {};
    
            const isEmpty = (str) => !str || str.toString().trim() === "";
            const isValidNumber = (num) => !isNaN(parseFloat(num)) && parseFloat(num) > 0;
    
            console.log("Validating form data:", formData); // Debug log
    
            switch (type.toLowerCase()) {
              case "customer":
                if (isEmpty(formData.name)) newErrors.name = "Name is required";
                if (isEmpty(formData.email)) newErrors.email = "Email is required";
                else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
                  newErrors.email = "Valid email is required";
                }
                if (isEmpty(formData.mobile)) newErrors.mobile = "Mobile is required";
                break;
              case "laptop":
                if (isEmpty(formData.name)) newErrors.name = "Laptop name is required";
                if (isEmpty(formData.price) || !isValidNumber(formData.price)) {
                  newErrors.price = "Valid price is required";
                }
                if (isEmpty(formData.processor)) newErrors.processor = "Processor is required";
                if (isEmpty(formData.ram)) newErrors.ram = "RAM is required";
                if (isEmpty(formData.brand)) newErrors.brand = "Brand is required";
                if (!formData.mode || !["buy", "rent"].includes(formData.mode)) {
                  newErrors.mode = "Select mode: buy or rent";
                }
                break;
              case "rental":
                if (isEmpty(formData.customerId)) newErrors.customerId = "Customer is required";
                if (isEmpty(formData.laptopId)) newErrors.laptopId = "Laptop is required";
                if (isEmpty(formData.startDate)) newErrors.startDate = "Start date is required";
                if (isEmpty(formData.endDate)) newErrors.endDate = "End date is required";
                else if (new Date(formData.endDate) <= new Date(formData.startDate)) {
                  newErrors.endDate = "End date must be after start date";
                }
                break;
              default:
                break;
            }
    
            console.log("Validation errors:", newErrors); // Debug log
            setErrors(newErrors);
            return Object.keys(newErrors).length === 0;
          }, [formData, type]);
    
          const handleSubmit = useCallback(
            async (e) => {
              e.preventDefault();
              console.log("Submitting form with data:", formData);
              
              if (validateForm()) {
                await onSave(type, formData);
              } else {
                console.log("Form validation failed");
              }
            },
            [formData, onSave, validateForm, type]
          );
    
          const renderFormFields = useCallback(() => {
            switch (type.toLowerCase()) {
              case "customer":
                return (
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Name *
                      </label>
                      <input
                        type="text"
                        name="name"
                        value={formData.name || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.name ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.name && (
                        <p className="mt-1 text-sm text-red-600">{errors.name}</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Email *
                      </label>
                      <input
                        type="email"
                        name="email"
                        value={formData.email || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.email ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.email && (
                        <p className="mt-1 text-sm text-red-600">{errors.email}</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Mobile *
                      </label>
                      <input
                        type="text"
                        name="mobile"
                        value={formData.mobile || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.mobile ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.mobile && (
                        <p className="mt-1 text-sm text-red-600">{errors.mobile}</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Address
                      </label>
                      <textarea
                        name="address"
                        value={formData.address || ""}
                        onChange={handleChange}
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                        rows="3"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Company
                      </label>
                      <input
                        type="text"
                        name="company"
                        value={formData.company || ""}
                        onChange={handleChange}
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Status
                      </label>
                      <select
                        name="status"
                        value={formData.status || "Active"}
                        onChange={handleChange}
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      >
                        <option value="Active">Active</option>
                        <option value="Inactive">Inactive</option>
                      </select>
                    </div>
                  </div>
                );
              case "laptop":
                return (
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Laptop Name *
                      </label>
                      <input
                        type="text"
                        name="name"
                        value={formData.name || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.name ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.name && (
                        <p className="mt-1 text-sm text-red-600">{errors.name}</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Brand *
                      </label>
                      <input
                        type="text"
                        name="brand"
                        value={formData.brand || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.brand ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.brand && (
                        <p className="mt-1 text-sm text-red-600">{errors.brand}</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Processor *
                      </label>
                      <input
                        type="text"
                        name="processor"
                        value={formData.processor || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.processor ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.processor && (
                        <p className="mt-1 text-sm text-red-600">
                          {errors.processor}
                        </p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        RAM *
                      </label>
                      <input
                        type="text"
                        name="ram"
                        value={formData.ram || ""}
                        onChange={handleChange}
                        placeholder="e.g., 8GB"
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.ram ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.ram && (
                        <p className="mt-1 text-sm text-red-600">{errors.ram}</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Storage
                      </label>
                      <input
                        type="text"
                        name="storage"
                        value={formData.storage || ""}
                        onChange={handleChange}
                        placeholder="e.g., 512GB SSD"
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Graphics
                      </label>
                      <input
                        type="text"
                        name="graphic"
                        value={formData.graphic || ""}
                        onChange={handleChange}
                        placeholder="e.g., Integrated"
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Display
                      </label>
                      <input
                        type="text"
                        name="display"
                        value={formData.display || ""}
                        onChange={handleChange}
                        placeholder="e.g., 15.6 inch"
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Category
                      </label>
                      <input
                        type="text"
                        name="category"
                        value={formData.category || ""}
                        onChange={handleChange}
                        placeholder="e.g., Gaming, Business"
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Serial Number
                      </label>
                      <input
                        type="text"
                        name="serialNumber"
                        value={formData.serialNumber || ""}
                        onChange={handleChange}
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Price (₹) *
                      </label>
                      <input
                        type="number"
                        name="price"
                        value={formData.price || ""}
                        onChange={handleChange}
                        min="0"
                        step="0.01"
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.price ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.price && (
                        <p className="mt-1 text-sm text-red-600">{errors.price}</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Mode *
                      </label>
                      <select
                        name="mode"
                        value={formData.mode || "buy"}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.mode ? 'border-red-300' : 'border-gray-300'
                        }`}
                      >
                        <option value="buy">Buy</option>
                        <option value="rent">Rent</option>
                      </select>
                      {errors.mode && (
                        <p className="mt-1 text-sm text-red-600">{errors.mode}</p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Status
                      </label>
                      <select
                        name="status"
                        value={formData.status || "available"}
                        onChange={handleChange}
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      >
                        <option value="available">Available</option>
                        <option value="rented">Rented</option>
                        <option value="sold">Sold</option>
                        <option value="maintenance">Maintenance</option>
                      </select>
                    </div>
                  </div>
                );
              case "rental":
                return (
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Customer *
                      </label>
                      <select
                        name="customerId"
                        value={formData.customerId || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.customerId ? 'border-red-300' : 'border-gray-300'
                        }`}
                      >
                        <option value="">Select Customer</option>
                        {customers.map((customer) => (
                          <option key={customer._id} value={customer._id}>
                            {customer.name}
                          </option>
                        ))}
                      </select>
                      {errors.customerId && (
                        <p className="mt-1 text-sm text-red-600">
                          {errors.customerId}
                        </p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Laptop *
                      </label>
                      <select
                        name="laptopId"
                        value={formData.laptopId || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.laptopId ? 'border-red-300' : 'border-gray-300'
                        }`}
                      >
                        <option value="">Select Laptop</option>
                        {inventory
                          .filter((item) => item.status === "available" || item._id === formData.laptopId)
                          .map((laptop) => (
                            <option key={laptop._id} value={laptop._id}>
                              {laptop.Brand || laptop.brand} {laptop.name}
                            </option>
                          ))}
                      </select>
                      {errors.laptopId && (
                        <p className="mt-1 text-sm text-red-600">
                          {errors.laptopId}
                        </p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Start Date *
                      </label>
                      <input
                        type="date"
                        name="startDate"
                        value={formData.startDate || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.startDate ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.startDate && (
                        <p className="mt-1 text-sm text-red-600">
                          {errors.startDate}
                        </p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        End Date *
                      </label>
                      <input
                        type="date"
                        name="endDate"
                        value={formData.endDate || ""}
                        onChange={handleChange}
                        className={`mt-1 block w-full rounded-md shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm ${
                          errors.endDate ? 'border-red-300' : 'border-gray-300'
                        }`}
                      />
                      {errors.endDate && (
                        <p className="mt-1 text-sm text-red-600">
                          {errors.endDate}
                        </p>
                      )}
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Total Amount (₹)
                      </label>
                      <input
                        type="number"
                        name="totalAmount"
                        value={formData.totalAmount || ""}
                        onChange={handleChange}
                        min="0"
                        step="0.01"
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700">
                        Advance Paid (₹)
                      </label>
                      <input
                        type="number"
                        name="advancePaid"
                        value={formData.advancePaid || ""}
                        onChange={handleChange}
                        min="0"
                        step="0.01"
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      />
                    </div>
                  </div>
                );
              default:
                return null;
            }
          }, [type, formData, errors, handleChange, customers, inventory]);
    
          return (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
              <div className="bg-white rounded-lg p-6 w-full max-w-md max-h-[90vh] overflow-y-auto">
                <h3 className="text-lg font-semibold mb-4 text-blue-800">
                  {item ? "Edit" : "Add"} {type}
                </h3>
                <form onSubmit={handleSubmit}>
                  {renderFormFields()}
                  <div className="flex gap-2 pt-4">
                    <button
                      type="submit"
                      className="flex-1 bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 font-medium transition-colors"
                    >
                      Save {type}
                    </button>
                    <button
                      type="button"
                      onClick={onClose}
                      className="flex-1 bg-gray-300 text-gray-700 py-3 px-4 rounded-lg hover:bg-gray-400 font-medium transition-colors"
                    >
                      Cancel
                    </button>
                  </div>
                </form>
              </div>
            </div>
          );
        }
      );
    
      if (loading) {
        return (
          <div className="flex justify-center items-center h-screen">
            <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
          </div>
        );
      }
    
      if (error) {
        return (
          <div className="flex justify-center items-center h-screen text-red-500">
            <div className="bg-red-100 border border-red-400 p-4 rounded-lg max-w-md">
              <div className="flex items-center">
                <h3 className="font-medium text-red-800">Error loading data</h3>
              </div>
              <p className="mt-2 text-sm text-red-700">{error}</p>
              <button
                onClick={() => {
                  setError(null);
                  window.location.reload();
                }}
                className="mt-3 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 text-sm transition-colors"
              >
                Retry
              </button>
            </div>
          </div>
        );
      }
    
      return (
        <div className="min-h-screen bg-gray-50">
          <nav className="bg-white shadow-sm">
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
              <div className="flex justify-between h-16">
                <div className="flex items-center">
                  <Laptop className="h-8 w-8 text-blue-600" />
                  <span className="ml-2 text-xl font-semibold text-gray-900">
                    Aura Tech CRM
                  </span>
                </div>
                <div className="hidden md:flex items-center space-x-4">
                  {[
                    "dashboard",
                    "customers",
                    "inventory",
                    "rentals",
                    "sales",
                    "expenses",
                  ].map((tab) => (
                    <button
                      key={tab}
                      onClick={() => setActiveTab(tab)}
                      className={`px-3 py-2 rounded-md text-sm font-medium transition-colors ${
                        activeTab === tab
                          ? "bg-blue-100 text-blue-700"
                          : "text-gray-600 hover:text-gray-900"
                      }`}
                    >
                      {tab.charAt(0).toUpperCase() + tab.slice(1)}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </nav>
    
          <div className="md:hidden bg-white border-t border-gray-200">
            <div className="px-4 py-2">
              <select
                value={activeTab}
                onChange={(e) => setActiveTab(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm"
              >
                {[
                  "dashboard",
                  "customers",
                  "inventory",
                  "rentals",
                  "sales",
                  "expenses",
                ].map((tab) => (
                  <option key={tab} value={tab}>
                    {tab.charAt(0).toUpperCase() + tab.slice(1)}
                  </option>
                ))}
              </select>
            </div>
          </div>
    
          {error && (
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
              <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
                <span className="block sm:inline">{error}</span>
                <button
                  onClick={() => setError(null)}
                  className="float-right text-red-500 hover:text-red-700"
                >
                  ×
                </button>
              </div>
            </div>
          )}
    
          <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
            {activeTab === "dashboard" && (
              <Dashboard
                customers={customers}
                inventory={inventory}
                rentals={rentals}
                sales={sales}
                formatCurrency={formatCurrency}
              />
            )}
            {activeTab === "customers" && (
              <Customers
                customers={customers}
                onEdit={(item) => openModal("Customer", item)}
                onDelete={(id) => handleDelete("Customer", id)}
                onAdd={() => openModal("Customer")}
                formatCurrency={formatCurrency}
              />
            )}
            {activeTab === "inventory" && (
              <Inventory
                inventory={inventory}
                onEdit={(item) => openModal("Laptop", item)}
                onDelete={(id) => handleDelete("Laptop", id)}
                onAdd={() => openModal("Laptop")}
                formatCurrency={formatCurrency}
              />
            )}
            {activeTab === "rentals" && (
              <Rentals
                rentals={rentals}
                customers={customers}
                inventory={inventory}
                onEdit={(item) => openModal("Rental", item)}
                onDelete={(id) => handleDelete("Rental", id)}
                onAdd={() => openModal("Rental")}
                formatCurrency={formatCurrency}
              />
            )}
            {activeTab === "sales" && (
              <Sales
                sales={sales}
                customers={customers}
                inventory={inventory}
                formatCurrency={formatCurrency}
              />
            )}
            {activeTab === "expenses" && (
              <Expenses expenses={expenses} formatCurrency={formatCurrency} />
            )}
          </main>
    
          {showModal && (
            <Modal
              type={modalType}
              item={editingItem}
              onSave={handleSave}
              onClose={() => {
                setShowModal(false);
                setEditingItem(null);
                setError(null);
              }}
              customers={customers}
              inventory={inventory}
            />
          )}
        </div>
      );
    };
    
    export default React.memo(CRMDashboard);
    

    Key fixes made:

    1. Enhanced debugging - Added console logs to track exactly what data is being sent
    2. Proper field mapping - Ensures frontend fields (ram, brand) are correctly mapped to backend fields (RAM, Brand)
    3. Required field validation - Makes sure all required fields have proper values before sending
    4. Better form initialization - Properly handles both create and edit modes
    5. Cleaned data structure - Removes empty optional fields to avoid backend validation issues

    The debug logs will help you see exactly what's being sent to the backend. Check the browser console to see the "Transformed payload" and compare it with what your backend expects.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.

Identical first prompt