update: enhance device API functions with pagination and response structure; modify device form validation and UI components

This commit is contained in:
2025-10-01 14:33:55 +07:00
parent 2778c96143
commit 3b51f59679
4 changed files with 353 additions and 224 deletions

View File

@@ -5,7 +5,39 @@ const getAllDevice = async (queryParams) => {
method: 'get',
prefix: `device?${queryParams.toString()}`,
});
return response;
console.log('getAllDevice response:', response);
console.log('Query params:', queryParams.toString());
// Parse query params to get page and limit
const params = Object.fromEntries(queryParams);
const currentPage = parseInt(params.page) || 1;
const currentLimit = parseInt(params.limit) || 10;
// Backend returns all data, so we need to do client-side pagination
const allData = response.data || [];
const totalData = allData.length;
// Calculate start and end index for current page
const startIndex = (currentPage - 1) * currentLimit;
const endIndex = startIndex + currentLimit;
// Slice data for current page
const paginatedData = allData.slice(startIndex, endIndex);
// Transform response to match TableList expected structure
return {
status: response.statusCode || 200,
data: {
data: paginatedData,
paging: {
page: currentPage,
limit: currentLimit,
total: totalData,
page_total: Math.ceil(totalData / currentLimit)
},
total: totalData
}
};
};
const getDeviceById = async (id) => {
@@ -22,7 +54,13 @@ const createDevice = async (queryParams) => {
prefix: `device`,
params: queryParams,
});
return response.data;
console.log('createDevice full response:', response);
// Return full response with statusCode
return {
statusCode: response.statusCode || 200,
data: response.data,
message: response.message
};
};
const updateDevice = async (device_id, queryParams) => {
@@ -31,7 +69,13 @@ const updateDevice = async (device_id, queryParams) => {
prefix: `device/${device_id}`,
params: queryParams,
});
return response.data;
console.log('updateDevice full response:', response);
// Return full response with statusCode
return {
statusCode: response.statusCode || 200,
data: response.data,
message: response.message
};
};
const deleteDevice = async (queryParams) => {
@@ -39,7 +83,13 @@ const deleteDevice = async (queryParams) => {
method: 'delete',
prefix: `device/${queryParams}`,
});
return response.data;
console.log('deleteDevice full response:', response);
// Return full response with statusCode
return {
statusCode: response.statusCode || 200,
data: response.data,
message: response.message
};
};
export { getAllDevice, getDeviceById, createDevice, updateDevice, deleteDevice };

View File

@@ -66,7 +66,7 @@ const IndexDevice = memo(function IndexDevice() {
setSelectedData={setSelectedData}
readOnly={readOnly}
showModal={showModal}
permitDefault={true}
permitDefault={false}
actionMode={actionMode}
/>
{actionMode == 'generatepdf' && (

View File

@@ -1,21 +1,25 @@
import React, { useEffect, useState } from 'react';
import { Modal, Input, Divider, Typography, Switch, Button, ConfigProvider, Radio } from 'antd';
import { Modal, Input, Divider, Typography, Switch, Button, ConfigProvider, Radio, Select } from 'antd';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
import { createApd, getJenisPermit, updateApd } from '../../../../api/master-apd';
import { createDevice, updateDevice } from '../../../../api/master-device';
import { Checkbox } from 'antd';
const CheckboxGroup = Checkbox.Group;
const { Text } = Typography;
const { TextArea } = Input;
const DetailDevice = (props) => {
const [confirmLoading, setConfirmLoading] = useState(false);
const defaultData = {
id_apd: '',
nama_apd: '',
type_input: 1,
is_active: true,
jenis_permit_default: [],
device_id: '',
device_code: '',
device_name: '',
device_status: true,
device_location: 'Building A',
device_description: '',
ip_address: '',
};
const [FormData, setFormData] = useState(defaultData);
@@ -50,16 +54,62 @@ const DetailDevice = (props) => {
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);
if (!FormData.nama_apd) {
// Validasi required fields
if (!FormData.device_code) {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Kolom Nama APD Tidak Boleh Kosong',
message: 'Kolom Device Code Tidak Boleh Kosong',
});
setConfirmLoading(false);
return;
}
if (!FormData.device_name) {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Kolom Device Name Tidak Boleh Kosong',
});
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;
}
@@ -76,27 +126,31 @@ const DetailDevice = (props) => {
}
const payload = {
nama_apd: FormData.nama_apd,
is_active: FormData.is_active,
type_input: FormData.type_input,
jenis_permit_default: checkedList,
device_code: FormData.device_code,
device_name: FormData.device_name,
device_status: FormData.device_status,
device_location: FormData.device_location,
device_description: FormData.device_description,
ip_address: FormData.ip_address,
};
if (props.permitDefault) {
try {
let response;
if (!FormData.id_apd) {
response = await createApd(payload);
if (!FormData.device_id) {
response = await createDevice(payload);
} else {
response = await updateApd(FormData.id_apd, payload);
response = await updateDevice(FormData.device_id, payload);
}
if (response.statusCode === 200) {
console.log('Save Device Response:', response);
// Check if response is successful
if (response && (response.statusCode === 200 || response.statusCode === 201)) {
NotifOk({
icon: 'success',
title: 'Berhasil',
message: `Data "${response.data.nama_apd}" berhasil ${
FormData.id_apd ? 'diubah' : 'ditambahkan'
message: `Data Device "${response.data?.device_name || FormData.device_name}" berhasil ${
FormData.device_id ? 'diubah' : 'ditambahkan'
}.`,
});
@@ -105,24 +159,17 @@ const DetailDevice = (props) => {
NotifAlert({
icon: 'error',
title: 'Gagal',
message: response.message || 'Terjadi kesalahan saat menyimpan data.',
message: response?.message || 'Terjadi kesalahan saat menyimpan data.',
});
}
} catch (error) {
console.error('Save Device Error:', error);
NotifAlert({
icon: 'error',
title: 'Error',
message: 'Terjadi kesalahan pada server. Coba lagi nanti.',
message: error.message || 'Terjadi kesalahan pada server. Coba lagi nanti.',
});
}
} else {
props.setData((prevData) => [
...prevData,
{ nama_apd: payload.nama_apd, type_input: payload.type_input },
]);
props.setActionMode('list');
}
setConfirmLoading(false);
};
@@ -139,22 +186,35 @@ const DetailDevice = (props) => {
const isChecked = event;
setFormData({
...FormData,
is_active: isChecked ? true : false,
device_status: isChecked ? true : false,
});
};
const handleSelectChange = (value) => {
setFormData({
...FormData,
device_location: value,
});
};
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
// Only call getDataJenisPermit if permitDefault is enabled
if (props.permitDefault) {
getDataJenisPermit();
}
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);
}
} else {
navigate('/signin');
// navigate('/signin'); // Uncomment if useNavigate is imported
}
}, [props.showModal]);
@@ -217,11 +277,9 @@ const DetailDevice = (props) => {
>
{FormData && (
<div>
{props.permitDefault && (
<>
<div>
<div>
<Text strong>Aktif</Text>
<Text strong>Device Status</Text>
</div>
<div
style={{
@@ -235,56 +293,87 @@ const DetailDevice = (props) => {
disabled={props.readOnly}
style={{
backgroundColor:
FormData.is_active == 1 ? '#23A55A' : '#bfbfbf',
FormData.device_status === true ? '#23A55A' : '#bfbfbf',
}}
checked={FormData.is_active == 1 ? true : false}
checked={FormData.device_status === true}
onChange={handleStatusToggle}
/>
</div>
<div>
<Text>
{FormData.is_active == 1 ? 'Aktif' : 'Non Aktif'}
{FormData.device_status === true ? 'Running' : 'Offline'}
</Text>
</div>
</div>
</div>
<Divider style={{ margin: '5px 0' }} />
</>
)}
<Divider style={{ margin: '12px 0' }} />
<div hidden>
<Text strong>Device ID</Text>
<Input
name="id_apd"
value={FormData.id_apd}
name="device_id"
value={FormData.device_id}
onChange={handleInputChange}
disabled
/>
</div>
<div>
<Text strong>Device Name</Text>
<div style={{ marginBottom: 12 }}>
<Text strong>Device Code</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="nama_apd"
value={FormData.nama_apd}
name="device_code"
value={FormData.device_code}
onChange={handleInputChange}
placeholder="Enter Device Code"
readOnly={props.readOnly}
/>
</div>
<div style={{ marginTop: 4, marginBottom: 4 }}>
<Text strong>Tipe Input</Text>
<Text style={{ color: 'red', marginLeft: 4 }}>*</Text>
<div>
<Radio.Group
value={FormData.type_input}
options={[
{ value: 1, label: 'Check' },
{ value: 2, label: 'Text' },
{ value: 3, label: 'Number' },
]}
onChange={onChangeRadio}
disabled={props.readOnly}
<div style={{ marginBottom: 12 }}>
<Text strong>Device Name</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="device_name"
value={FormData.device_name}
onChange={handleInputChange}
placeholder="Enter Device Name"
readOnly={props.readOnly}
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Device Location</Text>
<Text style={{ color: 'red' }}> *</Text>
<Select
value={FormData.device_location}
onChange={handleSelectChange}
disabled={props.readOnly}
style={{ width: '100%' }}
placeholder="Select Location"
options={[
{ value: 'Building A', label: 'Building A' },
{ value: 'Building B', label: 'Building B' },
]}
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>IP Address</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="ip_address"
value={FormData.ip_address}
onChange={handleInputChange}
placeholder="e.g. 192.168.1.1"
readOnly={props.readOnly}
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Device Description</Text>
<TextArea
name="device_description"
value={FormData.device_description}
onChange={handleInputChange}
placeholder="Enter Device Description (Optional)"
readOnly={props.readOnly}
rows={4}
/>
</div>
{props.permitDefault && (
<div>

View File

@@ -3,7 +3,15 @@ import {
Space,
Tag,
ConfigProvider,
Button, Row, Col, Card, Divider, Form, Input, Dropdown } from 'antd';
Button,
Row,
Col,
Card,
Divider,
Form,
Input,
Dropdown,
} from 'antd';
import {
PlusOutlined,
FilterOutlined,
@@ -13,11 +21,12 @@ import {
SearchOutlined,
FilePdfOutlined,
FileExcelOutlined,
EllipsisOutlined
EllipsisOutlined,
} from '@ant-design/icons';
import { NotifAlert, NotifOk, NotifConfirmDialog } from '../../../../components/Global/ToastNotif';
import { useNavigate } from 'react-router-dom';
import { deleteApd, getAllApd } from '../../../../api/master-apd';
import { deleteDevice, getAllDevice } from '../../../../api/master-device';
import TableList from '../../../../components/Global/TableList';
import { getFilterData } from '../../../../components/Global/DataFilter';
import ExcelJS from 'exceljs';
@@ -27,32 +36,50 @@ import logoPiEnergi from '../../../../assets/images/logo/pi-energi.png';
const columns = (items, handleClickMenu) => [
{
title: 'ID',
dataIndex: 'id_apd',
key: 'id_apd',
dataIndex: 'device_id',
key: 'device_id',
width: '5%',
hidden: 'true',
},
{
title: 'Device Name',
dataIndex: 'nama_apd',
key: 'nama_apd',
width: '55%',
title: 'Device Code',
dataIndex: 'device_code',
key: 'device_code',
width: '8%',
},
{
title: 'Aktif',
dataIndex: 'is_active',
key: 'is_active',
title: 'Device Name',
dataIndex: 'device_name',
key: 'device_name',
width: '20%',
},
{
title: 'Location',
dataIndex: 'device_location',
key: 'device_location',
width: '12%',
},
{
title: 'IP Address',
dataIndex: 'ip_address',
key: 'ip_address',
width: '13%',
},
{
title: 'Status',
dataIndex: 'device_status',
key: 'device_status',
width: '10%',
align: 'center',
render: (_, { is_active }) => (
render: (_, { device_status }) => (
<>
{is_active === true ? (
<Tag color={'green'} key={'aaa'}>
Aktif
{device_status === true ? (
<Tag color={'green'} key={'status'}>
Running
</Tag>
) : (
<Tag color={'red'} key={'aaa'}>
Non-Aktif
<Tag color={'red'} key={'status'}>
Offline
</Tag>
)}
</>
@@ -67,15 +94,12 @@ const columns = (items, handleClickMenu) => [
<Dropdown
menu={{
items,
onClick: ({key})=>handleClickMenu(key, record)
onClick: ({ key }) => handleClickMenu(key, record),
}}
trigger={['click']}
placement="bottomRight"
>
<Button
shape="default"
icon={<EllipsisOutlined />}
/>
<Button shape="default" icon={<EllipsisOutlined />} />
</Dropdown>
),
},
@@ -85,8 +109,9 @@ const ListDevice = memo(function ListDevice(props) {
const [showFilter, setShowFilter] = useState(false);
const [trigerFilter, setTrigerFilter] = useState(false);
const defaultFilter = { nama_apd: '' };
const defaultFilter = { search: '' };
const [formDataFilter, setFormDataFilter] = useState(defaultFilter);
const [searchValue, setSearchValue] = useState('');
const navigate = useNavigate();
@@ -111,12 +136,15 @@ const ListDevice = memo(function ListDevice(props) {
setTrigerFilter((prev) => !prev);
};
const handleInputChangeFilter = (e) => {
const { name, value } = e.target;
setFormDataFilter((prevData) => ({
...prevData,
[name]: value,
}));
const handleSearch = () => {
setFormDataFilter({ search: searchValue });
setTrigerFilter((prev) => !prev);
};
const handleSearchClear = () => {
setSearchValue('');
setFormDataFilter({ search: '' });
setTrigerFilter((prev) => !prev);
};
const showPreviewModal = (param) => {
@@ -138,27 +166,27 @@ const ListDevice = memo(function ListDevice(props) {
NotifConfirmDialog({
icon: 'question',
title: 'Konfirmasi',
message: 'Apakah anda yakin hapus data "' + param.nama_apd + '" ?',
onConfirm: () => handleDelete(param.id_apd),
message: 'Apakah anda yakin hapus data "' + param.device_name + '" ?',
onConfirm: () => handleDelete(param.device_id),
onCancel: () => props.setSelectedData(null),
});
};
const handleDelete = async (id_apd) => {
const response = await deleteApd(id_apd);
const handleDelete = async (device_id) => {
const response = await deleteDevice(device_id);
if (response.statusCode == 200) {
NotifAlert({
icon: 'success',
title: 'Berhasil',
message: 'Data Data "' + response.data[0].nama_apd + '" berhasil dihapus.',
message: 'Data Device "' + response.data.device_name + '" berhasil dihapus.',
});
doFilter();
} else {
NotifOk({
icon: 'error',
title: 'Gagal',
message: 'Gagal Menghapus Data Data "' + response.data[0].nama_apd + '"',
message: 'Gagal Menghapus Data Device',
});
}
};
@@ -293,23 +321,37 @@ const ListDevice = memo(function ListDevice(props) {
<Row>
<Col xs={24}>
<Row justify="space-between" align="middle" gutter={[8, 8]}>
<Col>
<ConfigProvider
theme={{
token: { colorBgContainer: '#E9F6EF' },
components: {
Button: {
defaultBg: 'white',
defaultColor: '#23A55A',
defaultBorderColor: '#23A55A',
},
},
<Col xs={24} sm={24} md={12} lg={12}>
<Input.Search
placeholder="Search device by name, code, or location..."
value={searchValue}
onChange={(e) => {
const value = e.target.value;
setSearchValue(value);
// Auto search when clearing by backspace/delete
if (value === '') {
setFormDataFilter({ search: '' });
setTrigerFilter((prev) => !prev);
}
}}
onSearch={handleSearch}
allowClear={{
clearIcon: <span onClick={handleSearchClear}></span>,
}}
enterButton={
<Button
type="primary"
icon={<SearchOutlined />}
style={{
backgroundColor: '#23A55A',
borderColor: '#23A55A',
}}
>
<Button onClick={toggleFilter} icon={<FilterOutlined />}>
Filter
Search
</Button>
</ConfigProvider>
}
size="large"
/>
</Col>
<Col>
<Space wrap size="small">
@@ -330,6 +372,7 @@ const ListDevice = memo(function ListDevice(props) {
<Button
icon={<PlusOutlined />}
onClick={() => showAddModal()}
size="large"
>
Tambah Data
</Button>
@@ -338,62 +381,9 @@ const ListDevice = memo(function ListDevice(props) {
</Col>
</Row>
</Col>
{/* filter */}
<Col xs={24} sm={24} md={24} lg={24} xl={24} style={{ marginTop: '16px' }}>
{showFilter && (
<>
<Divider />
<Form layout="vertical">
<Form.Item label="Nama APD">
<div
style={{
display: 'flex',
gap: '8px',
alignItems: 'center',
maxWidth: '500px',
width: '100%',
}}
>
<Input
name="nama_apd"
value={formDataFilter.nama_apd}
onChange={handleInputChangeFilter}
placeholder="Enter Nama APD"
style={{ height: '40px' }}
/>
<ConfigProvider
theme={{
token: {
colorText: 'white',
colorBgContainer: 'purple',
},
components: {
Button: {
defaultBg: 'white',
defaultColor: '#23A55A',
defaultBorderColor: '#23A55A',
},
},
}}
>
<Button
icon={<SearchOutlined />}
onClick={doFilter}
style={{ height: '40px' }}
>
Cari
</Button>
</ConfigProvider>
</div>
</Form.Item>
</Form>
</>
)}
</Col>
<Col xs={24} sm={24} md={24} lg={24} xl={24} style={{ marginTop: '16px' }}>
<TableList
getData={getAllApd}
getData={getAllDevice}
queryParams={formDataFilter}
columns={columns(menu, handleClickMenu)}
triger={trigerFilter}