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

@@ -1,461 +0,0 @@
// import React, { useState } from 'react';
// import {
// Flex,
// Input,
// InputNumber,
// Form,
// Button,
// Card,
// Space,
// Upload,
// Divider,
// Tooltip,
// message,
// Select,
// } from 'antd';
// import {
// UploadOutlined,
// UserOutlined,
// IdcardOutlined,
// PhoneOutlined,
// LockOutlined,
// InfoCircleOutlined,
// MailOutlined,
// } from '@ant-design/icons';
// const { Item } = Form;
// const { Option } = Select;
// import sypiu_ggcp from 'assets/sypiu_ggcp.jpg';
// import { useNavigate } from 'react-router-dom';
// import { register, uploadFile, checkUsername } from '../../api/auth';
// import { NotifAlert } from '../../components/Global/ToastNotif';
// const Registration = () => {
// const [form] = Form.useForm();
// const navigate = useNavigate();
// const [loading, setLoading] = useState(false);
// const [fileListKontrak, setFileListKontrak] = useState([]);
// const [fileListHsse, setFileListHsse] = useState([]);
// const [fileListIcon, setFileListIcon] = useState([]);
// // Daftar jenis vendor
// const vendorTypes = [
// { vendor_type: 1, vendor_type_name: 'One-Time' },
// { vendor_type: 2, vendor_type_name: 'Rutin' },
// ];
// const onFinish = async (values) => {
// setLoading(true);
// try {
// if (!fileListKontrak.length || !fileListHsse.length) {
// message.error('Harap unggah Lampiran Kontrak Kerja dan HSSE Plan!');
// setLoading(false);
// return;
// }
// const formData = new FormData();
// formData.append('path_kontrak', fileListKontrak[0].originFileObj);
// formData.append('path_hse_plant', fileListHsse[0].originFileObj);
// if (fileListIcon.length) {
// formData.append('path_icon', fileListIcon[0].originFileObj);
// }
// const uploadResponse = await uploadFile(formData);
// if (!uploadResponse.data?.pathKontrak && !uploadResponse.data?.pathHsePlant) {
// message.error(uploadResponse.message || 'Gagal mengunggah file.');
// setLoading(false);
// return;
// }
// const params = new URLSearchParams({ username: values.username });
// const usernameCheck = await checkUsername(params);
// if (usernameCheck.data.data && usernameCheck.data.data.available === false) {
// NotifAlert({
// icon: 'error',
// title: 'Gagal',
// message: usernameCheck.data.message || 'Terjadi kesalahan, silakan coba lagi',
// });
// setLoading(false);
// return;
// }
// const registerData = {
// nama_perusahaan: values.namaPerusahaan,
// no_kontak_wo: values.noKontakWo,
// path_kontrak: uploadResponse.data.pathKontrak || '',
// durasi: values.durasiPekerjaan,
// nilai_csms: values.nilaiCsms.toString(),
// vendor_type: values.jenisVendor, // Tambahkan jenis vendor ke registerData
// path_hse_plant: uploadResponse.data.pathHsePlant || '',
// nama_leader: values.penanggungJawab,
// no_identitas: values.noIdentitas,
// no_hp: values.noHandphone,
// email_register: values.username,
// password_register: values.password,
// };
// const response = await register(registerData);
// if (response.data?.id_register) {
// message.success('Data berhasil disimpan!');
// try {
// form.resetFields();
// setFileListKontrak([]);
// setFileListHsse([]);
// setFileListIcon([]);
// navigate('/registration-submitted');
// } catch (postSuccessError) {
// message.warning(
// 'Registrasi berhasil, tetapi ada masalah setelahnya. Silakan ke halaman login secara manual.'
// );
// }
// } else {
// message.error(response.message || 'Pendaftaran gagal, silakan coba lagi.');
// }
// } catch (error) {
// console.error('Error saat registrasi:', error);
// NotifAlert({
// icon: 'error',
// title: 'Gagal',
// message: error.message || 'Terjadi kesalahan, silakan coba lagi',
// });
// } finally {
// setLoading(false);
// }
// };
// const onCancel = () => {
// form.resetFields();
// setFileListKontrak([]);
// setFileListHsse([]);
// setFileListIcon([]);
// navigate('/signin');
// };
// const handleChangeKontrak = ({ fileList }) => {
// setFileListKontrak(fileList);
// };
// const handleChangeHsse = ({ fileList }) => {
// setFileListHsse(fileList);
// };
// const handleChangeIcon = ({ fileList }) => {
// setFileListIcon(fileList);
// };
// const beforeUpload = (file, fieldname) => {
// const isValidType = [
// 'image/jpeg',
// 'image/jpg',
// 'image/png',
// fieldname !== 'path_icon' ? 'application/pdf' : null,
// ]
// .filter(Boolean)
// .includes(file.type);
// const isNotEmpty = file.size > 0;
// const isSizeValid = file.size / 1024 / 1024 < 10;
// if (!isValidType) {
// message.error(
// `Hanya file ${
// fieldname === 'path_icon' ? 'JPG/PNG' : 'PDF/JPG/PNG'
// } yang diperbolehkan!`
// );
// return false;
// }
// if (!isNotEmpty) {
// message.error('File tidak boleh kosong!');
// return false;
// }
// if (!isSizeValid) {
// message.error('Ukuran file maksimal 10MB!');
// return false;
// }
// return true;
// };
// return (
// <Flex
// align="center"
// justify="center"
// style={{
// minHeight: '100vh',
// backgroundImage: `url(${sypiu_ggcp})`,
// backgroundSize: 'cover',
// backgroundPosition: 'center',
// padding: '20px',
// }}
// >
// <Card
// style={{
// width: '100%',
// maxWidth: 800,
// background: 'rgba(255, 255, 255, 0.9)',
// backdropFilter: 'blur(10px)',
// borderRadius: '12px',
// boxShadow: '0 8px 16px rgba(0, 0, 0, 0.1)',
// padding: '24px',
// }}
// title={
// <Flex align="center" justify="space-between">
// <h2 style={{ margin: 0, color: '#1a3c34' }}>Formulir Pendaftaran</h2>
// <Button
// type="link"
// icon={<InfoCircleOutlined />}
// onClick={() => navigate('/signin')}
// >
// Kembali
// </Button>
// </Flex>
// }
// >
// <Form
// form={form}
// onFinish={onFinish}
// layout="horizontal"
// labelCol={{ span: 8 }}
// wrapperCol={{ span: 16 }}
// labelAlign="left"
// style={{ maxWidth: 800 }}
// >
// {/* Informasi Perusahaan */}
// <Divider
// orientation="left"
// orientationMargin={0}
// style={{
// color: '#23A55A',
// fontWeight: 'bold',
// marginLeft: 0,
// paddingLeft: 0,
// }}
// >
// Informasi Perusahaan
// </Divider>
// <Item
// label="Nama Perusahaan"
// name="namaPerusahaan"
// rules={[{ required: true, message: 'Masukkan Nama Perusahaan!' }]}
// >
// <Input
// prefix={<UserOutlined />}
// placeholder="Masukkan Nama Perusahaan"
// size="large"
// />
// </Item>
// <Item
// label="Durasi Pekerjaan (Hari)"
// name="durasiPekerjaan"
// rules={[{ required: true, message: 'Masukkan Durasi Pekerjaan!' }]}
// >
// <InputNumber
// min={1}
// style={{ width: '100%' }}
// placeholder="Masukkan Durasi Pekerjaan"
// size="large"
// />
// </Item>
// <Item
// label="No Kontrak Kerja / Agreement"
// name="noKontakWo"
// rules={[
// { required: true, message: 'Masukkan No Kontrak Kerja / Agreement!' },
// ]}
// >
// <Input
// style={{
// width: '100%',
// }}
// placeholder="Masukkan No Kontrak Kerja / Agreement"
// size="large"
// />
// </Item>
// <Item
// label="Lampiran Kontrak Kerja"
// name="lampiranKontrak"
// rules={[{ required: true, message: 'Unggah Lampiran Kontrak Kerja!' }]}
// >
// <Upload
// beforeUpload={(file) => beforeUpload(file, 'path_kontrak')}
// fileList={fileListKontrak}
// onChange={handleChangeKontrak}
// maxCount={1}
// >
// <Button icon={<UploadOutlined />} size="large">
// Unggah PDF/JPG
// </Button>
// </Upload>
// </Item>
// <Item
// label="HSSE Plan"
// name="hssePlan"
// rules={[{ required: true, message: 'Unggah HSSE Plan!' }]}
// >
// <Upload
// beforeUpload={(file) => beforeUpload(file, 'path_hse_plant')}
// fileList={fileListHsse}
// onChange={handleChangeHsse}
// maxCount={1}
// >
// <Button icon={<UploadOutlined />} size="large">
// Unggah PDF/JPG
// </Button>
// </Upload>
// </Item>
// <Item
// label="Nilai CSMS"
// name="nilaiCsms"
// rules={[{ required: true, message: 'Masukkan Nilai CSMS!' }]}
// >
// <InputNumber
// min={0}
// max={100}
// style={{ width: '100%' }}
// placeholder="Masukkan Nilai CSMS"
// size="large"
// />
// </Item>
// <Item
// label="Jenis Vendor"
// name="jenisVendor"
// rules={[{ required: true, message: 'Pilih Jenis Vendor!' }]}
// >
// <Select
// placeholder="Pilih Jenis Vendor"
// size="large"
// style={{ width: '100%' }}
// >
// {vendorTypes.map((vendor) => (
// <Option key={vendor.vendor_type} value={vendor.vendor_type}>
// {vendor.vendor_type_name}
// </Option>
// ))}
// </Select>
// </Item>
// {/* Informasi Penanggung Jawab */}
// <Divider
// orientation="left"
// orientationMargin={0}
// style={{
// color: '#23A55A',
// fontWeight: 'bold',
// marginLeft: 0,
// paddingLeft: 0,
// }}
// >
// Informasi Penanggung Jawab
// </Divider>
// <Item
// label="Nama Penanggung Jawab"
// name="penanggungJawab"
// rules={[{ required: true, message: 'Masukkan Nama Penanggung Jawab!' }]}
// >
// <Input
// prefix={<UserOutlined />}
// placeholder="Masukkan Nama Penanggung Jawab"
// size="large"
// />
// </Item>
// <Item
// label="No Handphone"
// name="noHandphone"
// rules={[
// { required: true, message: 'Masukkan No Handphone!' },
// {
// pattern: /^(\+62|0)[0-9]{9,12}$/,
// message:
// 'Format nomor telepon tidak valid! (Contoh: +62.... atau 0....)',
// },
// ]}
// >
// <Input
// prefix={<PhoneOutlined />}
// placeholder="Masukkan No Handphone (+62)"
// size="large"
// />
// </Item>
// <Item
// label="No Identitas"
// name="noIdentitas"
// rules={[{ required: true, message: 'Masukkan No Identitas!' }]}
// >
// <Input
// prefix={<IdcardOutlined />}
// placeholder="Masukkan No Identitas"
// size="large"
// />
// </Item>
// {/* Akun Pengguna */}
// <Divider
// orientation="left"
// orientationMargin={0}
// style={{
// color: '#23A55A',
// fontWeight: 'bold',
// marginLeft: 0,
// paddingLeft: 0,
// }}
// >
// Akun Pengguna (digunakan sebagai user login SYPIU)
// </Divider>
// <Item
// label="Email"
// name="username"
// rules={[
// { required: true, message: 'Masukkan Email!' },
// { type: 'email', message: 'Format email tidak valid!' },
// ]}
// >
// <Input
// prefix={<MailOutlined />}
// placeholder="Masukkan Email"
// size="large"
// />
// </Item>
// <Item
// label="Password"
// name="password"
// rules={[
// { required: true, message: 'Masukkan Password!' },
// { min: 6, message: 'Password minimal 6 karakter!' },
// ]}
// >
// <Input.Password
// prefix={<LockOutlined />}
// placeholder="Masukkan Password"
// size="large"
// />
// </Item>
// {/* Tombol */}
// <Item wrapperCol={{ offset: 8, span: 16 }}>
// <Space style={{ marginTop: '24px', width: '100%' }}>
// <Button
// type="primary"
// htmlType="submit"
// size="large"
// loading={loading}
// style={{
// backgroundColor: '#23A55A',
// borderColor: '#23A55A',
// width: 120,
// }}
// >
// Simpan
// </Button>
// <Button onClick={onCancel} size="large" style={{ width: 120 }}>
// Batal
// </Button>
// </Space>
// </Item>
// </Form>
// </Card>
// </Flex>
// );
// };
// export default Registration;

View File

@@ -31,8 +31,9 @@ const SignIn = () => {
prefix: 'auth/generate-captcha',
token: false,
});
setCaptchaSvg(res.data.svg || '');
setCaptchaText(res.data.text || '');
setCaptchaSvg(res.data?.data?.svg || '');
setCaptchaText(res.data?.data?.text || '');
} catch (err) {
console.error('Error fetching captcha:', err);
}
@@ -57,8 +58,8 @@ const SignIn = () => {
withCredentials: true,
});
const user = res?.data?.user || res?.user;
const accessToken = res?.data?.accessToken || res?.tokens?.accessToken;
const user = res?.data?.data?.user || res?.user;
const accessToken = res?.data?.data?.accessToken || res?.tokens?.accessToken;
if (user && accessToken) {
localStorage.setItem('token', accessToken);

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;