javascript Copy code
import {
Alert,
Autocomplete,
Box,
Button,
CircularProgress,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
FormControl,
FormControlLabel,
Grid,
IconButton,
MenuItem,
Paper,
Radio,
RadioGroup,
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, useGetStockTransfer } from "../../store/inventory.store";
import { useGetWarehouse } from "../../store/warehouse.store";
import { TRANSFER_STATUS_OPTIONS } from "../../utils/constants";
import { TruncatedText } from "../common/truncatedText";
import CustomFormLabel from "../forms/theme-elements/CustomFormLabel";
import CustomLoadingButton from "../forms/theme-elements/CustomLoadingButton";
import CustomSelect from "../forms/theme-elements/CustomSelect";
interface InventoryStockTransferProps {
open: boolean;
onClose: () => void;
onSuccess: () => void;
productId?: string;
stockTransferId?: string; // added parameter for edit mode
showCancelledOption?: boolean;
}
const InventoryStockTransfer: React.FC<InventoryStockTransferProps> = ({ open, onClose, productId, onSuccess, stockTransferId, showCancelledOption }) => {
const [selectedProducts, setSelectedProducts] = useState<DTO.ProductDetail[]>([]);
const [searchValue, setSearchValue] = useState("");
const [searchResults, setSearchResults] = useState<DTO.ProductDetail[]>([]);
const [productError, setProductError] = useState<string>();
const [status, setStatus] = useState("0");
const [fromWarehouseId, setFromWarehouseId] = useState<string>();
const [toWarehouseId, setToWarehouseId] = useState<string>();
const [notes, setNotes] = useState("");
const [isLoadingDetails, setIsLoadingDetails] = useState(true); // loading indicator for fetching stock transfer details
const { getOrgProducts, isLoading } = useGetOrgProducts();
const { getWarehouse, warehouses } = useGetWarehouse();
const { getStockTransfer, stockTransfer } = useGetStockTransfer();
const { addTransfer, isLoading: isSaving } = useAddTransfer();
// Fetch warehouses on mount
useEffect(() => {
getWarehouse();
}, []);
// Fetch stock transfer details if stockTransferId is provided
useEffect(() => {
if (stockTransferId) {
setIsLoadingDetails(true);
getStockTransfer(stockTransferId, {
onSuccess: (response) => {
const transfer = response.data;
setFromWarehouseId(transfer.fromWarehouseId);
setToWarehouseId(transfer.toWarehouseId);
setStatus(transfer.status);
setNotes(''); // Assuming you want to reset notes or can set to transfer.notes
// Fetch products into selectedProducts based on transfer.items
const products = transfer.transferItems.map(item => ({
id: item.inventoryId,
minQuantity: item.quantity,
// Include other product details as needed
}));
setSelectedProducts(products);
setIsLoadingDetails(false);
},
onFailure: () => {
setIsLoadingDetails(false);
// Handle error if needed
}
});
} else {
// Reset state if not in edit mode
setSelectedProducts([]);
setFromWarehouseId(undefined);
setToWarehouseId(undefined);
setStatus("0");
setNotes("");
}
}, [stockTransferId, getStockTransfer]);
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,
notes,
items: selectedProducts.map((product) => ({
productId: product.id,
qty: product.minQuantity || 1
}))
}, {
onSuccess: () => {
onSuccess();
}
});
};
const handleAddProduct = (product) => {
if (status !== "0") { // Allow adding products only if status is draft
return;
}
const isExisting = selectedProducts.some((p) => p.id === product.id);
if (!isExisting) {
setSelectedProducts([...selectedProducts, { ...product, minQuantity: 1 }]);
}
setSearchValue("");
setProductError("");
};
const handleRemoveProduct = (id) => {
if (status !== "0") { // Allow removing products only if status is draft
return;
}
setSelectedProducts(selectedProducts.filter((p) => p.id !== id));
};
const handleQuantityChange = (id, value) => {
if (status !== "0") { // Allow quantity change only if status is draft
return;
}
setSelectedProducts(
selectedProducts.map((p) => (p.id === id ? { ...p, minQuantity: parseInt(value, 10) || 1 } : p))
);
};
return (
<Dialog open={open} onClose={onClose} disableRestoreFocus maxWidth="lg">
<DialogTitle>Stock Transfer</DialogTitle>
<DialogContent sx={{ width: "800px" }}>
{isLoadingDetails ? ( // Show loader if fetching stock transfer details
<Box display="flex" justifyContent="center" alignItems="center" height="200px">
<CircularProgress />
</Box>
) : (
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<FormControl fullWidth>
<CustomFormLabel>
From Warehouse
</CustomFormLabel>
<CustomSelect
value={fromWarehouseId}
fullWidth
onChange={(event) => {
if (status === "0") { // Allow changes only if status is draft
setFromWarehouseId(event.target.value);
}
}}
disabled={status !== "0"} // Disable if not draft
>
{warehouses?.map((warehouse) => (
<MenuItem key={warehouse.warehouseId} value={warehouse.warehouseId}>
{warehouse.name}
</MenuItem>
))}
</CustomSelect>
</FormControl>
</Grid>
<Grid item xs={12} sm={6}>
<FormControl fullWidth>
<CustomFormLabel>
To Warehouse
</CustomFormLabel>
<CustomSelect
fullWidth
value={toWarehouseId}
onChange={(event) => {
if (status === "0") { // Allow changes only if status is draft
setToWarehouseId(event.target.value);
}
}}
disabled={status !== "0"} // Disable if not draft
>
{warehouses?.map((warehouse) => (
<MenuItem key={warehouse.warehouseId} value={warehouse.warehouseId}>
{warehouse.name}
</MenuItem>
))}
</CustomSelect>
</FormControl>
</Grid>
<Grid item xs={12}>
<FormControl fullWidth>
<CustomFormLabel>
Status
</CustomFormLabel>
<RadioGroup
row
value={status}
onChange={(e) => {
if (status === "0") { // Allow changing status only if current status is draft
setStatus(e.target.value);
}
}}
>
{Object.entries(TRANSFER_STATUS_OPTIONS).map(([key, value]) => (
(showCancelledOption || key !== 'CANCELLED') ? (
<FormControlLabel
key={key}
control={<Radio />}
label={value}
value={key}
disabled={status === '4'} // Disable if status is completed
/>
) : null
))}
</RadioGroup>
</FormControl>
</Grid>
<Grid item xs={12}>
<FormControl fullWidth>
<CustomFormLabel>
Notes
</CustomFormLabel>
<TextField
value={notes}
onChange={(e) => setNotes(e.target.value)}
fullWidth
multiline
rows={1}
placeholder="Optional notes..."
disabled={status !== "0"} // Disable if not draft
/>
</FormControl>
</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 }}
disabled={status !== "0"} // Disable if not draft
/>
</TableCell>
<TableCell>
<IconButton
color="error"
onClick={() => handleRemoveProduct(product.id)}
>
<IconTrash />
</IconButton>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
)}
</Grid>
)}
</DialogContent>
<DialogActions>
<CustomLoadingButton
loading={isSaving}
text="Save"
variant="contained"
sx={{ ml: 2 }}
onClick={handleTransfer}
disabled={isLoadingDetails || status === '4'} // Disable if loading or if status is completed
/>
<Button onClick={onClose} disabled={isSaving}>Cancel</Button>
</DialogActions>
</Dialog>
);
};
export default InventoryStockTransfer;
This change allows for greater flexibility and user experience in handling stock transfers in both creation and editing scenarios.