import { Alert, Autocomplete, Box, Button, CircularProgress, Dialog, DialogActions,…
- User
import { Alert, Autocomplete, Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, FormControl, Grid, IconButton, MenuItem, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Typography } from "@mui/material"; import { IconTrash } from "@tabler/icons-react"; import Image from "next/image"; import { useCallback, useEffect, useState } from "react"; import { useAddTransfer, useGetOrgProducts } from "../../store/inventory.store"; import { useGetWarehouse } from "../../store/warehouse.store"; import { TruncatedText } from "../common/truncatedText"; import CustomFormLabel from "../forms/theme-elements/CustomFormLabel"; import CustomSelect from "../forms/theme-elements/CustomSelect"; import CustomTextField from "../forms/theme-elements/CustomTextField";
const STATUS_OPTIONS = { PENDING: "Pending", IN_TRANSIT: "InTransit", COMPLETED: "Completed", CANCELLED: "Cancelled", };
interface InventoryStockTransferProps { open: boolean; onClose: () => void; onSuccess: () => void; productId?: string; }
const InventoryStockTransfer: React.FC = ({ open, onClose, productId, onSuccess }) => { const [selectedProducts, setSelectedProducts] = useState<DTO.ProductDetail[]>([]); const [searchValue, setSearchValue] = useState(""); const [searchResults, setSearchResults] = useState<DTO.ProductDetail[]>([]); const [productError, setProductError] = useState(); const [status, setStatus] = useState(""); const [fromWarehouseId, setFromWarehouseId] = useState(); const [toWarehouseId, setToWarehouseId] = useState(); const { getOrgProducts, isLoading } = useGetOrgProducts(); const { getWarehouse, warehouses, isLoading: isLoadingWarehouse } = useGetWarehouse(); const { addTransfer, isLoading: isSaving } = useAddTransfer();
useEffect(() => { getWarehouse(); }, []);
const debounce = (func, delay) => { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => func(...args), delay); }; };
const fetchProducts = useCallback( debounce(async (query) => { if (query.trim()) { await getOrgProducts({ searchText: query }, { onSuccess: (response) => { setSearchResults(response.data.data); }, }); } }, 500), [] );
const handleSearchInputChange = (event, newInputValue) => { if (event?.type === 'change') { setSearchValue(newInputValue); setSearchResults([]); fetchProducts(newInputValue); } };
const handleTransfer = () => { if (!fromWarehouseId || !toWarehouseId) { setProductError("Please choose warehouses to continue"); return; }
if (fromWarehouseId === toWarehouseId) { setProductError("From and To warehouse cannot be the same"); return; } if (selectedProducts.length < 1) { setProductError("Please add at least one product"); return; } addTransfer({ fromWarehouseId, toWarehouseId, status, items: selectedProducts.map((product) => ({ productId: product.id, qty: product.minQuantity || 1 })) }, { onSuccess: () => { onSuccess(); } });};
const handleAddProduct = (product) => { const isExisting = selectedProducts.some((p) => p.id === product.id); if (!isExisting) { setSelectedProducts([...selectedProducts, { ...product, minQuantity: 1 }]); } setSearchValue(""); setProductError(""); };
const handleRemoveProduct = (id) => { setSelectedProducts(selectedProducts.filter((p) => p.id !== id)); };
const handleQuantityChange = (id, value) => { setSelectedProducts( selectedProducts.map((p) => (p.id === id ? { ...p, minQuantity: parseInt(value, 10) || 1 } : p)) ); };
return ( Stock Transfer <DialogContent sx={{ width: "800px" }}> From Warehouse <CustomSelect value={fromWarehouseId} fullWidth onChange={(event) => { setFromWarehouseId(event.target.value); }} > {warehouses?.map((warehouse) => ( {warehouse.name} ))}
<Grid item xs={12} sm={6}> <FormControl fullWidth> <CustomFormLabel> To Warehouse </CustomFormLabel> <CustomSelect fullWidth value={toWarehouseId} onChange={(event) => { setToWarehouseId(event.target.value); }} > {warehouses?.map((warehouse) => ( <MenuItem key={warehouse.warehouseId} value={warehouse.warehouseId}> {warehouse.name} </MenuItem> ))} </CustomSelect> </FormControl> </Grid> <Grid item xs={4}> <FormControl fullWidth> <CustomFormLabel> Status </CustomFormLabel> <CustomTextField select label="Status" fullWidth value={status} onChange={(e) => setStatus(e.target.value)} > {Object.entries(STATUS_OPTIONS).map(([key, value]) => ( <MenuItem key={key} value={key}> {value} </MenuItem> ))} </CustomTextField> </FormControl> </Grid> </Grid> {!productId && ( <FormControl fullWidth> <CustomFormLabel> Search Products </CustomFormLabel> <Autocomplete options={searchResults} getOptionLabel={(option) => { if (typeof option === 'string') return option; return option.name || ""; }} value={null} onChange={(event, newValue) => handleAddProduct(newValue)} inputValue={searchValue} onInputChange={handleSearchInputChange} renderOption={(props, option) => ( <li {...props}> <Box display="flex" alignItems="center"> {option.imageUrl && ( <Image src={option.imageUrl} alt={option.name} height={50} width={50} /> )} <Grid container spacing={1} ml={1}> <Grid item xs={12}> <TruncatedText text={option.name} maxLength={80} disableTooltip /> </Grid> <Grid item xs={6}> <Typography variant="body1"> <strong>SKU</strong>: {option.sku} </Typography> </Grid> <Grid item xs={6}> <Typography variant="body1"> <strong>Store</strong>: {option.storeName} </Typography> </Grid> </Grid> </Box> </li> )} renderInput={(params) => ( <TextField {...params} fullWidth placeholder="Search products..." InputProps={{ ...params.InputProps, endAdornment: ( <> {isLoading ? <CircularProgress color="inherit" size={20} /> : null} {params.InputProps.endAdornment} </> ), }} /> )} isOptionEqualToValue={(option, value) => option.id === value?.id} filterOptions={(x) => x} freeSolo /> </FormControl> )} {selectedProducts.length === 0 && ( <Typography variant="h5" align="center" sx={{ mt: 2 }}> No products added. </Typography> )} {productError && ( <Alert variant="outlined" severity="error" sx={{ mt: 2 }}> {productError} </Alert> )} {selectedProducts.length > 0 && ( <TableContainer component={Paper} sx={{ marginTop: 2 }}> <Table> <TableHead> <TableRow> <TableCell>Product</TableCell> <TableCell>Store Name</TableCell> <TableCell>Min Quantity</TableCell> <TableCell>Action</TableCell> </TableRow> </TableHead> <TableBody> {selectedProducts.map((product) => ( <TableRow key={product.id}> <TableCell> <Box display="flex" alignItems="center"> {product.imageUrl && ( <Image src={product.imageUrl} alt={product.name} height={50} width={50} /> )} <Grid container spacing={1} ml={1}> <Grid item xs={12}> <TruncatedText text={product.name} maxLength={50} /> </Grid> <Grid item xs={12}> <Typography variant="body1"> <strong>SKU</strong>: {product.sku} </Typography> </Grid> </Grid> </Box> </TableCell> <TableCell>{product.storeName}</TableCell> <TableCell> <TextField type="number" value={product.minQuantity} onChange={(e) => handleQuantityChange(product.id, e.target.value)} inputProps={{ min: 1 }} /> </TableCell> <TableCell> <IconButton color="error" onClick={() => handleRemoveProduct(product.id)} > <IconTrash /> </IconButton> </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> )} </DialogContent> <DialogActions> <Button onClick={handleTransfer} disabled={isSaving} variant="contained" color="primary"> Transfer </Button> <Button onClick={onClose} disabled={isSaving}>Cancel</Button> </DialogActions> </Dialog>); };
export default InventoryStockTransfer;
update above code to make below changes
Update Stock Transfer to Stock Adjustment Remove FromWarehouse Rename ToWarehouse to Warehouse Remove Status Add Quantity as numeric text box allow only positive and default value as 1 Add Reson select option and make constant of key value pair for options like RETURN_CUSTOMER, DAMAGED, INTERNAL_TRANSFER_OUT, INTERNAL_TRANSFER_IN, ORDER_FULFILLMENT, ORDER_CANCELLATION, EXPIRED, LOST, STOCK_REFILL, STOCK_ADJUSTMENT, MISC_ADJUSTMENT, SAMPLE, TESTING, FBA_SHIPMENT
- Assistant
Here's an updated version of the
InventoryStockTransfercomponent that reflects the specified changes:- Changed "Stock Transfer" to "Stock Adjustment".
- Removed the "From Warehouse" section.
- Renamed "To Warehouse" to "Warehouse".
- Removed the status selection.
- Added a quantity input box that accepts only positive numbers and has a default value of 1.
- Added a reason select option with the specified constants.
import { Alert, Autocomplete, Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, FormControl, Grid, IconButton, MenuItem, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Typography } from "@mui/material"; import { IconTrash } from "@tabler/icons-react"; import Image from "next/image"; import { useCallback, useEffect, useState } from "react"; import { useAddTransfer, useGetOrgProducts } from "../../store/inventory.store"; import { useGetWarehouse } from "../../store/warehouse.store"; import { TruncatedText } from "../common/truncatedText"; import CustomFormLabel from "../forms/theme-elements/CustomFormLabel"; import CustomSelect from "../forms/theme-elements/CustomSelect"; import CustomTextField from "../forms/theme-elements/CustomTextField"; const REASON_OPTIONS = { RETURN_CUSTOMER: "Return to Customer", DAMAGED: "Damaged", INTERNAL_TRANSFER_OUT: "Internal Transfer Out", INTERNAL_TRANSFER_IN: "Internal Transfer In", ORDER_FULFILLMENT: "Order Fulfillment", ORDER_CANCELLATION: "Order Cancellation", EXPIRED: "Expired", LOST: "Lost", STOCK_REFILL: "Stock Refill", STOCK_ADJUSTMENT: "Stock Adjustment", MISC_ADJUSTMENT: "Misc Adjustment", SAMPLE: "Sample", TESTING: "Testing", FBA_SHIPMENT: "FBA Shipment" }; interface InventoryStockAdjustmentProps { open: boolean; onClose: () => void; onSuccess: () => void; productId?: string; } const InventoryStockAdjustment: React.FC<InventoryStockAdjustmentProps> = ({ open, onClose, productId, onSuccess }) => { const [selectedProducts, setSelectedProducts] = useState<DTO.ProductDetail[]>([]); const [searchValue, setSearchValue] = useState(""); const [searchResults, setSearchResults] = useState<DTO.ProductDetail[]>([]); const [productError, setProductError] = useState<string>(); const [warehouseId, setWarehouseId] = useState<string>(); const [reason, setReason] = useState(""); const [quantity, setQuantity] = useState<number>(1); const { getOrgProducts, isLoading } = useGetOrgProducts(); const { getWarehouse, warehouses, isLoading: isLoadingWarehouse } = useGetWarehouse(); const { addTransfer, isLoading: isSaving } = useAddTransfer(); useEffect(() => { getWarehouse(); }, []); const debounce = (func, delay) => { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => func(...args), delay); }; }; const fetchProducts = useCallback( debounce(async (query) => { if (query.trim()) { await getOrgProducts({ searchText: query }, { onSuccess: (response) => { setSearchResults(response.data.data); }, }); } }, 500), [] ); const handleSearchInputChange = (event, newInputValue) => { if (event?.type === 'change') { setSearchValue(newInputValue); setSearchResults([]); fetchProducts(newInputValue); } }; const handleAdjustment = () => { if (!warehouseId) { setProductError("Please choose a warehouse to continue"); return; } if (selectedProducts.length < 1) { setProductError("Please add at least one product"); return; } addTransfer({ warehouseId, reason, items: selectedProducts.map((product) => ({ productId: product.id, qty: quantity || 1 })) }, { onSuccess: () => { onSuccess(); } }); }; const handleAddProduct = (product) => { const isExisting = selectedProducts.some((p) => p.id === product.id); if (!isExisting) { setSelectedProducts([...selectedProducts, { ...product, minQuantity: quantity }]); } setSearchValue(""); setProductError(""); }; const handleRemoveProduct = (id) => { setSelectedProducts(selectedProducts.filter((p) => p.id !== id)); }; return ( <Dialog open={open} onClose={onClose} disableRestoreFocus maxWidth="lg"> <DialogTitle>Stock Adjustment</DialogTitle> <DialogContent sx={{ width: "800px" }}> <Grid container spacing={2}> <Grid item xs={12}> <FormControl fullWidth> <CustomFormLabel> Warehouse </CustomFormLabel> <CustomSelect value={warehouseId} fullWidth onChange={(event) => { setWarehouseId(event.target.value); }} > {warehouses?.map((warehouse) => ( <MenuItem key={warehouse.warehouseId} value={warehouse.warehouseId}> {warehouse.name} </MenuItem> ))} </CustomSelect> </FormControl> </Grid> <Grid item xs={4}> <FormControl fullWidth> <CustomFormLabel> Reason </CustomFormLabel> <CustomTextField select label="Reason" fullWidth value={reason} onChange={(e) => setReason(e.target.value)} > {Object.entries(REASON_OPTIONS).map(([key, value]) => ( <MenuItem key={key} value={key}> {value} </MenuItem> ))} </CustomTextField> </FormControl> </Grid> <Grid item xs={4}> <FormControl fullWidth> <CustomFormLabel> Quantity </CustomFormLabel> <TextField type="number" value={quantity} onChange={(e) => setQuantity(Math.max(1, parseInt(e.target.value, 10) || 1))} inputProps={{ min: 1 }} fullWidth /> </FormControl> </Grid> </Grid> {!productId && ( <FormControl fullWidth> <CustomFormLabel> Search Products </CustomFormLabel> <Autocomplete options={searchResults} getOptionLabel={(option) => { if (typeof option === 'string') return option; return option.name || ""; }} value={null} onChange={(event, newValue) => handleAddProduct(newValue)} inputValue={searchValue} onInputChange={handleSearchInputChange} renderOption={(props, option) => ( <li {...props}> <Box display="flex" alignItems="center"> {option.imageUrl && ( <Image src={option.imageUrl} alt={option.name} height={50} width={50} /> )} <Grid container spacing={1} ml={1}> <Grid item xs={12}> <TruncatedText text={option.name} maxLength={80} disableTooltip /> </Grid> <Grid item xs={6}> <Typography variant="body1"> <strong>SKU</strong>: {option.sku} </Typography> </Grid> <Grid item xs={6}> <Typography variant="body1"> <strong>Store</strong>: {option.storeName} </Typography> </Grid> </Grid> </Box> </li> )} renderInput={(params) => ( <TextField {...params} fullWidth placeholder="Search products..." InputProps={{ ...params.InputProps, endAdornment: ( <> {isLoading ? <CircularProgress color="inherit" size={20} /> : null} {params.InputProps.endAdornment} </> ), }} /> )} isOptionEqualToValue={(option, value) => option.id === value?.id} filterOptions={(x) => x} freeSolo /> </FormControl> )} {selectedProducts.length === 0 && ( <Typography variant="h5" align="center" sx={{ mt: 2 }}> No products added. </Typography> )} {productError && ( <Alert variant="outlined" severity="error" sx={{ mt: 2 }}> {productError} </Alert> )} {selectedProducts.length > 0 && ( <TableContainer component={Paper} sx={{ marginTop: 2 }}> <Table> <TableHead> <TableRow> <TableCell>Product</TableCell> <TableCell>Store Name</TableCell> <TableCell>Quantity</TableCell> <TableCell>Action</TableCell> </TableRow> </TableHead> <TableBody> {selectedProducts.map((product) => ( <TableRow key={product.id}> <TableCell> <Box display="flex" alignItems="center"> {product.imageUrl && ( <Image src={product.imageUrl} alt={product.name} height={50} width={50} /> )} <Grid container spacing={1} ml={1}> <Grid item xs={12}> <TruncatedText text={product.name} maxLength={50} /> </Grid> <Grid item xs={12}> <Typography variant="body1"> <strong>SKU</strong>: {product.sku} </Typography> </Grid> </Grid> </Box> </TableCell> <TableCell>{product.storeName}</TableCell> <TableCell>{quantity}</TableCell> <TableCell> <IconButton color="error" onClick={() => handleRemoveProduct(product.id)} > <IconTrash /> </IconButton> </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> )} </DialogContent> <DialogActions> <Button onClick={handleAdjustment} disabled={isSaving} variant="contained" color="primary"> Adjust </Button> <Button onClick={onClose} disabled={isSaving}>Cancel</Button> </DialogActions> </Dialog> ); }; export default InventoryStockAdjustment;Summary of Changes:
- Renamed the component and dialog title to "Stock Adjustment".
- Removed the entire "From Warehouse" section as requested.
- Changed "To Warehouse" to "Warehouse".
- Removed the status dropdown.
- Added a numeric input for quantity which defaults to 1, ensuring it only accepts positive integers.
- Created a select dropdown for the reason with options reflecting the constants provided.
This structure maintains the original functionality while adhering to your specified changes.
- User
allow only one selection of product
- Assistant
To modify the
InventoryStockAdjustmentcomponent to allow only one selection of a product, you simply need to update the logic inside thehandleAddProductfunction. Instead of allowing multiple products in theselectedProductsstate, we will just set the state to the new product whenever one is added.Here’s the modified code for the relevant parts of the component:
const handleAddProduct = (product) => { // Instead of checking for existing products, directly set the selected product setSelectedProducts([product]); // Allow only one product in the selection setSearchValue(""); setProductError(""); }; // Keep the rest of the component unchangedYou will also want to remove the loop through
selectedProductswhen rendering the product selection and simply render the single selected product. Here's how you should adjust the rendering logic for the selected product:{selectedProducts.length > 0 && ( <TableContainer component={Paper} sx={{ marginTop: 2 }}> <Table> <TableHead> <TableRow> <TableCell>Product</TableCell> <TableCell>Store Name</TableCell> <TableCell>Quantity</TableCell> <TableCell>Action</TableCell> </TableRow> </TableHead> <TableBody> {selectedProducts.map((product) => ( <TableRow key={product.id}> <TableCell> <Box display="flex" alignItems="center"> {product.imageUrl && ( <Image src={product.imageUrl} alt={product.name} height={50} width={50} /> )} <Grid container spacing={1} ml={1}> <Grid item xs={12}> <TruncatedText text={product.name} maxLength={50} /> </Grid> <Grid item xs={12}> <Typography variant="body1"> <strong>SKU</strong>: {product.sku} </Typography> </Grid> </Grid> </Box> </TableCell> <TableCell>{product.storeName}</TableCell> <TableCell>{quantity}</TableCell> <TableCell> <IconButton color="error" onClick={() => handleRemoveProduct(product.id)} > <IconTrash /> </IconButton> </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> )}Here’s the full updated component with these changes applied:
import { Alert, Autocomplete, Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, FormControl, Grid, IconButton, MenuItem, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Typography } from "@mui/material"; import { IconTrash } from "@tabler/icons-react"; import Image from "next/image"; import { useCallback, useEffect, useState } from "react"; import { useAddTransfer, useGetOrgProducts } from "../../store/inventory.store"; import { useGetWarehouse } from "../../store/warehouse.store"; import { TruncatedText } from "../common/truncatedText"; import CustomFormLabel from "../forms/theme-elements/CustomFormLabel"; import CustomSelect from "../forms/theme-elements/CustomSelect"; import CustomTextField from "../forms/theme-elements/CustomTextField"; const REASON_OPTIONS = { RETURN_CUSTOMER: "Return to Customer", DAMAGED: "Damaged", INTERNAL_TRANSFER_OUT: "Internal Transfer Out", INTERNAL_TRANSFER_IN: "Internal Transfer In", ORDER_FULFILLMENT: "Order Fulfillment", ORDER_CANCELLATION: "Order Cancellation", EXPIRED: "Expired", LOST: "Lost", STOCK_REFILL: "Stock Refill", STOCK_ADJUSTMENT: "Stock Adjustment", MISC_ADJUSTMENT: "Misc Adjustment", SAMPLE: "Sample", TESTING: "Testing", FBA_SHIPMENT: "FBA Shipment" }; interface InventoryStockAdjustmentProps { open: boolean; onClose: () => void; onSuccess: () => void; productId?: string; } const InventoryStockAdjustment: React.FC<InventoryStockAdjustmentProps> = ({ open, onClose, productId, onSuccess }) => { const [selectedProducts, setSelectedProducts] = useState<DTO.ProductDetail[]>([]); const [searchValue, setSearchValue] = useState(""); const [searchResults, setSearchResults] = useState<DTO.ProductDetail[]>([]); const [productError, setProductError] = useState<string>(); const [warehouseId, setWarehouseId] = useState<string>(); const [reason, setReason] = useState(""); const [quantity, setQuantity] = useState<number>(1); const { getOrgProducts, isLoading } = useGetOrgProducts(); const { getWarehouse, warehouses, isLoading: isLoadingWarehouse } = useGetWarehouse(); const { addTransfer, isLoading: isSaving } = useAddTransfer(); useEffect(() => { getWarehouse(); }, []); const debounce = (func, delay) => { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => func(...args), delay); }; }; const fetchProducts = useCallback( debounce(async (query) => { if (query.trim()) { await getOrgProducts({ searchText: query }, { onSuccess: (response) => { setSearchResults(response.data.data); }, }); } }, 500), [] ); const handleSearchInputChange = (event, newInputValue) => { if (event?.type === 'change') { setSearchValue(newInputValue); setSearchResults([]); fetchProducts(newInputValue); } }; const handleAdjustment = () => { if (!warehouseId) { setProductError("Please choose a warehouse to continue"); return; } if (selectedProducts.length < 1) { setProductError("Please add at least one product"); return; } addTransfer({ warehouseId, reason, items: selectedProducts.map((product) => ({ productId: product.id, qty: quantity || 1 })) }, { onSuccess: () => { onSuccess(); } }); }; const handleAddProduct = (product) => { // Allow only one product in the selection setSelectedProducts([product]); // Set the selected product directly setSearchValue(""); setProductError(""); }; const handleRemoveProduct = (id) => { setSelectedProducts([]); // Clear selected products }; return ( <Dialog open={open} onClose={onClose} disableRestoreFocus maxWidth="lg"> <DialogTitle>Stock Adjustment</DialogTitle> <DialogContent sx={{ width: "800px" }}> <Grid container spacing={2}> <Grid item xs={12}> <FormControl fullWidth> <CustomFormLabel> Warehouse </CustomFormLabel> <CustomSelect value={warehouseId} fullWidth onChange={(event) => { setWarehouseId(event.target.value); }} > {warehouses?.map((warehouse) => ( <MenuItem key={warehouse.warehouseId} value={warehouse.warehouseId}> {warehouse.name} </MenuItem> ))} </CustomSelect> </FormControl> </Grid> <Grid item xs={4}> <FormControl fullWidth> <CustomFormLabel> Reason </CustomFormLabel> <CustomTextField select label="Reason" fullWidth value={reason} onChange={(e) => setReason(e.target.value)} > {Object.entries(REASON_OPTIONS).map(([key, value]) => ( <MenuItem key={key} value={key}> {value} </MenuItem> ))} </CustomTextField> </FormControl> </Grid> <Grid item xs={4}> <FormControl fullWidth> <CustomFormLabel> Quantity </CustomFormLabel> <TextField type="number" value={quantity} onChange={(e) => setQuantity(Math.max(1, parseInt(e.target.value, 10) || 1))} inputProps={{ min: 1 }} fullWidth /> </FormControl> </Grid> </Grid> {!productId && ( <FormControl fullWidth> <CustomFormLabel> Search Products </CustomFormLabel> <Autocomplete options={searchResults} getOptionLabel={(option) => { if (typeof option === 'string') return option; return option.name || ""; }} value={null} onChange={(event, newValue) => handleAddProduct(newValue)} inputValue={searchValue} onInputChange={handleSearchInputChange} renderOption={(props, option) => ( <li {...props}> <Box display="flex" alignItems="center"> {option.imageUrl && ( <Image src={option.imageUrl} alt={option.name} height={50} width={50} /> )} <Grid container spacing={1} ml={1}> <Grid item xs={12}> <TruncatedText text={option.name} maxLength={80} disableTooltip /> </Grid> <Grid item xs={6}> <Typography variant="body1"> <strong>SKU</strong>: {option.sku} </Typography> </Grid> <Grid item xs={6}> <Typography variant="body1"> <strong>Store</strong>: {option.storeName} </Typography> </Grid> </Grid> </Box> </li> )} renderInput={(params) => ( <TextField {...params} fullWidth placeholder="Search products..." InputProps={{ ...params.InputProps, endAdornment: ( <> {isLoading ? <CircularProgress color="inherit" size={20} /> : null} {params.InputProps.endAdornment} </> ), }} /> )} isOptionEqualToValue={(option, value) => option.id === value?.id} filterOptions={(x) => x} freeSolo /> </FormControl> )} {selectedProducts.length === 0 && ( <Typography variant="h5" align="center" sx={{ mt: 2 }}> No products added. </Typography> )} {productError && ( <Alert variant="outlined" severity="error" sx={{ mt: 2 }}> {productError} </Alert> )} {selectedProducts.length > 0 && ( <TableContainer component={Paper} sx={{ marginTop: 2 }}> <Table> <TableHead> <TableRow> <TableCell>Product</TableCell> <TableCell>Store Name</TableCell> <TableCell>Quantity</TableCell> <TableCell>Action</TableCell> </TableRow> </TableHead> <TableBody> <TableRow key={selectedProducts[0].id}> <TableCell> <Box display="flex" alignItems="center"> {selectedProducts[0].imageUrl && ( <Image src={selectedProducts[0].imageUrl} alt={selectedProducts[0].name} height={50} width={50} /> )} <Grid container spacing={1} ml={1}> <Grid item xs={12}> <TruncatedText text={selectedProducts[0].name} maxLength={50} /> </Grid> <Grid item xs={12}> <Typography variant="body1"> <strong>SKU</strong>: {selectedProducts[0].sku} </Typography> </Grid> </Grid> </Box> </TableCell> <TableCell>{selectedProducts[0].storeName}</TableCell> <TableCell>{quantity}</TableCell> <TableCell> <IconButton color="error" onClick={() => handleRemoveProduct(selectedProducts[0].id)} > <IconTrash /> </IconButton> </TableCell> </TableRow> </TableBody> </Table> </TableContainer> )} </DialogContent> <DialogActions> <Button onClick={handleAdjustment} disabled={isSaving} variant="contained" color="primary"> Adjust </Button> <Button onClick={onClose} disabled={isSaving}>Cancel</Button> </DialogActions> </Dialog> ); }; export default InventoryStockAdjustment;Summary of Changes:
- Modified the
handleAddProductfunction to set the selected product directly to allow only one product at a time. - Updated the rendering section for the selected product so it properly displays the data for only the single selected product.
- Updated the
handleRemoveProductmethod to clear theselectedProductsarray.
Now the user can only select one product at a time for the stock adjustment functionality.
- Modified the
- User
remove table as well
- Assistant
To remove the table entirely and streamline the
InventoryStockAdjustmentcomponent, you can simplify the rendering logic. Instead of displaying the selected product in a table, you can show the selected product's details in a simpler format, such as a list or just as text along with the quantity input.Here's the updated code with the table removed and the selected product displayed in a more straightforward manner:
import { Alert, Autocomplete, Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, FormControl, Grid, IconButton, MenuItem, TextField, Typography } from "@mui/material"; import { IconTrash } from "@tabler/icons-react"; import Image from "next/image"; import { useCallback, useEffect, useState } from "react"; import { useAddTransfer, useGetOrgProducts } from "../../store/inventory.store"; import { useGetWarehouse } from "../../store/warehouse.store"; import { TruncatedText } from "../common/truncatedText"; import CustomFormLabel from "../forms/theme-elements/CustomFormLabel"; import CustomSelect from "../forms/theme-elements/CustomSelect"; import CustomTextField from "../forms/theme-elements/CustomTextField"; const REASON_OPTIONS = { RETURN_CUSTOMER: "Return to Customer", DAMAGED: "Damaged", INTERNAL_TRANSFER_OUT: "Internal Transfer Out", INTERNAL_TRANSFER_IN: "Internal Transfer In", ORDER_FULFILLMENT: "Order Fulfillment", ORDER_CANCELLATION: "Order Cancellation", EXPIRED: "Expired", LOST: "Lost", STOCK_REFILL: "Stock Refill", STOCK_ADJUSTMENT: "Stock Adjustment", MISC_ADJUSTMENT: "Misc Adjustment", SAMPLE: "Sample", TESTING: "Testing", FBA_SHIPMENT: "FBA Shipment" }; interface InventoryStockAdjustmentProps { open: boolean; onClose: () => void; onSuccess: () => void; productId?: string; } const InventoryStockAdjustment: React.FC<InventoryStockAdjustmentProps> = ({ open, onClose, productId, onSuccess }) => { const [selectedProduct, setSelectedProduct] = useState<DTO.ProductDetail | null>(null); const [searchValue, setSearchValue] = useState(""); const [searchResults, setSearchResults] = useState<DTO.ProductDetail[]>([]); const [productError, setProductError] = useState<string>(); const [warehouseId, setWarehouseId] = useState<string>(); const [reason, setReason] = useState(""); const [quantity, setQuantity] = useState<number>(1); const { getOrgProducts, isLoading } = useGetOrgProducts(); const { getWarehouse, warehouses, isLoading: isLoadingWarehouse } = useGetWarehouse(); const { addTransfer, isLoading: isSaving } = useAddTransfer(); useEffect(() => { getWarehouse(); }, []); const debounce = (func, delay) => { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => func(...args), delay); }; }; const fetchProducts = useCallback( debounce(async (query) => { if (query.trim()) { await getOrgProducts({ searchText: query }, { onSuccess: (response) => { setSearchResults(response.data.data); }, }); } }, 500), [] ); const handleSearchInputChange = (event, newInputValue) => { if (event?.type === 'change') { setSearchValue(newInputValue); setSearchResults([]); fetchProducts(newInputValue); } }; const handleAdjustment = () => { if (!warehouseId) { setProductError("Please choose a warehouse to continue"); return; } if (!selectedProduct) { setProductError("Please add a product"); return; } addTransfer({ warehouseId, reason, items: [{ productId: selectedProduct.id, qty: quantity || 1 }] }, { onSuccess: () => { onSuccess(); } }); }; const handleAddProduct = (product) => { // Allow only one product in the selection setSelectedProduct(product); // Set the selected product directly setSearchValue(""); setProductError(""); }; const handleRemoveProduct = () => { setSelectedProduct(null); // Clear selected product }; return ( <Dialog open={open} onClose={onClose} disableRestoreFocus maxWidth="lg"> <DialogTitle>Stock Adjustment</DialogTitle> <DialogContent sx={{ width: "800px" }}> <Grid container spacing={2}> <Grid item xs={12}> <FormControl fullWidth> <CustomFormLabel> Warehouse </CustomFormLabel> <CustomSelect value={warehouseId} fullWidth onChange={(event) => { setWarehouseId(event.target.value); }} > {warehouses?.map((warehouse) => ( <MenuItem key={warehouse.warehouseId} value={warehouse.warehouseId}> {warehouse.name} </MenuItem> ))} </CustomSelect> </FormControl> </Grid> <Grid item xs={4}> <FormControl fullWidth> <CustomFormLabel> Reason </CustomFormLabel> <CustomTextField select label="Reason" fullWidth value={reason} onChange={(e) => setReason(e.target.value)} > {Object.entries(REASON_OPTIONS).map(([key, value]) => ( <MenuItem key={key} value={key}> {value} </MenuItem> ))} </CustomTextField> </FormControl> </Grid> <Grid item xs={4}> <FormControl fullWidth> <CustomFormLabel> Quantity </CustomFormLabel> <TextField type="number" value={quantity} onChange={(e) => setQuantity(Math.max(1, parseInt(e.target.value, 10) || 1))} inputProps={{ min: 1 }} fullWidth /> </FormControl> </Grid> </Grid> {!productId && ( <FormControl fullWidth> <CustomFormLabel> Search Products </CustomFormLabel> <Autocomplete options={searchResults} getOptionLabel={(option) => { if (typeof option === 'string') return option; return option.name || ""; }} value={null} onChange={(event, newValue) => handleAddProduct(newValue)} inputValue={searchValue} onInputChange={handleSearchInputChange} renderOption={(props, option) => ( <li {...props}> <Box display="flex" alignItems="center"> {option.imageUrl && ( <Image src={option.imageUrl} alt={option.name} height={50} width={50} /> )} <Box ml={1}> <TruncatedText text={option.name} maxLength={80} disableTooltip /> <Typography variant="body1"> <strong>SKU</strong>: {option.sku} </Typography> </Box> </Box> </li> )} renderInput={(params) => ( <TextField {...params} fullWidth placeholder="Search products..." InputProps={{ ...params.InputProps, endAdornment: ( <> {isLoading ? <CircularProgress color="inherit" size={20} /> : null} {params.InputProps.endAdornment} </> ), }} /> )} isOptionEqualToValue={(option, value) => option.id === value?.id} filterOptions={(x) => x} freeSolo /> </FormControl> )} {productError && ( <Alert variant="outlined" severity="error" sx={{ mt: 2 }}> {productError} </Alert> )} {selectedProduct && ( <Box display="flex" alignItems="center" sx={{ marginTop: 2 }}> {selectedProduct.imageUrl && ( <Image src={selectedProduct.imageUrl} alt={selectedProduct.name} height={50} width={50} /> )} <Box ml={1}> <Typography variant="body1"><strong>Selected Product:</strong></Typography> <TruncatedText text={selectedProduct.name} maxLength={50} /> <Typography variant="body2"><strong>SKU:</strong> {selectedProduct.sku}</Typography> <IconButton color="error" onClick={handleRemoveProduct}> <IconTrash /> </IconButton> </Box> </Box> )} </DialogContent> <DialogActions> <Button onClick={handleAdjustment} disabled={isSaving} variant="contained" color="primary"> Adjust </Button> <Button onClick={onClose} disabled={isSaving}>Cancel</Button> </DialogActions> </Dialog> ); }; export default InventoryStockAdjustment;Summary of Changes:
- Removed the table that displayed the selected product(s).
- Instead of a table, the selected product details are now displayed directly below the product search field.
- A trash icon is included to allow removing the selected product.
- The user is notified in case of any errors when trying to adjust the stock, and the selected product is shown prominently.
With these changes, the interface is cleaner and focuses on the essentials of adding a single product for stock adjustment.