// components/modals/CountStockModal.tsx import React from 'react' import axios from 'axios' import { toast } from 'react-hot-toast' import { StockBatch, StockEntry } from "@/types" interface Props { onClose: () => void selectedBatch: () => StockBatch } const CountStockModal: React.FC = ({ onClose, selectedBatch }) => { const [quantity, setQuantity] = React.useState("") const [isDropdownOpen, setIsDropdownOpen] = React.useState(false) const [selectedEntry, setSelectedEntry] = React.useState(null) const handleSelect = (entry: StockEntry) => { setSelectedEntry(entry) setIsDropdownOpen(false) } const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() if (!selectedEntry) { toast.error("Please select a product first.") return } try { const { data } = await axios.post( "/api/pdaView/countStock", { entryId: selectedEntry.id, quantity, }, { withCredentials: true } ) // If the HTTP status was 200 but success===false, // inspect data.error to decide which toast to show if (!data.success) { switch (data.error) { case "already_counted": toast.error("This item has already been counted.") break case "validation_failed": toast.error("Validation failed. Please check your inputs.") break case "not_found": toast.error("Could not find that stock entry.") break case "server_error": default: // show the message from the server if provided, otherwise fallback toast.error( data.message ?? "Something went wrong on the server." ) break } return } // success === true: toast.success("Stock counted!") onClose() } catch (err: any) { // If the request itself failed (e.g. network or HTTP 500 that didn't return JSON): // You can inspect err.response.status if you want, e.g. 409 → extract JSON, etc. if (err.response && err.response.data) { // Attempt to read the server’s JSON error payload const payload = err.response.data if (payload.error === "already_counted") { toast.error("This item has already been counted.") return } if (payload.error === "validation_failed") { toast.error("Validation failed. Please check your inputs.") return } if (payload.error === "not_found") { toast.error("Could not find that stock entry.") return } // Fallback to any message string toast.error(payload.message || "Unknown error occurred.") return } // Otherwise, a true “network” or unexpected error: toast.error("Failed to count stock. Please try again.") } } return (

Count Stock

{/* Product Dropdown */}
    {selectedBatch.stock_entries.map((entry) => (
  • ))} {selectedBatch.stock_entries.length === 0 && (
  • No items available
  • )}
{/* Quantity Input */}
setQuantity(+e.target.value)} className="input input-bordered w-full" required />
{/* Actions */}
) } export default CountStockModal