Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 11 additions & 13 deletions src/actions/bmdashboard/equipmentActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@ export const setErrors = payload => {
export const fetchEquipmentById = equipmentId => {
const url = `${ENDPOINTS.BM_EQUIPMENT_BY_ID(equipmentId)}`;
return async dispatch => {
axios
.get(url)
.then(res => {
dispatch(setEquipment(res.data));
})
.catch(error => {
dispatch(setErrors(error));
});
try {
const response = await axios.get(url);
dispatch(setEquipment(response.data));
return response.data;
} catch (error) {
dispatch(setErrors(error));
return { error };
}
};
};

Expand Down Expand Up @@ -119,16 +119,15 @@ export const updateEquipment = (equipmentId, updateData) => async (dispatch, get
}

if (!currentUserId) {
const errorMsg = 'User not authenticated. Please log in.';
toast.error(errorMsg);
throw new Error(errorMsg);
throw new Error('User not authenticated. Please log in.');
}

const statusUpdateData = {
condition: updateData.condition,
lastUsedBy: updateData.lastUsedBy,
lastUsedFor: updateData.lastUsedFor,
replacementRequired: updateData.replacementRequired,
replacementReason: updateData.replacementReason || '',
description: updateData.description || '',
notes: updateData.notes || '',
createdBy: currentUserId,
Expand All @@ -137,7 +136,6 @@ export const updateEquipment = (equipmentId, updateData) => async (dispatch, get
const res = await axios.put(url, statusUpdateData);

dispatch(setEquipment(res.data));
toast.success('Equipment status updated successfully!');
dispatch(fetchEquipmentById(equipmentId));

return res.data;
Expand All @@ -157,7 +155,7 @@ export const updateEquipment = (equipmentId, updateData) => async (dispatch, get
errorMessage = err.message;
}

toast.error(errorMessage);
err.message = errorMessage;
throw err;
}
};
Expand Down
5 changes: 3 additions & 2 deletions src/components/BMDashboard/Equipment/List/EquipmentsTable.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ import { BiPencil } from 'react-icons/bi';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSortDown, faSortUp } from '@fortawesome/free-solid-svg-icons';
import ReactTooltip from 'react-tooltip';
import { Link } from 'react-router-dom';
import { Link, useHistory } from 'react-router-dom';
import { fetchAllEquipments } from '~/actions/bmdashboard/equipmentActions';
import EquipmentListModal from './EquipmentListModal';
import styles from './Equipments.module.css';

function EquipmentsTable({ equipment, project }) {
const dispatch = useDispatch();
const history = useHistory();

const equipments = useSelector(state => state.bmEquipments.equipmentslist);
const [recordType, setRecordType] = useState(null);
Expand Down Expand Up @@ -181,7 +182,7 @@ function EquipmentsTable({ equipment, project }) {
<td className="materials_cell">
<button
type="button"
onClick={() => handleOpenModal(rec, 'UpdatesEdit')}
onClick={() => history.push(`/bmdashboard/tools/${rec._id}/update`)}
aria-label="Edit updates"
>
<BiPencil />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { Provider } from 'react-redux';
import { Router } from 'react-router-dom';
import { createMemoryHistory } from 'history';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import EquipmentsTable from '../EquipmentsTable';

vi.mock('~/actions/bmdashboard/equipmentActions', () => ({
fetchAllEquipments: () => ({ type: 'MOCK_FETCH_ALL_EQUIPMENTS' }),
}));

const equipmentslist = [
{
_id: 'equipment-1',
project: { _id: 'project-1', name: 'Community Kitchen' },
itemType: { name: 'Cordless Drill' },
purchaseStatus: 'Purchased',
updateRecord: [
{
_id: 'update-1',
date: '2025-03-05T12:00:00.000Z',
createdBy: { _id: 'user-1', firstName: 'Ada', lastName: 'Lovelace' },
},
],
purchaseRecord: [{ _id: 'purchase-1', date: '2025-01-10T12:00:00.000Z', status: 'Approved' }],
},
{
_id: 'equipment-2',
project: { _id: 'project-2', name: 'Garden' },
itemType: { name: 'Shovel' },
purchaseStatus: 'Rental',
updateRecord: [],
purchaseRecord: [],
},
];

const setupTable = () => {
const history = createMemoryHistory({ initialEntries: ['/bmdashboard/equipment'] });
const store = configureMockStore([thunk])({ bmEquipments: { equipmentslist } });
render(
<Provider store={store}>
<Router history={history}>
<EquipmentsTable equipment={[]} project={[]} />
</Router>
</Provider>,
);
return { history };
};

describe('EquipmentsTable', () => {
it('renders a row per equipment with detail links', () => {
setupTable();
expect(screen.getByRole('link', { name: 'Cordless Drill' }).getAttribute('href')).toBe(
'/bmdashboard/equipment/equipment-1',
);
expect(screen.getByText('Shovel')).toBeInTheDocument();
});

it('navigates to the status update form for the clicked equipment', () => {
const { history } = setupTable();
fireEvent.click(screen.getAllByLabelText('Edit updates')[1]);
expect(history.location.pathname).toBe('/bmdashboard/tools/equipment-2/update');
expect(screen.queryByText(/Edit Record/)).not.toBeInTheDocument();
});

it('opens update history from the UPDATES View button', () => {
const { history } = setupTable();
fireEvent.click(screen.getAllByRole('button', { name: 'View' })[0]);
expect(screen.getByText(/Update History/)).toBeInTheDocument();
expect(screen.getByText('Ada Lovelace')).toBeInTheDocument();
expect(history.location.pathname).toBe('/bmdashboard/equipment');
});

it('opens purchase history from the PURCHASES View button', () => {
setupTable();
fireEvent.click(screen.getAllByRole('button', { name: 'View' })[1]);
expect(screen.getByText(/Purchase History/)).toBeInTheDocument();
expect(screen.getByText('Approved')).toBeInTheDocument();
});
});
Loading
Loading