feat: add unit management functionality with list, detail, and API integration

This commit is contained in:
2025-10-17 15:48:14 +07:00
parent 2df7c953c7
commit 6be90b6ea9
7 changed files with 858 additions and 8 deletions

View File

@@ -0,0 +1,76 @@
import React, { memo, useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import ListUnit from './component/ListUnit';
import DetailUnit from './component/DetailUnit';
import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb';
import { Typography } from 'antd';
const { Text } = Typography;
const IndexUnit = memo(function IndexUnit() {
const navigate = useNavigate();
const { setBreadcrumbItems } = useBreadcrumb();
const [actionMode, setActionMode] = useState('list');
const [selectedData, setSelectedData] = useState(null);
const [readOnly, setReadOnly] = useState(false);
const [showModal, setShowmodal] = useState(false);
const setMode = (param) => {
setActionMode(param);
switch (param) {
case 'add':
setReadOnly(false);
setShowmodal(true);
break;
case 'edit':
setReadOnly(false);
setShowmodal(true);
break;
case 'preview':
setReadOnly(true);
setShowmodal(true);
break;
default:
setShowmodal(false);
break;
}
};
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
setBreadcrumbItems([
{ title: <Text strong style={{ fontSize: '14px' }}> Master</Text> },
{ title: <Text strong style={{ fontSize: '14px' }}>Unit</Text> }
]);
} else {
navigate('/signin');
}
}, []);
return (
<React.Fragment>
<ListUnit
actionMode={actionMode}
setActionMode={setMode}
selectedData={selectedData}
setSelectedData={setSelectedData}
readOnly={readOnly}
/>
<DetailUnit
setActionMode={setMode}
selectedData={selectedData}
setSelectedData={setSelectedData}
readOnly={readOnly}
showModal={showModal}
actionMode={actionMode}
/>
</React.Fragment>
);
});
export default IndexUnit;

View File

@@ -0,0 +1,253 @@
import { useEffect, useState } from 'react';
import { Modal, Input, Typography, Button, ConfigProvider, Switch } from 'antd';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
import { createUnit, updateUnit } from '../../../../api/master-unit';
const { Text } = Typography;
const DetailUnit = (props) => {
const [confirmLoading, setConfirmLoading] = useState(false);
const defaultData = {
unit_id: '',
unit_code: '',
unit_name: '',
is_active: true,
};
const [FormData, setFormData] = useState(defaultData);
const handleCancel = () => {
props.setSelectedData(null);
props.setActionMode('list');
};
const handleSave = async () => {
setConfirmLoading(true);
// Validasi required fields
if (!FormData.unit_name || FormData.unit_name.trim() === '') {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Kolom Name Tidak Boleh Kosong',
});
setConfirmLoading(false);
return;
}
try {
if (FormData.unit_id) {
// Update existing unit
const payload = {
name: FormData.unit_name,
is_active: FormData.is_active,
};
const response = await updateUnit(FormData.unit_id, payload);
console.log('updateUnit response:', response);
if (response.statusCode === 200) {
// Get updated data to show unit_code in notification
const unitCode = response.data?.unit_code || FormData.unit_code;
NotifOk({
icon: 'success',
title: 'Berhasil',
message: `Data Unit "${unitCode} - ${FormData.unit_name}" berhasil diubah.`,
});
props.setActionMode('list');
} else {
NotifAlert({
icon: 'error',
title: 'Gagal',
message: response.message || 'Gagal mengubah data Unit.',
});
}
} else {
// Create new unit
const payload = {
name: FormData.unit_name,
is_active: FormData.is_active,
};
const response = await createUnit(payload);
console.log('createUnit response:', response);
if (response.statusCode === 200 || response.statusCode === 201) {
// Get unit_code from response
const unitCode = response.data?.unit_code || 'N/A';
NotifOk({
icon: 'success',
title: 'Berhasil',
message: `Data Unit "${unitCode} - ${FormData.unit_name}" berhasil ditambahkan.`,
});
props.setActionMode('list');
} else {
NotifAlert({
icon: 'error',
title: 'Gagal',
message: response.message || 'Gagal menambahkan data Unit.',
});
}
}
} catch (error) {
console.error('Save Unit Error:', error);
NotifAlert({
icon: 'error',
title: 'Error',
message: error.message || 'Terjadi kesalahan saat menyimpan data.',
});
}
setConfirmLoading(false);
};
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormData({
...FormData,
[name]: value,
});
};
const handleStatusToggle = (isChecked) => {
setFormData({
...FormData,
is_active: isChecked,
});
};
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
if (props.selectedData != null) {
// Only set fields that are in defaultData
const filteredData = {
unit_id: props.selectedData.unit_id || '',
unit_code: props.selectedData.unit_code || '',
unit_name: props.selectedData.unit_name || '',
is_active: props.selectedData.is_active ?? true,
};
setFormData(filteredData);
} else {
setFormData(defaultData);
}
}
}, [props.showModal]);
return (
<Modal
title={`${
props.actionMode === 'add'
? 'Tambah'
: props.actionMode === 'preview'
? 'Preview'
: 'Edit'
} Unit`}
open={props.showModal}
onCancel={handleCancel}
footer={[
<>
<ConfigProvider
theme={{
token: { colorBgContainer: '#E9F6EF' },
components: {
Button: {
defaultBg: 'white',
defaultColor: '#23A55A',
defaultBorderColor: '#23A55A',
defaultHoverColor: '#23A55A',
},
},
}}
>
<Button onClick={handleCancel}>Batal</Button>
</ConfigProvider>
<ConfigProvider
theme={{
token: {
colorBgContainer: '#209652',
},
components: {
Button: {
defaultBg: '#23a55a',
defaultColor: '#FFFFFF',
defaultBorderColor: '#23a55a',
defaultHoverColor: '#FFFFFF',
defaultHoverBorderColor: '#23a55a',
},
},
}}
>
{!props.readOnly && (
<Button loading={confirmLoading} onClick={handleSave}>
Simpan
</Button>
)}
</ConfigProvider>
</>,
]}
>
{FormData && (
<div>
{/* Status Toggle */}
<div style={{ marginBottom: 12 }}>
<div>
<Text strong>Status</Text>
</div>
<div
style={{
display: 'flex',
alignItems: 'center',
marginTop: '8px',
}}
>
<div style={{ marginRight: '8px' }}>
<Switch
disabled={props.readOnly}
style={{
backgroundColor:
FormData.is_active === true
? '#23A55A'
: '#bfbfbf',
}}
checked={FormData.is_active === true}
onChange={handleStatusToggle}
/>
</div>
<div>
<Text>
{FormData.is_active === true ? 'Active' : 'Inactive'}
</Text>
</div>
</div>
</div>
{/* Unit Code - Display only for edit/preview */}
{FormData.unit_code && (
<div style={{ marginBottom: 12 }}>
<Text strong>Unit Code</Text>
<Input
name="unit_code"
value={FormData.unit_code}
disabled
/>
</div>
)}
<div style={{ marginBottom: 12 }}>
<Text strong>Name</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="unit_name"
value={FormData.unit_name}
onChange={handleInputChange}
placeholder="Enter Unit Name"
readOnly={props.readOnly}
/>
</div>
</div>
)}
</Modal>
);
};
export default DetailUnit;

View File

@@ -0,0 +1,276 @@
import React, { memo, useState, useEffect } from 'react';
import { Space, Tag, ConfigProvider, Button, Row, Col, Card, Input } from 'antd';
import {
PlusOutlined,
EditOutlined,
DeleteOutlined,
EyeOutlined,
SearchOutlined,
} from '@ant-design/icons';
import { NotifAlert, NotifConfirmDialog } from '../../../../components/Global/ToastNotif';
import { useNavigate } from 'react-router-dom';
import TableList from '../../../../components/Global/TableList';
import { getAllUnit, deleteUnit } from '../../../../api/master-unit';
const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [
{
title: 'No',
key: 'no',
width: '5%',
align: 'center',
render: (_, __, index) => index + 1,
},
{
title: 'Unit Code',
dataIndex: 'unit_code',
key: 'unit_code',
width: '20%',
},
{
title: 'Name',
dataIndex: 'unit_name',
key: 'unit_name',
width: '20%',
},
{
title: 'Status',
dataIndex: 'is_active',
key: 'is_active',
width: '10%',
align: 'center',
render: (_, { is_active }) => {
const color = is_active ? 'green' : 'red';
const text = is_active ? 'Active' : 'Inactive';
return (
<Tag color={color} key={'status'}>
{text}
</Tag>
);
},
},
{
title: 'Aksi',
key: 'aksi',
align: 'center',
width: '20%',
render: (_, record) => (
<Space>
<Button
type="text"
icon={<EyeOutlined />}
onClick={() => showPreviewModal(record)}
style={{
color: '#1890ff',
borderColor: '#1890ff',
}}
/>
<Button
type="text"
icon={<EditOutlined />}
onClick={() => showEditModal(record)}
style={{
color: '#faad14',
borderColor: '#faad14',
}}
/>
<Button
danger
type="text"
icon={<DeleteOutlined />}
onClick={() => showDeleteDialog(record)}
style={{
borderColor: '#ff4d4f',
}}
/>
</Space>
),
},
];
const ListUnit = memo(function ListUnit(props) {
const [trigerFilter, setTrigerFilter] = useState(false);
const defaultFilter = {
criteria: '',
};
const [formDataFilter, setFormDataFilter] = useState(defaultFilter);
const [searchValue, setSearchValue] = useState('');
const navigate = useNavigate();
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
if (props.actionMode == 'list') {
doFilter();
}
} else {
navigate('/signin');
}
}, [props.actionMode]);
const doFilter = () => {
setTrigerFilter((prev) => !prev);
};
const handleSearch = () => {
setFormDataFilter((prev) => ({ ...prev, criteria: searchValue }));
doFilter();
};
const handleSearchClear = () => {
setSearchValue('');
setFormDataFilter((prev) => ({ ...prev, criteria: '' }));
doFilter();
};
const showPreviewModal = (param) => {
props.setSelectedData(param);
props.setActionMode('preview');
};
const showEditModal = (param = null) => {
props.setSelectedData(param);
props.setActionMode('edit');
};
const showAddModal = (param = null) => {
props.setSelectedData(param);
props.setActionMode('add');
};
const showDeleteDialog = (param) => {
NotifConfirmDialog({
icon: 'question',
title: 'Konfirmasi',
message: `Apakah anda yakin hapus data "${param.unit_code} - ${param.unit_name}" ?`,
onConfirm: () => handleDelete(param),
onCancel: () => props.setSelectedData(null),
});
};
const handleDelete = async (param) => {
try {
const response = await deleteUnit(param.unit_id);
console.log('deleteUnit response:', response);
if (response.statusCode === 200) {
NotifAlert({
icon: 'success',
title: 'Berhasil',
message: `Data Unit "${param.unit_code} - ${param.unit_name}" berhasil dihapus.`,
});
// Refresh table
doFilter();
} else {
NotifAlert({
icon: 'error',
title: 'Gagal',
message: response.message || 'Gagal menghapus data Unit.',
});
}
} catch (error) {
console.error('Delete Unit Error:', error);
NotifAlert({
icon: 'error',
title: 'Error',
message: error.message || 'Terjadi kesalahan saat menghapus data.',
});
}
};
// Function untuk dipanggil dari DetailUnit setelah create/update
const refreshData = () => {
doFilter();
};
// Pass refresh function to props
if (props.setRefreshData) {
props.setRefreshData(refreshData);
}
return (
<React.Fragment>
<Card>
<Row>
<Col xs={24}>
<Row justify="space-between" align="middle" gutter={[8, 8]}>
<Col xs={24} sm={24} md={12} lg={12}>
<Input.Search
placeholder="Search unit by code or name..."
value={searchValue}
onChange={(e) => {
const value = e.target.value;
setSearchValue(value);
// Auto search when clearing by backspace/delete
if (value === '') {
handleSearchClear();
}
}}
onSearch={handleSearch}
allowClear
onClear={handleSearchClear}
enterButton={
<Button
type="primary"
icon={<SearchOutlined />}
style={{
backgroundColor: '#23A55A',
borderColor: '#23A55A',
}}
>
Search
</Button>
}
size="large"
/>
</Col>
<Col>
<Space wrap size="small">
<ConfigProvider
theme={{
token: { colorBgContainer: '#E9F6EF' },
components: {
Button: {
defaultBg: 'white',
defaultColor: '#23A55A',
defaultBorderColor: '#23A55A',
defaultHoverColor: '#23A55A',
defaultHoverBorderColor: '#23A55A',
},
},
}}
>
<Button
icon={<PlusOutlined />}
onClick={() => showAddModal()}
size="large"
>
Tambah Data
</Button>
</ConfigProvider>
</Space>
</Col>
</Row>
</Col>
<Col xs={24} sm={24} md={24} lg={24} xl={24} style={{ marginTop: '16px' }}>
<TableList
mobile
cardColor={'#42AAFF'}
header={'unit_name'}
showPreviewModal={showPreviewModal}
showEditModal={showEditModal}
showDeleteDialog={showDeleteDialog}
getData={getAllUnit}
queryParams={formDataFilter}
columns={columns(showPreviewModal, showEditModal, showDeleteDialog)}
triger={trigerFilter}
/>
</Col>
</Row>
</Card>
</React.Fragment>
);
});
export default ListUnit;