Skip to content

Commit

Permalink
Deepthi M|Gok-363|Updated the save functionality to StockTake Api and…
Browse files Browse the repository at this point in the history
… also handled refresh of quantity when stock Adjustment is done.
  • Loading branch information
deepthi-mantena committed Oct 3, 2023
1 parent 277e38e commit 21f11ca
Show file tree
Hide file tree
Showing 5 changed files with 292 additions and 21 deletions.
5 changes: 4 additions & 1 deletion src/components/BasicTableModal/BasicTableModal.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@
position: sticky;
left: 0;
z-index: 2;
}
}
.smaller-input {
width: 2px;
}
233 changes: 228 additions & 5 deletions src/components/BasicTableModal/index.jsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import React, { useState, useEffect, useRef } from 'react';
import {
DataTable,
TableContainer,
Expand All @@ -9,20 +10,136 @@ import {
TableRow,
TableBody,
ModalHeader,
Button,
} from 'carbon-components-react';
import React from 'react';
import { Edit16, Save16 } from '@carbon/icons-react';
import styles from './BasicTableModal.module.scss';
import saveEditedQuantity from '../../service/save-quantity';
import useSWR from 'swr';
import { fetcher, stockRoomURL, stockTakeURL } from '../../utils/api-utils';
import { locationCookieName } from '../../../constants';
import { useCookies } from 'react-cookie';

const TableModal = (props) => {
const { showModal, headers, rows, closeModal, stickyColumnName, title } = props;
const {
showModal,
headers,
rows,
closeModal,
stickyColumnName,
title,
onChildSave,

} = props;

const [editedRows, setEditedRows] = useState([...rows]);
const [editingRowId, setEditingRowId] = useState(null);
const [cookies] = useCookies();
const [saveClicked, setSaveClicked] = useState(false);
const [isEditing, setIsEditing] = useState(false); // Track editing mode
const editRowRef = useRef(null);
const [editedQuantity, setEditedQuantity] = useState({}); // State to track edited quantity values

const { data: stockRoom, error: stockRoomError } = useSWR(
stockRoomURL(cookies[locationCookieName]?.name.trim()),
fetcher,
);

useEffect(() => {
if (saveClicked) {
onChildSave();
setSaveClicked(false);
}
}, [saveClicked, onChildSave]);

useEffect(() => {
setEditedRows([...rows]);
}, [rows]);
useEffect(() => {
function handleClickOutside(event) {
if (editRowRef.current && !editRowRef.current.contains(event.target)) {
setIsEditing(false);
setEditingRowId(null);
}
}

document.addEventListener('mousedown', handleClickOutside);

return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, []);

const handleQuantityChange = (rowId, value) => {
// Update the edited quantity state when the quantity input changes
setEditedQuantity((prevEditedQuantity) => ({
...prevEditedQuantity,
[rowId]: value,
}));
};

const handleActualQuantityChange = (rowId, value) => {
const updatedEditedRows = editedRows.map((row) => {
if (row.id === rowId) {
return {
...row,
actualQuantity: value,
};
}
return row;
});
setEditedRows(updatedEditedRows);
};

const startEditingRow = (rowId) => {
setEditingRowId(rowId);

setIsEditing(true); // Enter editing mode
};

const handleSaveClick = async (rowId) => {
try {
const editedRow = editedRows.find((row) => row.id === rowId);

if (editedRow) {
const { productName, quantity, actualQuantity, expiration, batchNumber } = editedRow;

// Use the edited quantity state if available, otherwise use the original quantity value
const editedQuantityValue = editedQuantity[rowId] || quantity;

const response = await saveEditedQuantity(
productName,
editedQuantityValue, // Use the edited quantity value
actualQuantity,
expiration,
batchNumber,
stockRoom.results[0]?.uuid
);

if (response && response.ok) {
setSaveClicked(true);
console.log('Successfully saved:', editedRow);
} else {
console.error('Failed to save:', editedRow);
}
} else {
console.error('Row not found for rowId:', rowId);
}
} catch (error) {
console.error('An error occurred during save:', error);
}

setEditingRowId(null);
setIsEditing(false);
};

return (
<ComposedModal open={showModal} onClose={() => closeModal(false)}>
<ModalHeader>
<h4>{title}</h4>
</ModalHeader>
<TableContainer id="modal-table-container">
<DataTable rows={rows} headers={headers}>
<DataTable rows={editedRows} headers={headers}>
{({ rows, headers, getTableProps, getHeaderProps, getRowProps }) => (
<Table {...getTableProps()} useZebraStyles={true}>
<TableHead>
Expand All @@ -44,7 +161,7 @@ const TableModal = (props) => {
{rows.length === 0 ? (
<TableRow style={{ fontSize: '20px' }}>
<TableCell colSpan={headers.length}>
Currently there are no stocks available
Currently, there are no stocks available
</TableCell>
</TableRow>
) : (
Expand All @@ -57,7 +174,113 @@ const TableModal = (props) => {
cell.id.includes(stickyColumnName) ? styles.stickyColumn : ''
}`}
>
{cell.value}
{cell.id.includes('quantity') ? (
<>
{editingRowId === row.id ? (
<div
style={{
display: 'flex',
alignItems: 'center',
}}
ref={editRowRef}
>
<div style={{ paddingRight:'50px' }}>
{editedQuantity[row.id] || cell.value}
</div>
{isEditing && (
<>
<label htmlFor={`actual-quantity-${row.id}`}>Actual Qty:</label>
<input
id={`actual-quantity-${row.id}`}
type="number"
value={editedRows.find((r) => r.id === row.id)?.actualQuantity}
onChange={(e) => handleActualQuantityChange(row.id, e.target.value)}
min="0"
className={`${styles.smallerInput} ${isEditing ? styles.smallerInputActive : ''}`}

onKeyDown={(e) => {
if (e.key === '-' || e.key === 'e') {
e.preventDefault(); // Prevent typing "-" and "e"
}
}}

style={{ width: '50px' }}
/>
<Button
kind="ghost"
size="small"
onClick={() => handleSaveClick(row.id)}
renderIcon={Save16}
>
</Button>
</>
)}
</div>
) : (
<>
{cell.value}
{!isEditing ? (
<Button
style={{
float: 'right',
}}
kind="ghost"
size="small"
onClick={() => startEditingRow(row.id)}
renderIcon={Edit16}
/>
) : null}
</>
)}
</>
) : (
<>
{cell.id.includes('Actual Quantity') ? (
<>
{editingRowId === row.id ? (
<div
style={{
display: 'flex',
alignItems: 'center',
}}
ref={editRowRef}
>
<input
id={`actual-quantity-${row.id}`}
type="number"
value={editedRows.find((r) => r.id === row.id)?.actualQuantity}
onChange={(e) => handleActualQuantityChange(row.id, e.target.value)}
/>
{isEditing && (
<Button
kind="ghost"
size="small"
onClick={() => handleSaveClick(row.id)}
renderIcon={Save16}
>
Save
</Button>
)}
</div>
) : (
<>
{cell.value}
{!isEditing ? (
<Button
kind="ghost"
size="small"
onClick={() => startEditingRow(row.id)}
renderIcon={Edit16}
/>
) : null}
</>
)}
</>
) : (
cell.value
)}
</>
)}
</TableCell>
))}
</TableRow>
Expand Down
36 changes: 21 additions & 15 deletions src/inventory/inventory-landing-page.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ const InventoryLandingPage = (props) => {
setSearchText(event.target.value);
};
const handleExportToExcel = () => exportToExcel(filteredRows);
const refreshParent = () => {
props.setReloadData(true);
};

useEffect(() => {
if (itemStock?.length > 0) {
Expand All @@ -56,11 +59,11 @@ const InventoryLandingPage = (props) => {
if (itemStock?.length > 0) {
const item = itemStock.find((itemObject) => itemObject.item.name === productName);
const groupedRows = {};

item.details.forEach((detail, detailIndex) => {
const { expiration, batchNumber } = detail;
const id = `${expiration || 'No Expiration Date'}-${batchNumber || 'No Batch Number'}`;

let formattedExpirationDate = 'No Expiration Date';

if (expiration) {
Expand All @@ -82,15 +85,16 @@ const InventoryLandingPage = (props) => {
batchNumber: batchNumber || 'No Batch Number',
};
}

groupedRows[id].quantity += detail.quantity || 0;
});

const updatedRows = Object.values(groupedRows);
props.setReloadData(false);
return updatedRows;
}
};

const filteredRows = rows.filter((row) =>
searchText !== '' ? row?.productName?.toLowerCase().includes(searchText?.toLowerCase()) : row,
);
Expand All @@ -100,6 +104,7 @@ const InventoryLandingPage = (props) => {
const handleClick = (productName) => {
setSelectedProductName(productName);
setShowModal(true);
props.setReloadData(false);
};

return (
Expand All @@ -108,16 +113,16 @@ const InventoryLandingPage = (props) => {
{({ rows, headers, getTableProps, getHeaderProps, getRowProps }) => (
<>
<LoadStock setReloadData={props.setReloadData}></LoadStock>
<TableContainer style={{width:'100%'}}>
<TableToolbar style={{ backgroundColor:"white", paddingTop:"10px"}}>
<TableToolbarContent style={{ justifyContent: 'flex-start', backgroundColor:"#f4f4f4" }}>
<TableToolbarSearch value={searchText} onChange={handleSearch}/>
<TableContainer style={{ width: '100%' }}>
<TableToolbar style={{ backgroundColor: "white", paddingTop: "10px" }}>
<TableToolbarContent style={{ justifyContent: 'flex-start', backgroundColor: "#f4f4f4" }}>
<TableToolbarSearch value={searchText} onChange={handleSearch} />
</TableToolbarContent>
{rows.length > 0 && (
<Button onClick={handleExportToExcel} kind='tertiary' size='sm'>
Export To Excel
</Button>
)}
<Button onClick={handleExportToExcel} kind='tertiary' size='sm'>
Export To Excel
</Button>
)}
</TableToolbar>
<Table {...getTableProps()} useZebraStyles={true}>
<TableHead>
Expand Down Expand Up @@ -150,8 +155,8 @@ const InventoryLandingPage = (props) => {
key={cell.id}
className={`${
cell.id.includes('productName') ? styles.stickyColumn : ''
}
}`}
}
`}
>
{cell.id.includes('productName') ? (
<Link href='#' onClick={() => handleClick(cell.value)}>
Expand Down Expand Up @@ -179,6 +184,7 @@ const InventoryLandingPage = (props) => {
closeModal={() => setShowModal(false)}
stickyColumnName={'productName'}
title={`Stock Details for ${selectedProductName}`}
onChildSave={refreshParent}
/>
)}
</div>
Expand Down
Loading

0 comments on commit 21f11ca

Please sign in to comment.