feat: refactor DetailUnit component for improved state management and validation
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Modal, Input, Typography, Button, ConfigProvider, Switch } from 'antd';
|
||||
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
|
||||
import { createUnit, updateUnit, getAllUnit } from '../../../../api/master-unit';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Modal, Input, Typography, Switch, Button, ConfigProvider, Divider } from 'antd';
|
||||
import { NotifOk } from '../../../../components/Global/ToastNotif';
|
||||
import { createUnit, updateUnit } from '../../../../api/master-unit';
|
||||
import { validateRun } from '../../../../Utils/validate';
|
||||
|
||||
const { Text } = Typography;
|
||||
@@ -16,8 +16,7 @@ const DetailUnit = (props) => {
|
||||
is_active: true,
|
||||
};
|
||||
|
||||
const [FormData, setFormData] = useState(defaultData);
|
||||
const [nextUnitCode, setNextUnitCode] = useState('Auto-fill');
|
||||
const [formData, setFormData] = useState(defaultData);
|
||||
|
||||
const handleCancel = () => {
|
||||
props.setSelectedData(null);
|
||||
@@ -27,12 +26,13 @@ const DetailUnit = (props) => {
|
||||
const handleSave = async () => {
|
||||
setConfirmLoading(true);
|
||||
|
||||
// Daftar aturan validasi
|
||||
const validationRules = [
|
||||
{ field: 'unit_name', label: 'Name', required: true },
|
||||
{ field: 'unit_name', label: 'Unit Name', required: true },
|
||||
];
|
||||
|
||||
if (
|
||||
validateRun(FormData, validationRules, (errorMessages) => {
|
||||
validateRun(formData, validationRules, (errorMessages) => {
|
||||
NotifOk({
|
||||
icon: 'warning',
|
||||
title: 'Peringatan',
|
||||
@@ -45,36 +45,37 @@ const DetailUnit = (props) => {
|
||||
|
||||
try {
|
||||
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
|
||||
? await updateUnit(FormData.unit_id, payload)
|
||||
const response =
|
||||
props.actionMode === 'edit'
|
||||
? await updateUnit(formData.unit_id, payload)
|
||||
: await createUnit(payload);
|
||||
|
||||
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';
|
||||
if (response && (response.statusCode === 200 || response.statusCode === 201)) {
|
||||
const action = props.actionMode === 'edit' ? 'diubah' : 'ditambahkan';
|
||||
|
||||
NotifOk({
|
||||
icon: 'success',
|
||||
title: 'Berhasil',
|
||||
message: `Data Unit "${unitCode} - ${payload.unit_name}" berhasil ${action}.`,
|
||||
message: `Data Unit berhasil ${action}.`,
|
||||
});
|
||||
|
||||
props.setActionMode('list');
|
||||
} else {
|
||||
NotifAlert({
|
||||
NotifOk({
|
||||
icon: 'error',
|
||||
title: 'Gagal',
|
||||
message: response.message || 'Gagal menyimpan data Unit.',
|
||||
message: response?.message || 'Terjadi kesalahan saat menyimpan data.',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Save Unit Error:', error);
|
||||
NotifAlert({
|
||||
NotifOk({
|
||||
icon: 'error',
|
||||
title: 'Error',
|
||||
message: error.message || 'Terjadi kesalahan saat menyimpan data.',
|
||||
message: error.message || 'Terjadi kesalahan pada server.',
|
||||
});
|
||||
} finally {
|
||||
setConfirmLoading(false);
|
||||
@@ -84,78 +85,25 @@ const DetailUnit = (props) => {
|
||||
const handleInputChange = (e) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData({
|
||||
...FormData,
|
||||
...formData,
|
||||
[name]: value,
|
||||
});
|
||||
};
|
||||
|
||||
const handleStatusToggle = (isChecked) => {
|
||||
const handleStatusToggle = (checked) => {
|
||||
setFormData({
|
||||
...FormData,
|
||||
is_active: isChecked,
|
||||
...formData,
|
||||
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(() => {
|
||||
const token = localStorage.getItem('token');
|
||||
if (token) {
|
||||
if (props.showModal) {
|
||||
// Generate next unit code only for add mode
|
||||
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);
|
||||
if (props.selectedData) {
|
||||
setFormData(props.selectedData);
|
||||
} else {
|
||||
setFormData(defaultData);
|
||||
}
|
||||
}
|
||||
}, [props.showModal, props.actionMode]);
|
||||
}, [props.showModal, props.selectedData, props.actionMode]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
@@ -169,34 +117,27 @@ const DetailUnit = (props) => {
|
||||
open={props.showModal}
|
||||
onCancel={handleCancel}
|
||||
footer={[
|
||||
<>
|
||||
<React.Fragment key="modal-footer">
|
||||
<ConfigProvider
|
||||
theme={{
|
||||
token: { colorBgContainer: '#E9F6EF' },
|
||||
components: {
|
||||
Button: {
|
||||
defaultBg: 'white',
|
||||
defaultColor: '#23A55A',
|
||||
defaultBorderColor: '#23A55A',
|
||||
defaultHoverColor: '#23A55A',
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Button onClick={handleCancel}>Batal</Button>
|
||||
<Button onClick={handleCancel}>{props.readOnly ? 'Tutup' : 'Batal'}</Button>
|
||||
</ConfigProvider>
|
||||
<ConfigProvider
|
||||
theme={{
|
||||
token: {
|
||||
colorBgContainer: '#209652',
|
||||
},
|
||||
components: {
|
||||
Button: {
|
||||
defaultBg: '#23a55a',
|
||||
defaultColor: '#FFFFFF',
|
||||
defaultBorderColor: '#23a55a',
|
||||
defaultHoverColor: '#FFFFFF',
|
||||
defaultHoverBorderColor: '#23a55a',
|
||||
},
|
||||
},
|
||||
}}
|
||||
@@ -207,64 +148,55 @@ const DetailUnit = (props) => {
|
||||
</Button>
|
||||
)}
|
||||
</ConfigProvider>
|
||||
</>,
|
||||
</React.Fragment>,
|
||||
]}
|
||||
>
|
||||
{FormData && (
|
||||
{formData && (
|
||||
<div>
|
||||
<div>
|
||||
{/* Status Toggle */}
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<div>
|
||||
<Text strong>Status</Text>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
marginTop: '8px',
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center', marginTop: '8px' }}>
|
||||
<div style={{ marginRight: '8px' }}>
|
||||
<Switch
|
||||
disabled={props.readOnly}
|
||||
style={{
|
||||
backgroundColor:
|
||||
FormData.is_active === true
|
||||
? '#23A55A'
|
||||
: '#bfbfbf',
|
||||
backgroundColor: formData.is_active ? '#23A55A' : '#bfbfbf',
|
||||
}}
|
||||
checked={FormData.is_active === true}
|
||||
checked={formData.is_active}
|
||||
onChange={handleStatusToggle}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Text>
|
||||
{FormData.is_active === true ? 'Active' : 'Inactive'}
|
||||
</Text>
|
||||
<Text>{formData.is_active ? 'Active' : 'Inactive'}</Text>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Divider style={{ margin: '12px 0' }} />
|
||||
|
||||
{/* Unit Code - Auto Increment & Read Only */}
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<Text strong>Unit Code</Text>
|
||||
<Input
|
||||
name="unit_code"
|
||||
value={FormData.unit_code || nextUnitCode}
|
||||
placeholder={nextUnitCode}
|
||||
value={formData.unit_code || ''}
|
||||
placeholder={'Unit Code Auto Fill'}
|
||||
disabled
|
||||
style={{
|
||||
backgroundColor: '#f5f5f5',
|
||||
cursor: 'not-allowed',
|
||||
color: FormData.unit_code ? '#000000' : '#bfbfbf'
|
||||
color: formData.unit_code ? '#000000' : '#bfbfbf',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<Text strong>Name</Text>
|
||||
<Text strong>Unit Name</Text>
|
||||
<Text style={{ color: 'red' }}> *</Text>
|
||||
<Input
|
||||
name="unit_name"
|
||||
value={FormData.unit_name}
|
||||
value={formData.unit_name}
|
||||
onChange={handleInputChange}
|
||||
placeholder="Enter Unit Name"
|
||||
readOnly={props.readOnly}
|
||||
|
||||
Reference in New Issue
Block a user