feat: refactor DetailUnit component for improved state management and validation

This commit is contained in:
2025-10-22 10:29:21 +07:00
parent 9091392dfb
commit dca0a37774

View File

@@ -1,7 +1,7 @@
import { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Modal, Input, Typography, Button, ConfigProvider, Switch } from 'antd'; import { Modal, Input, Typography, Switch, Button, ConfigProvider, Divider } from 'antd';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif'; import { NotifOk } from '../../../../components/Global/ToastNotif';
import { createUnit, updateUnit, getAllUnit } from '../../../../api/master-unit'; import { createUnit, updateUnit } from '../../../../api/master-unit';
import { validateRun } from '../../../../Utils/validate'; import { validateRun } from '../../../../Utils/validate';
const { Text } = Typography; const { Text } = Typography;
@@ -16,8 +16,7 @@ const DetailUnit = (props) => {
is_active: true, is_active: true,
}; };
const [FormData, setFormData] = useState(defaultData); const [formData, setFormData] = useState(defaultData);
const [nextUnitCode, setNextUnitCode] = useState('Auto-fill');
const handleCancel = () => { const handleCancel = () => {
props.setSelectedData(null); props.setSelectedData(null);
@@ -27,12 +26,13 @@ const DetailUnit = (props) => {
const handleSave = async () => { const handleSave = async () => {
setConfirmLoading(true); setConfirmLoading(true);
// Daftar aturan validasi
const validationRules = [ const validationRules = [
{ field: 'unit_name', label: 'Name', required: true }, { field: 'unit_name', label: 'Unit Name', required: true },
]; ];
if ( if (
validateRun(FormData, validationRules, (errorMessages) => { validateRun(formData, validationRules, (errorMessages) => {
NotifOk({ NotifOk({
icon: 'warning', icon: 'warning',
title: 'Peringatan', title: 'Peringatan',
@@ -45,36 +45,37 @@ const DetailUnit = (props) => {
try { try {
const payload = { const payload = {
unit_name: FormData.unit_name, is_active: formData.is_active,
is_active: FormData.is_active, unit_name: formData.unit_name,
}; };
const response = FormData.unit_id const response =
? await updateUnit(FormData.unit_id, payload) props.actionMode === 'edit'
: await createUnit(payload); ? await updateUnit(formData.unit_id, payload)
: await createUnit(payload);
if (response && (response.statusCode === 200 || response.statusCode === 201)) {
const action = props.actionMode === 'edit' ? 'diubah' : 'ditambahkan';
if (response.statusCode === 200 || response.statusCode === 201) {
const unitCode = response.data?.unit_code || FormData.unit_code || 'N/A';
const action = FormData.unit_id ? 'diubah' : 'ditambahkan';
NotifOk({ NotifOk({
icon: 'success', icon: 'success',
title: 'Berhasil', title: 'Berhasil',
message: `Data Unit "${unitCode} - ${payload.unit_name}" berhasil ${action}.`, message: `Data Unit berhasil ${action}.`,
}); });
props.setActionMode('list'); props.setActionMode('list');
} else { } else {
NotifAlert({ NotifOk({
icon: 'error', icon: 'error',
title: 'Gagal', title: 'Gagal',
message: response.message || 'Gagal menyimpan data Unit.', message: response?.message || 'Terjadi kesalahan saat menyimpan data.',
}); });
} }
} catch (error) { } catch (error) {
console.error('Save Unit Error:', error); NotifOk({
NotifAlert({
icon: 'error', icon: 'error',
title: 'Error', title: 'Error',
message: error.message || 'Terjadi kesalahan saat menyimpan data.', message: error.message || 'Terjadi kesalahan pada server.',
}); });
} finally { } finally {
setConfirmLoading(false); setConfirmLoading(false);
@@ -84,78 +85,25 @@ const DetailUnit = (props) => {
const handleInputChange = (e) => { const handleInputChange = (e) => {
const { name, value } = e.target; const { name, value } = e.target;
setFormData({ setFormData({
...FormData, ...formData,
[name]: value, [name]: value,
}); });
}; };
const handleStatusToggle = (isChecked) => { const handleStatusToggle = (checked) => {
setFormData({ setFormData({
...FormData, ...formData,
is_active: isChecked, is_active: checked,
}); });
}; };
const generateNextUnitCode = async () => {
try {
const params = new URLSearchParams({ limit: 10000 });
const response = await getAllUnit(params);
if (response && response.data && response.data.data) {
const units = response.data.data;
if (units.length === 0) {
setNextUnitCode('UNT001');
return;
}
// Extract numeric part from unit codes and find the maximum
const unitNumbers = units
.map((unit) => {
const match = unit.unit_code?.match(/unt(\d+)/i);
return match ? parseInt(match[1], 10) : 0;
})
.filter((num) => !isNaN(num));
const maxNumber = unitNumbers.length > 0 ? Math.max(...unitNumbers) : 0;
const nextNumber = maxNumber + 1;
// Format with leading zeros (UNT001, UNT002, etc.)
const nextCode = `UNT${String(nextNumber).padStart(3, '0')}`;
setNextUnitCode(nextCode);
} else {
setNextUnitCode('UNT001');
}
} catch (error) {
console.error('Error generating next unit code:', error);
setNextUnitCode('Auto-fill');
}
};
useEffect(() => { useEffect(() => {
const token = localStorage.getItem('token'); if (props.selectedData) {
if (token) { setFormData(props.selectedData);
if (props.showModal) { } else {
// Generate next unit code only for add mode setFormData(defaultData);
if (props.actionMode === 'add' && !props.selectedData) {
generateNextUnitCode();
}
}
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, props.actionMode]); }, [props.showModal, props.selectedData, props.actionMode]);
return ( return (
<Modal <Modal
@@ -169,34 +117,27 @@ const DetailUnit = (props) => {
open={props.showModal} open={props.showModal}
onCancel={handleCancel} onCancel={handleCancel}
footer={[ footer={[
<> <React.Fragment key="modal-footer">
<ConfigProvider <ConfigProvider
theme={{ theme={{
token: { colorBgContainer: '#E9F6EF' },
components: { components: {
Button: { Button: {
defaultBg: 'white', defaultBg: 'white',
defaultColor: '#23A55A', defaultColor: '#23A55A',
defaultBorderColor: '#23A55A', defaultBorderColor: '#23A55A',
defaultHoverColor: '#23A55A',
}, },
}, },
}} }}
> >
<Button onClick={handleCancel}>Batal</Button> <Button onClick={handleCancel}>{props.readOnly ? 'Tutup' : 'Batal'}</Button>
</ConfigProvider> </ConfigProvider>
<ConfigProvider <ConfigProvider
theme={{ theme={{
token: {
colorBgContainer: '#209652',
},
components: { components: {
Button: { Button: {
defaultBg: '#23a55a', defaultBg: '#23a55a',
defaultColor: '#FFFFFF', defaultColor: '#FFFFFF',
defaultBorderColor: '#23a55a', defaultBorderColor: '#23a55a',
defaultHoverColor: '#FFFFFF',
defaultHoverBorderColor: '#23a55a',
}, },
}, },
}} }}
@@ -207,64 +148,55 @@ const DetailUnit = (props) => {
</Button> </Button>
)} )}
</ConfigProvider> </ConfigProvider>
</>, </React.Fragment>,
]} ]}
> >
{FormData && ( {formData && (
<div> <div>
{/* Status Toggle */} <div>
<div style={{ marginBottom: 12 }}>
<div> <div>
<Text strong>Status</Text> <Text strong>Status</Text>
</div> </div>
<div <div style={{ display: 'flex', alignItems: 'center', marginTop: '8px' }}>
style={{
display: 'flex',
alignItems: 'center',
marginTop: '8px',
}}
>
<div style={{ marginRight: '8px' }}> <div style={{ marginRight: '8px' }}>
<Switch <Switch
disabled={props.readOnly} disabled={props.readOnly}
style={{ style={{
backgroundColor: backgroundColor: formData.is_active ? '#23A55A' : '#bfbfbf',
FormData.is_active === true
? '#23A55A'
: '#bfbfbf',
}} }}
checked={FormData.is_active === true} checked={formData.is_active}
onChange={handleStatusToggle} onChange={handleStatusToggle}
/> />
</div> </div>
<div> <div>
<Text> <Text>{formData.is_active ? 'Active' : 'Inactive'}</Text>
{FormData.is_active === true ? 'Active' : 'Inactive'}
</Text>
</div> </div>
</div> </div>
</div> </div>
<Divider style={{ margin: '12px 0' }} />
{/* Unit Code - Auto Increment & Read Only */} {/* Unit Code - Auto Increment & Read Only */}
<div style={{ marginBottom: 12 }}> <div style={{ marginBottom: 12 }}>
<Text strong>Unit Code</Text> <Text strong>Unit Code</Text>
<Input <Input
name="unit_code" name="unit_code"
value={FormData.unit_code || nextUnitCode} value={formData.unit_code || ''}
placeholder={nextUnitCode} placeholder={'Unit Code Auto Fill'}
disabled disabled
style={{ style={{
backgroundColor: '#f5f5f5', backgroundColor: '#f5f5f5',
cursor: 'not-allowed', cursor: 'not-allowed',
color: FormData.unit_code ? '#000000' : '#bfbfbf' color: formData.unit_code ? '#000000' : '#bfbfbf',
}} }}
/> />
</div> </div>
<div style={{ marginBottom: 12 }}> <div style={{ marginBottom: 12 }}>
<Text strong>Name</Text> <Text strong>Unit Name</Text>
<Text style={{ color: 'red' }}> *</Text> <Text style={{ color: 'red' }}> *</Text>
<Input <Input
name="unit_name" name="unit_name"
value={FormData.unit_name} value={formData.unit_name}
onChange={handleInputChange} onChange={handleInputChange}
placeholder="Enter Unit Name" placeholder="Enter Unit Name"
readOnly={props.readOnly} readOnly={props.readOnly}