clean code master plant sub section and master device

This commit is contained in:
2025-10-21 20:26:05 +07:00
parent 55213480c9
commit 4bd0348a2a
24 changed files with 521 additions and 2460 deletions

View File

@@ -10,6 +10,7 @@ import {
import { NotifAlert, NotifConfirmDialog } from '../../../../components/Global/ToastNotif';
import { useNavigate } from 'react-router-dom';
import TableList from '../../../../components/Global/TableList';
import { getAllBrands } from '../../../../api/master-brand';
// Dummy data
const initialBrandDeviceData = [
@@ -145,55 +146,6 @@ const ListBrandDevice = memo(function ListBrandDevice(props) {
const navigate = useNavigate();
// Dummy data function to simulate API call - now uses state
const getAllBrandDevice = async (params) => {
// Simulate API delay
await new Promise((resolve) => setTimeout(resolve, 300));
// Extract URLSearchParams - TableList sends URLSearchParams object
const searchParam = params.get('search') || '';
const page = parseInt(params.get('page')) || 1;
const limit = parseInt(params.get('limit')) || 10;
console.log('getAllBrandDevice called with:', { searchParam, page, limit });
// Filter by search
let filteredBrandDevices = brandDeviceData;
if (searchParam) {
const searchLower = searchParam.toLowerCase();
filteredBrandDevices = brandDeviceData.filter(
(brand) =>
brand.brandName.toLowerCase().includes(searchLower) ||
brand.brandType.toLowerCase().includes(searchLower) ||
brand.manufacturer.toLowerCase().includes(searchLower) ||
brand.model.toLowerCase().includes(searchLower)
);
}
// Pagination logic
const totalData = filteredBrandDevices.length;
const totalPages = Math.ceil(totalData / limit);
const startIndex = (page - 1) * limit;
const endIndex = startIndex + limit;
const paginatedData = filteredBrandDevices.slice(startIndex, endIndex);
// Return structure that matches TableList expectation
return {
status: 200,
statusCode: 200,
data: {
data: paginatedData,
total: totalData,
paging: {
page: page,
limit: limit,
total: totalData,
page_total: totalPages,
},
},
};
};
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
@@ -333,7 +285,7 @@ const ListBrandDevice = memo(function ListBrandDevice(props) {
showPreviewModal={showPreviewModal}
showEditModal={showEditModal}
showDeleteDialog={showDeleteDialog}
getData={getAllBrandDevice}
getData={getAllBrands}
queryParams={formDataFilter}
columns={columns(showPreviewModal, showEditModal, showDeleteDialog)}
triger={trigerFilter}

View File

@@ -1,20 +1,8 @@
import React, { useEffect, useState } from 'react';
import {
Modal,
Input,
Divider,
Typography,
Switch,
Button,
ConfigProvider,
Radio,
Select,
} from 'antd';
import { Modal, Input, Divider, Typography, Switch, Button, ConfigProvider } from 'antd';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
import { createApd, getJenisPermit, updateApd } from '../../../../api/master-apd';
import { createDevice, updateDevice, getAllDevice } from '../../../../api/master-device';
import { Checkbox } from 'antd';
const CheckboxGroup = Checkbox.Group;
import { createDevice, updateDevice } from '../../../../api/master-device';
import { validateRun } from '../../../../Utils/validate';
const { Text } = Typography;
const { TextArea } = Input;
@@ -27,156 +15,60 @@ const DetailDevice = (props) => {
device_code: '',
device_name: '',
is_active: true,
device_location: 'Building A',
device_location: '',
device_description: '',
ip_address: '',
};
const [FormData, setFormData] = useState(defaultData);
const [nextDeviceCode, setNextDeviceCode] = useState('Auto-fill');
const [jenisPermit, setJenisPermit] = useState([]);
const [checkedList, setCheckedList] = useState([]);
const onChange = (list) => {
setCheckedList(list);
};
const onChangeRadio = (e) => {
setFormData({
...FormData,
type_input: e.target.value,
});
};
const getDataJenisPermit = async () => {
setCheckedList([]);
const result = await getJenisPermit();
const data = result.data ?? [];
const names = data.map((item) => ({
value: item.id_jenis_permit,
label: item.nama_jenis_permit,
}));
setJenisPermit(names);
};
const [formData, setFormData] = useState(defaultData);
const handleCancel = () => {
props.setSelectedData(null);
props.setActionMode('list');
};
const validateIPAddress = (ip) => {
const ipRegex =
/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
return ipRegex.test(ip);
};
const handleSave = async () => {
setConfirmLoading(true);
// Validasi required fields
// if (!FormData.device_code) {
// NotifOk({
// icon: 'warning',
// title: 'Peringatan',
// message: 'Kolom Device Code Tidak Boleh Kosong',
// });
// setConfirmLoading(false);
// return;
// }
// Daftar aturan validasi
const validationRules = [
{ field: 'device_name', label: 'Device Name', required: true },
{ field: 'ip_address', label: 'Ip Address', required: true, ip: true },
];
if (!FormData.device_name) {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Kolom Device Name Tidak Boleh Kosong',
});
setConfirmLoading(false);
if (
validateRun(formData, validationRules, (errorMessages) => {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: errorMessages,
});
setConfirmLoading(false);
})
)
return;
}
if (!FormData.device_location) {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Kolom Device Location Tidak Boleh Kosong',
});
setConfirmLoading(false);
return;
}
if (!FormData.ip_address) {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Kolom IP Address Tidak Boleh Kosong',
});
setConfirmLoading(false);
return;
}
// Validasi format IP
if (!validateIPAddress(FormData.ip_address)) {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Format IP Address Tidak Valid',
});
setConfirmLoading(false);
return;
}
if (props.permitDefault && checkedList.length === 0) {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Kolom Jenis Permit Tidak Boleh Kosong',
});
setConfirmLoading(false);
return;
}
// Backend validation schema doesn't include device_code
const payload = {
device_name: FormData.device_name,
is_active: FormData.is_active,
device_location: FormData.device_location,
ip_address: FormData.ip_address,
};
// For CREATE: device_description is required (cannot be empty)
// For UPDATE: device_description is optional
if (!FormData.device_id) {
// Creating - ensure description is not empty
payload.device_description = FormData.device_description || '-';
} else {
// Updating - include description as-is
payload.device_description = FormData.device_description;
}
console.log('Payload to send:', payload);
try {
let response;
if (!FormData.device_id) {
response = await createDevice(payload);
} else {
response = await updateDevice(FormData.device_id, payload);
}
const payload = {
device_name: formData.device_name,
is_active: formData.is_active,
device_location: formData.device_location,
ip_address: formData.ip_address,
};
console.log('Save Device Response:', response);
const response = !formData.device_id
? await updateDevice(formData.device_id, payload)
: await createDevice(payload);
// Check if response is successful
if (response && (response.statusCode === 200 || response.statusCode === 201)) {
// Response.data is now a single object (already extracted from array)
const deviceName = response.data?.device_name || FormData.device_name;
const deviceName = response.data?.device_name || formData.device_name;
NotifOk({
icon: 'success',
title: 'Berhasil',
message: `Data Device "${deviceName}" berhasil ${
FormData.device_id ? 'diubah' : 'ditambahkan'
formData.device_id ? 'diubah' : 'ditambahkan'
}.`,
});
@@ -203,7 +95,7 @@ const DetailDevice = (props) => {
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormData({
...FormData,
...formData,
[name]: value,
});
};
@@ -211,78 +103,22 @@ const DetailDevice = (props) => {
const handleStatusToggle = (event) => {
const isChecked = event;
setFormData({
...FormData,
...formData,
is_active: isChecked ? true : false,
});
};
const generateNextDeviceCode = async () => {
try {
const params = new URLSearchParams({ limit: 10000 });
const response = await getAllDevice(params);
if (response && response.data && response.data.data) {
const devices = response.data.data;
if (devices.length === 0) {
setNextDeviceCode('DVC001');
return;
}
// Extract numeric part from device codes and find the maximum
const deviceNumbers = devices
.map((device) => {
const match = device.device_code?.match(/dvc(\d+)/i);
return match ? parseInt(match[1], 10) : 0;
})
.filter((num) => !isNaN(num));
const maxNumber = deviceNumbers.length > 0 ? Math.max(...deviceNumbers) : 0;
const nextNumber = maxNumber + 1;
// Format with leading zeros (DVC001, DVC002, etc.)
const nextCode = `DVC${String(nextNumber).padStart(3, '0')}`;
setNextDeviceCode(nextCode);
} else {
setNextDeviceCode('DVC001');
}
} catch (error) {
console.error('Error generating next device code:', error);
setNextDeviceCode('Auto-fill');
}
};
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
if (props.showModal) {
// Only call getDataJenisPermit if permitDefault is enabled
if (props.permitDefault) {
getDataJenisPermit();
}
// Generate next device code only for add mode
if (props.actionMode === 'add' && !props.selectedData) {
generateNextDeviceCode();
}
}
if (props.selectedData != null) {
setFormData(props.selectedData);
if (props.permitDefault && props.selectedData.jenis_permit_default_arr) {
setCheckedList(props.selectedData.jenis_permit_default_arr);
}
} else {
setFormData(defaultData);
}
if (props.selectedData) {
setFormData(props.selectedData);
} else {
// navigate('/signin'); // Uncomment if useNavigate is imported
setFormData(defaultData);
}
}, [props.showModal, props.actionMode]);
}, [props.showModal, props.selectedData, props.actionMode]);
return (
<Modal
// title={`${FormData.id_apd === '' ? 'Tambah' : 'Edit'} APD`}
// title={`${formData.id_apd === '' ? 'Tambah' : 'Edit'} APD`}
title={`${
props.actionMode === 'add'
? 'Tambah'
@@ -337,7 +173,7 @@ const DetailDevice = (props) => {
</React.Fragment>,
]}
>
{FormData && (
{formData && (
<div>
<div>
<div>
@@ -355,14 +191,14 @@ const DetailDevice = (props) => {
disabled={props.readOnly}
style={{
backgroundColor:
FormData.is_active === true ? '#23A55A' : '#bfbfbf',
formData.is_active === true ? '#23A55A' : '#bfbfbf',
}}
checked={FormData.is_active === true}
checked={formData.is_active === true}
onChange={handleStatusToggle}
/>
</div>
<div>
<Text>{FormData.is_active === true ? 'Running' : 'Offline'}</Text>
<Text>{formData.is_active === true ? 'Running' : 'Offline'}</Text>
</div>
</div>
</div>
@@ -371,7 +207,7 @@ const DetailDevice = (props) => {
<Text strong>Device ID</Text>
<Input
name="device_id"
value={FormData.device_id}
value={formData.device_id}
onChange={handleInputChange}
disabled
/>
@@ -381,13 +217,13 @@ const DetailDevice = (props) => {
<Text strong>Device Code</Text>
<Input
name="device_code"
value={FormData.device_code || nextDeviceCode}
placeholder={nextDeviceCode}
value={formData.device_code}
placeholder={'Device Code Auto Fill'}
disabled
style={{
backgroundColor: '#f5f5f5',
cursor: 'not-allowed',
color: FormData.device_code ? '#000000' : '#bfbfbf'
color: formData.device_code ? '#000000' : '#bfbfbf',
}}
/>
</div>
@@ -396,7 +232,7 @@ const DetailDevice = (props) => {
<Text style={{ color: 'red' }}> *</Text>
<Input
name="device_name"
value={FormData.device_name}
value={formData.device_name}
onChange={handleInputChange}
placeholder="Enter Device Name"
readOnly={props.readOnly}
@@ -404,11 +240,10 @@ const DetailDevice = (props) => {
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Device Location</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
type="text"
name="device_location"
value={FormData.device_location}
value={formData.device_location}
onChange={handleInputChange}
placeholder="Enter Device Location"
readOnly={props.readOnly}
@@ -419,7 +254,7 @@ const DetailDevice = (props) => {
<Text style={{ color: 'red' }}> *</Text>
<Input
name="ip_address"
value={FormData.ip_address}
value={formData.ip_address}
onChange={handleInputChange}
placeholder="e.g. 192.168.1.1"
readOnly={props.readOnly}
@@ -429,26 +264,13 @@ const DetailDevice = (props) => {
<Text strong>Device Description</Text>
<TextArea
name="device_description"
value={FormData.device_description}
value={formData.device_description}
onChange={handleInputChange}
placeholder="Enter Device Description (Optional)"
readOnly={props.readOnly}
rows={4}
/>
</div>
{props.permitDefault && (
<div>
<Text strong>Jenis Permit</Text>
<Text style={{ color: 'red' }}> *</Text>
<CheckboxGroup
options={jenisPermit}
value={checkedList}
onChange={onChange}
disabled={props.readOnly}
/>
</div>
)}
</div>
)}
</Modal>

View File

@@ -1,15 +1,8 @@
import React, { useEffect, useState } from 'react';
import {
Modal,
Input,
Typography,
Switch,
Button,
ConfigProvider,
Divider,
} from 'antd';
import { Modal, Input, Typography, Switch, Button, ConfigProvider, Divider } from 'antd';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
import { createPlantSection, updatePlantSection, getAllPlantSection } from '../../../../api/master-plant-section';
import { createPlantSection, updatePlantSection } from '../../../../api/master-plant-section';
import { validateRun } from '../../../../Utils/validate';
const { Text } = Typography;
@@ -23,13 +16,12 @@ const DetailPlantSection = (props) => {
is_active: true,
};
const [FormData, setFormData] = useState(defaultData);
const [nextPlantSectionCode, setNextPlantSectionCode] = useState('Auto-fill');
const [formData, setFormData] = useState(defaultData);
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormData({
...FormData,
...formData,
[name]: value,
});
};
@@ -42,52 +34,53 @@ const DetailPlantSection = (props) => {
const handleSave = async () => {
setConfirmLoading(true);
if (!FormData.sub_section_name) {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Kolom Plant Sub Section Name Tidak Boleh Kosong',
});
setConfirmLoading(false);
// Daftar aturan validasi
const validationRules = [
{ field: 'sub_section_name', label: 'Plant Sub Section Name', required: true },
];
if (
validateRun(formData, validationRules, (errorMessages) => {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: errorMessages,
});
setConfirmLoading(false);
})
)
return;
}
try {
let response;
let payload;
const payload = {
is_active: formData.is_active,
sub_section_name: formData.sub_section_name,
};
if (props.actionMode === 'edit') {
payload = {
is_active: FormData.is_active,
sub_section_name: FormData.sub_section_name
};
response = await updatePlantSection(FormData.sub_section_id, payload);
} else {
// Backend generates the code, so we only send the name and status
payload = {
sub_section_name: FormData.sub_section_name,
is_active: FormData.is_active,
}
response = await createPlantSection(payload);
}
const response =
props.actionMode === 'edit'
? await updatePlantSection(formData.sub_section_id, payload)
: await createPlantSection(payload);
if (response && (response.statusCode === 200 || response.statusCode === 201)) {
const action = props.actionMode === 'edit' ? 'diubah' : 'ditambahkan';
NotifOk({
icon: 'success',
title: 'Berhasil',
message: `Data Plant Section berhasil ${action}.`,
});
props.setActionMode('list');
} else {
NotifAlert({
NotifOk({
icon: 'error',
title: 'Gagal',
message: response?.message || 'Terjadi kesalahan saat menyimpan data.',
});
}
} catch (error) {
NotifAlert({
NotifOk({
icon: 'error',
title: 'Error',
message: error.message || 'Terjadi kesalahan pada server.',
@@ -96,58 +89,15 @@ const DetailPlantSection = (props) => {
setConfirmLoading(false);
}
};
const handleStatusToggle = (checked) => {
setFormData({
...FormData,
...formData,
is_active: checked,
});
};
const generateNextPlantSectionCode = async () => {
try {
const params = new URLSearchParams({ limit: 10000 });
const response = await getAllPlantSection(params);
if (response && response.data && response.data.data) {
const sections = response.data.data;
if (sections.length === 0) {
setNextPlantSectionCode('SUB001');
return;
}
// Extract numeric part from plant section codes and find the maximum
const sectionNumbers = sections
.map((section) => {
const match = section.sub_section_code?.match(/sub(\d+)/i);
return match ? parseInt(match[1], 10) : 0;
})
.filter((num) => !isNaN(num));
const maxNumber = sectionNumbers.length > 0 ? Math.max(...sectionNumbers) : 0;
const nextNumber = maxNumber + 1;
// Format with leading zeros (SUB001, SUB002, etc.)
const nextCode = `SUB${String(nextNumber).padStart(3, '0')}`;
setNextPlantSectionCode(nextCode);
} else {
setNextPlantSectionCode('SUB001');
}
} catch (error) {
console.error('Error generating next plant section code:', error);
setNextPlantSectionCode('Auto-fill');
}
};
useEffect(() => {
if (props.showModal) {
// Generate next plant section code only for add mode
if (props.actionMode === 'add' && !props.selectedData) {
generateNextPlantSectionCode();
}
}
if (props.selectedData) {
setFormData(props.selectedData);
} else {
@@ -157,7 +107,7 @@ const DetailPlantSection = (props) => {
return (
<Modal
title={`${
title={`${
props.actionMode === 'add'
? 'Tambah'
: props.actionMode === 'preview'
@@ -201,7 +151,7 @@ const DetailPlantSection = (props) => {
</React.Fragment>,
]}
>
{FormData && (
{formData && (
<div>
<div>
<div>
@@ -212,16 +162,14 @@ const DetailPlantSection = (props) => {
<Switch
disabled={props.readOnly}
style={{
backgroundColor: FormData.is_active ? '#23A55A' : '#bfbfbf',
backgroundColor: formData.is_active ? '#23A55A' : '#bfbfbf',
}}
checked={FormData.is_active}
checked={formData.is_active}
onChange={handleStatusToggle}
/>
</div>
<div>
<Text>
{FormData.is_active ? 'Active' : 'Inactive'}
</Text>
<Text>{formData.is_active ? 'Active' : 'Inactive'}</Text>
</div>
</div>
</div>
@@ -232,13 +180,13 @@ const DetailPlantSection = (props) => {
<Text strong>Plant Section Code</Text>
<Input
name="sub_section_code"
value={FormData.sub_section_code || nextPlantSectionCode}
placeholder={nextPlantSectionCode}
value={formData.sub_section_code || ''}
placeholder={'Plant Sub Section Code Auto Fill'}
disabled
style={{
backgroundColor: '#f5f5f5',
cursor: 'not-allowed',
color: FormData.sub_section_code ? '#000000' : '#bfbfbf'
color: formData.sub_section_code ? '#000000' : '#bfbfbf',
}}
/>
</div>
@@ -248,7 +196,7 @@ const DetailPlantSection = (props) => {
<Text style={{ color: 'red' }}> *</Text>
<Input
name="sub_section_name"
value={FormData.sub_section_name}
value={formData.sub_section_name}
onChange={handleInputChange}
placeholder="Enter Plant Sub Section Name"
readOnly={props.readOnly}
@@ -260,4 +208,4 @@ const DetailPlantSection = (props) => {
);
};
export default DetailPlantSection;
export default DetailPlantSection;