feat: implement shift management with CRUD operations and local storage integration

This commit is contained in:
2025-10-13 20:26:29 +07:00
parent bfe38d5955
commit 5ed5ee26bf
3 changed files with 177 additions and 70 deletions

View File

@@ -1,10 +1,58 @@
import { useState } from 'react'; import { useState, useEffect } from 'react';
import ListShift from './component/ListShift'; import ListShift from './component/ListShift';
import DetailShift from './component/DetailShift'; import DetailShift from './component/DetailShift';
import { getAllShift } from '../../../api/master-shift';
const IndexShift = () => { const IndexShift = () => {
const [actionMode, setActionMode] = useState('list'); const [actionMode, setActionMode] = useState('list');
const [selectedData, setSelectedData] = useState(null); const [selectedData, setSelectedData] = useState(null);
const [shiftData, setShiftData] = useState([]);
const [loading, setLoading] = useState(false);
const fetchData = async () => {
setLoading(true);
try {
const localData = localStorage.getItem('shiftData');
if (localData) {
setShiftData(JSON.parse(localData));
} else {
const response = await getAllShift();
if (response.data) {
setShiftData(response.data.data);
localStorage.setItem('shiftData', JSON.stringify(response.data.data));
}
}
} catch (error) {
console.error("Error fetching shift data:", error);
}
setLoading(false);
};
useEffect(() => {
fetchData();
}, []);
const handleAddShift = (newShift) => {
const newData = { ...newShift, id: Date.now() }; // Simulate adding an ID
const updatedData = [newData, ...shiftData];
setShiftData(updatedData);
localStorage.setItem('shiftData', JSON.stringify(updatedData));
setActionMode('list');
};
const handleUpdateShift = (updatedShift) => {
const updatedData = shiftData.map(shift => shift.id === updatedShift.id ? updatedShift : shift);
setShiftData(updatedData);
localStorage.setItem('shiftData', JSON.stringify(updatedData));
setActionMode('list');
};
const handleDeleteShift = (id) => {
const updatedData = shiftData.filter(shift => shift.id !== id);
setShiftData(updatedData);
localStorage.setItem('shiftData', JSON.stringify(updatedData));
};
return ( return (
<> <>
@@ -12,6 +60,10 @@ const IndexShift = () => {
<ListShift <ListShift
setActionMode={setActionMode} setActionMode={setActionMode}
setSelectedData={setSelectedData} setSelectedData={setSelectedData}
shiftData={shiftData}
loading={loading}
onDelete={handleDeleteShift}
fetchData={fetchData}
/> />
)} )}
{(actionMode === 'add' || actionMode === 'edit' || actionMode === 'preview') && ( {(actionMode === 'add' || actionMode === 'edit' || actionMode === 'preview') && (
@@ -20,6 +72,8 @@ const IndexShift = () => {
selectedData={selectedData} selectedData={selectedData}
setActionMode={setActionMode} setActionMode={setActionMode}
setSelectedData={setSelectedData} setSelectedData={setSelectedData}
onAdd={handleAddShift}
onUpdate={handleUpdateShift}
/> />
)} )}
</> </>

View File

@@ -45,22 +45,23 @@ const DetailShift = (props) => {
}; };
try { try {
const response = FormData.id if (FormData.id) {
? await updateShift(FormData.id, payload) props.onUpdate(payload);
: await createShift(payload); } else {
props.onAdd(payload);
if (response && (response.statusCode === 200 || response.statusCode === 201)) { }
NotifOk({ NotifOk({
icon: 'success', icon: 'success',
title: 'Berhasil', title: 'Berhasil',
message: `Data Shift "${FormData.nama_shift}" berhasil ${FormData.id ? 'diubah' : 'ditambahkan'}.`, message: `Data Shift "${payload.nama_shift}" berhasil ${FormData.id ? 'diubah' : 'ditambahkan'}.`,
}); });
props.setActionMode('list');
} else {
NotifAlert({ icon: 'error', title: 'Gagal', message: response?.message || 'Terjadi kesalahan saat menyimpan data.' });
}
} catch (error) { } catch (error) {
NotifAlert({ icon: 'error', title: 'Error', message: error.message || 'Terjadi kesalahan pada server.' }); console.error('Save Shift Error:', error);
NotifAlert({
icon: 'error',
title: 'Error',
message: error.message || 'Terjadi kesalahan pada server. Coba lagi nanti.',
});
} }
setConfirmLoading(false); setConfirmLoading(false);
@@ -89,28 +90,78 @@ const DetailShift = (props) => {
open={props.actionMode !== 'list'} open={props.actionMode !== 'list'}
onCancel={handleCancel} onCancel={handleCancel}
footer={[ footer={[
<Button key="back" onClick={handleCancel}>Batal</Button>, <>
!readOnly && ( <ConfigProvider
<Button key="submit" type="primary" loading={confirmLoading} onClick={handleSave}> theme={{
token: { colorBgContainer: '#E9F6EF' },
components: {
Button: {
defaultBg: 'white',
defaultColor: '#23A55A',
defaultBorderColor: '#23A55A',
defaultHoverColor: '#23A55A',
defaultHoverBorderColor: '#23A55A',
},
},
}}
>
<Button onClick={handleCancel}>Batal</Button>
</ConfigProvider>
<ConfigProvider
theme={{
token: {
colorBgContainer: '#209652',
},
components: {
Button: {
defaultBg: '#23a55a',
defaultColor: '#FFFFFF',
defaultBorderColor: '#23a55a',
defaultHoverColor: '#FFFFFF',
defaultHoverBorderColor: '#23a55a',
},
},
}}
>
{!readOnly && (
<Button loading={confirmLoading} onClick={handleSave}>
Simpan Simpan
</Button> </Button>
), )}
</ConfigProvider>
</>,
]} ]}
> >
{FormData && ( {FormData && (
<div>
<div> <div>
<div> <div>
<Text strong>Status</Text> <Text strong>Status</Text>
<div style={{ display: 'flex', alignItems: 'center', marginTop: '8px' }}> </div>
<div
style={{
display: 'flex',
alignItems: 'center',
marginTop: '8px',
}}
>
<div style={{ marginRight: '8px' }}>
<Switch <Switch
disabled={readOnly} disabled={readOnly}
checked={FormData.status} style={{
backgroundColor:
FormData.status === true ? '#23A55A' : '#bfbfbf',
}}
checked={FormData.status === true}
onChange={handleStatusToggle} onChange={handleStatusToggle}
/> />
<Text style={{ marginLeft: '8px' }}>{FormData.status ? 'Active' : 'Inactive'}</Text> </div>
<div>
<Text>{FormData.status === true ? 'Active' : 'Inactive'}</Text>
</div> </div>
</div> </div>
<Divider /> </div>
<Divider style={{ margin: '12px 0' }} />
<div style={{ marginBottom: 12 }}> <div style={{ marginBottom: 12 }}>
<Text strong>Nama Shift</Text> <Text strong>Nama Shift</Text>
<Text style={{ color: 'red' }}> *</Text> <Text style={{ color: 'red' }}> *</Text>

View File

@@ -1,21 +1,17 @@
import React, { memo, useState, useEffect } from 'react'; import React, { memo, useState, useEffect } from 'react';
import { Button, Col, Row, Input, ConfigProvider, Card, Tag } from 'antd'; import { Button, Col, Row, Input, ConfigProvider, Card, Tag, Table, Space } from 'antd';
import { import {
PlusOutlined, PlusOutlined,
EditOutlined, EditOutlined,
DeleteOutlined, DeleteOutlined,
SearchOutlined, SearchOutlined,
EyeOutlined, EyeOutlined,
SyncOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import { NotifAlert, NotifConfirmDialog } from '../../../../components/Global/ToastNotif'; import { NotifConfirmDialog } from '../../../../components/Global/ToastNotif';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import TableList from '../../../../components/Global/TableList';
import { getAllShift, deleteShift } from '../../../../api/master-shift';
const ListShift = (props) => { const ListShift = (props) => {
const [trigerFilter, setTrigerFilter] = useState(false);
const defaultFilter = { search: '' };
const [formDataFilter, setFormDataFilter] = useState(defaultFilter);
const [searchValue, setSearchValue] = useState(''); const [searchValue, setSearchValue] = useState('');
const navigate = useNavigate(); const navigate = useNavigate();
@@ -26,19 +22,14 @@ const ListShift = (props) => {
} }
}, [navigate]); }, [navigate]);
const doFilter = () => {
setTrigerFilter((prev) => !prev);
};
const handleSearch = (value) => { const handleSearch = (value) => {
setFormDataFilter({ search: value }); // This will be handled by the parent component if server-side search is needed
doFilter(); console.log('Search value:', value);
}; };
const handleSearchClear = () => { const handleSearchClear = () => {
setSearchValue(''); setSearchValue('');
setFormDataFilter(defaultFilter); // This will be handled by the parent component if server-side search is needed
doFilter();
}; };
const showPreviewModal = (record) => { const showPreviewModal = (record) => {
@@ -61,24 +52,10 @@ const ListShift = (props) => {
icon: 'question', icon: 'question',
title: 'Konfirmasi', title: 'Konfirmasi',
message: `Apakah anda yakin ingin menghapus data shift "${record.nama_shift}"?`, message: `Apakah anda yakin ingin menghapus data shift "${record.nama_shift}"?`,
onConfirm: () => handleDelete(record.id), onConfirm: () => props.onDelete(record.id),
}); });
}; };
const handleDelete = async (id) => {
try {
const response = await deleteShift(id);
if (response.statusCode === 200) {
NotifAlert({ icon: 'success', title: 'Berhasil', message: 'Data shift berhasil dihapus' });
doFilter();
} else {
NotifAlert({ icon: 'error', title: 'Gagal', message: response.message });
}
} catch (error) {
NotifAlert({ icon: 'error', title: 'Error', message: error.message });
}
};
const columns = [ const columns = [
{ {
title: 'No', title: 'No',
@@ -114,15 +91,40 @@ const ListShift = (props) => {
align: 'center', align: 'center',
width: '15%', width: '15%',
render: (_, record) => ( render: (_, record) => (
<ConfigProvider theme={{ token: { colorBgContainer: 'transparent' } }}> <Space>
<Button icon={<EyeOutlined />} onClick={() => showPreviewModal(record)} /> <Button
<Button icon={<EditOutlined />} onClick={() => showEditModal(record)} /> icon={<EyeOutlined />}
<Button icon={<DeleteOutlined />} onClick={() => showDeleteDialog(record)} danger /> onClick={() => showPreviewModal(record)}
</ConfigProvider> style={{
color: '#1890ff',
borderColor: '#1890ff',
}}
/>
<Button
icon={<EditOutlined />}
onClick={() => showEditModal(record)}
style={{
color: '#faad14',
borderColor: '#faad14',
}}
/>
<Button
danger
icon={<DeleteOutlined />}
onClick={() => showDeleteDialog(record)}
style={{
borderColor: '#ff4d4f',
}}
/>
</Space>
), ),
}, },
]; ];
const filteredData = props.shiftData.filter(item =>
item.nama_shift.toLowerCase().includes(searchValue.toLowerCase())
);
return ( return (
<Card> <Card>
<Row justify="space-between" align="middle" gutter={[16, 16]}> <Row justify="space-between" align="middle" gutter={[16, 16]}>
@@ -166,11 +168,11 @@ const ListShift = (props) => {
</Row> </Row>
<Row style={{ marginTop: 16 }}> <Row style={{ marginTop: 16 }}>
<Col span={24}> <Col span={24}>
<TableList <Table
getData={getAllShift}
queryParams={formDataFilter}
columns={columns} columns={columns}
triger={trigerFilter} dataSource={filteredData}
loading={props.loading}
rowKey="id"
/> />
</Col> </Col>
</Row> </Row>