feat: add brand device management with error code handling and navigation

This commit is contained in:
2025-10-21 17:07:36 +07:00
parent fb3e500139
commit cf063822eb
8 changed files with 677 additions and 365 deletions

View File

@@ -0,0 +1,325 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Input, Divider, Typography, Switch, Button, Steps, Form, message, Table, Row, Col, Radio, Card, Tag, Upload, ConfigProvider } from 'antd';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { NotifAlert, NotifOk } from '../../../components/Global/ToastNotif';
import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb';
const { Text, Title } = Typography;
const { Step } = Steps;
// Mock API for Error Codes (can be moved to a separate file later)
const mockErrorCodeApi = {
errorCodes: [],
createErrorCode: async (data) => {
const newId = mockErrorCodeApi.errorCodes.length > 0 ? Math.max(...mockErrorCodeApi.errorCodes.map(ec => ec.error_code_id)) + 1 : 1;
const newErrorCode = { ...data, error_code_id: newId };
mockErrorCodeApi.errorCodes.push(newErrorCode);
return { statusCode: 201, data: newErrorCode };
},
};
const AddBrandDevice = () => {
const navigate = useNavigate();
const { setBreadcrumbItems } = useBreadcrumb();
const [brandForm] = Form.useForm();
const [errorCodeForm] = Form.useForm();
const [confirmLoading, setConfirmLoading] = useState(false);
const [currentStep, setCurrentStep] = useState(0);
const [anotherSolutionType, setAnotherSolutionType] = useState(null);
const [fileList, setFileList] = useState([]);
// Watch for form values changes to update the switch color
const statusValue = Form.useWatch('status', errorCodeForm);
const defaultData = {
brandName: '',
brandType: '',
manufacturer: '',
model: '',
status: true,
};
const [formData, setFormData] = useState(defaultData);
const [errorCodes, setErrorCodes] = useState([]);
const handleCancel = () => {
navigate('/master/brand-device');
};
const handleNextStep = async () => {
try {
await brandForm.validateFields();
setCurrentStep(1);
} catch (error) {
console.log('Validate Failed:', error);
NotifAlert({ icon: 'warning', title: 'Perhatian', message: 'Harap isi semua kolom wajib untuk brand device!' });
}
};
const handleFinish = async () => {
if (errorCodes.length === 0) {
NotifAlert({ icon: 'warning', title: 'Perhatian', message: 'Silakan tambahkan minimal satu error code.' });
return;
}
setConfirmLoading(true);
try {
const finalFormData = { ...formData, status: formData.status ? 'Active' : 'Inactive' };
console.log("Saving brand device:", finalFormData);
await new Promise((resolve) => setTimeout(resolve, 500));
const newBrandDeviceId = Date.now();
console.log("Brand device saved with ID:", newBrandDeviceId);
console.log("Saving error codes:", errorCodes);
for (const errorCode of errorCodes) {
if (errorCode.another_solution === 'image' && errorCode.image) {
console.log(`Uploading image for error code ${errorCode.error_code}:`, errorCode.image.name);
}
await mockErrorCodeApi.createErrorCode({
...errorCode,
brand_device_id: newBrandDeviceId
});
console.log("Saved error code:", errorCode.error_code);
}
setConfirmLoading(false);
NotifOk({ icon: 'success', title: 'Berhasil', message: 'Brand Device dan Error Code berhasil disimpan.' });
navigate('/master/brand-device');
} catch (error) {
setConfirmLoading(false);
console.error("Failed to save data:", error);
NotifAlert({
icon: "error",
title: "Gagal",
message: "Gagal menyimpan data. Silakan coba lagi.",
});
}
};
const handleAddErrorCode = async () => {
try {
const values = await errorCodeForm.validateFields();
const newErrorCode = {
...values,
status: values.status === undefined ? true : values.status,
image: fileList.length > 0 ? fileList[0] : null,
key: `temp-${Date.now()}`
};
setErrorCodes([...errorCodes, newErrorCode]);
message.success('Error code berhasil ditambahkan');
errorCodeForm.resetFields();
setAnotherSolutionType(null);
setFileList([]);
} catch (error) {
console.log('Validate Failed:', error);
NotifAlert({ icon: 'warning', title: 'Perhatian', message: 'Harap isi semua kolom wajib untuk error code!' });
}
};
const handleDeleteErrorCode = (key) => {
setErrorCodes(errorCodes.filter(item => item.key !== key));
message.success('Error code berhasil dihapus');
};
const uploadProps = {
onRemove: (file) => {
setFileList([]);
},
beforeUpload: (file) => {
setFileList([file]);
return false; // Prevent auto-upload
},
fileList,
};
const errorCodeColumns = [
{ title: 'Error Code', dataIndex: 'error_code', key: 'error_code' },
{ title: 'Trouble Description', dataIndex: 'description', key: 'description' },
{
title: 'Status',
dataIndex: 'status',
key: 'status',
render: (status) => (
<Tag color={status ? '#23A55A' : 'red'}>
{status ? 'Active' : 'Inactive'}
</Tag>
),
},
{
title: 'Action',
key: 'action',
render: (_, record) => (
<Button type="link" danger onClick={() => handleDeleteErrorCode(record.key)}>Delete</Button>
),
},
];
useEffect(() => {
brandForm.setFieldsValue(formData);
}, [formData, brandForm]);
useEffect(() => {
setBreadcrumbItems([
{ title: <Text strong style={{ fontSize: '14px' }}> Master</Text> },
{ title: <Text strong style={{ fontSize: '14px' }} onClick={() => navigate('/master/brand-device')}>Brand Device</Text> },
{ title: <Text strong style={{ fontSize: '14px' }}>Tambah Brand Device</Text> }
]);
}, [setBreadcrumbItems, navigate]);
const renderStepContent = () => {
if (currentStep === 0) {
return (
<Form layout="vertical" form={brandForm} onValuesChange={(changedValues, allValues) => setFormData(prev => ({...prev, ...allValues}))} initialValues={formData}>
<Form.Item label="Status" name="status" valuePropName="checked">
<Switch
checked={formData.status}
style={{ backgroundColor: formData.status ? '#23A55A' : '#bfbfbf' }}
/>
</Form.Item>
<Form.Item label="Brand Name" name="brandName" rules={[{ required: true, message: 'Brand Name wajib diisi!' }]}>
<Input />
</Form.Item>
<Form.Item label="Type" name="brandType" rules={[{ required: true, message: 'Type wajib diisi!' }]}>
<Input />
</Form.Item>
<Form.Item label="Manufacturer" name="manufacturer" rules={[{ required: true, message: 'Manufacturer wajib diisi!' }]}>
<Input />
</Form.Item>
<Form.Item label="Model" name="model" rules={[{ required: true, message: 'Model wajib diisi!' }]}>
<Input />
</Form.Item>
</Form>
);
}
if (currentStep === 1) {
return (
<div>
<Title level={5}>Tambah Error Code {errorCodes.length + 1}</Title>
<Form form={errorCodeForm} layout="vertical" initialValues={{ status: true }}>
<Form.Item label="Status" name="status" valuePropName="checked">
<Switch
style={{ backgroundColor: statusValue ? '#23A55A' : '#bfbfbf' }}
/>
</Form.Item>
<Form.Item name="error_code" label="Error Code" rules={[{ required: true, message: 'Error Code wajib diisi' }]}>
<Input />
</Form.Item>
<Form.Item name="description" label="Trouble Description" rules={[{ required: true, message: 'Trouble Description wajib diisi' }]}>
<Input.TextArea />
</Form.Item>
<Form.Item name="detected_method" label="Detected Method" rules={[{ required: true, message: 'Detected Method wajib diisi' }]}>
<Input />
</Form.Item>
<Row gutter={16}>
<Col span={8}>
<Form.Item name="indicator_light" label="Indicator Light">
<Input />
</Form.Item>
</Col>
<Col span={8}>
<Form.Item name="detector" label="Detector">
<Input />
</Form.Item>
</Col>
<Col span={8}>
<Form.Item name="auto_shutdown" label="Auto Shutdown">
<Input />
</Form.Item>
</Col>
</Row>
<Form.Item name="what_action_to_take" label="What Action to Take" rules={[{ required: true, message: 'What Action to Take wajib diisi' }]}>
<Input.TextArea />
</Form.Item>
<Form.Item name="another_solution" label="Another Solution (opsional)">
<Radio.Group onChange={(e) => setAnotherSolutionType(e.target.value)}>
<Radio value="image">Image</Radio>
<Radio value="other">Other</Radio>
</Radio.Group>
</Form.Item>
{anotherSolutionType === 'image' && (
<Form.Item label="Upload Image">
<Upload {...uploadProps}>
<Button icon={<UploadOutlined />}>Click to Upload</Button>
</Upload>
</Form.Item>
)}
{anotherSolutionType === 'other' && (
<Form.Item name="another_solution_text" label="Enter Solution Text">
<Input.TextArea rows={4} />
</Form.Item>
)}
<Form.Item>
<Button type="dashed" icon={<PlusOutlined />} onClick={handleAddErrorCode} style={{ width: '100%' }}>
Tambah Error Code Lain
</Button>
</Form.Item>
</Form>
<Divider />
<Title level={5}>Daftar Error Code</Title>
<Table columns={errorCodeColumns} dataSource={errorCodes} rowKey="key" pagination={false} />
</div>
);
}
return null;
};
return (
<Card>
<Title level={4}>Tambah Brand Device</Title>
<Divider />
<Steps current={currentStep} style={{ marginBottom: 24 }}>
<Step title="Brand Device Details" />
<Step title="Error Codes" />
</Steps>
<div style={{ marginTop: 24 }}>
{renderStepContent()}
</div>
<Divider />
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
<ConfigProvider
theme={{
token: { colorBgContainer: '#E9F6EF' },
components: {
Button: {
defaultBg: 'white',
defaultColor: '#23A55A',
defaultBorderColor: '#23A55A',
defaultHoverColor: '#23A55A',
defaultHoverBorderColor: '#23A55A',
},
},
}}
>
<Button onClick={handleCancel}>Batal</Button>
{currentStep > 0 && (
<Button onClick={() => setCurrentStep(currentStep - 1)} style={{ marginRight: 8 }}>Kembali</Button>
)}
</ConfigProvider>
<ConfigProvider
theme={{
components: {
Button: {
defaultBg: '#23a55a',
defaultColor: '#FFFFFF',
defaultBorderColor: '#23a55a',
defaultHoverBg: '#209652', // A slightly darker shade for hover
defaultHoverColor: '#FFFFFF',
defaultHoverBorderColor: '#23a55a',
},
},
}}
>
{currentStep < 1 && (
<Button loading={confirmLoading} onClick={handleNextStep}>Lanjut</Button>
)}
{currentStep === 1 && (
<Button loading={confirmLoading} onClick={handleFinish}>Simpan</Button>
)}
</ConfigProvider>
</div>
</Card>
);
};
export default AddBrandDevice;

View File

@@ -1,8 +1,6 @@
import React, { memo, useState, useEffect } from 'react';
import React, { memo, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import ListBrandDevice from './component/ListBrandDevice';
import DetailBrandDevice from './component/DetailBrandDevice';
import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb';
import { Typography } from 'antd';
@@ -12,35 +10,6 @@ const IndexBrandDevice = memo(function IndexBrandDevice() {
const navigate = useNavigate();
const { setBreadcrumbItems } = useBreadcrumb();
const [actionMode, setActionMode] = useState('list');
const [selectedData, setSelectedData] = useState(null);
const [readOnly, setReadOnly] = useState(false);
const [showModal, setShowmodal] = useState(false);
const setMode = (param) => {
setActionMode(param);
switch (param) {
case 'add':
setReadOnly(false);
setShowmodal(true);
break;
case 'edit':
setReadOnly(false);
setShowmodal(true);
break;
case 'preview':
setReadOnly(true);
setShowmodal(true);
break;
default:
setShowmodal(false);
break;
}
};
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
@@ -55,23 +24,9 @@ const IndexBrandDevice = memo(function IndexBrandDevice() {
return (
<React.Fragment>
<ListBrandDevice
actionMode={actionMode}
setActionMode={setMode}
selectedData={selectedData}
setSelectedData={setSelectedData}
readOnly={readOnly}
/>
<DetailBrandDevice
setActionMode={setMode}
selectedData={selectedData}
setSelectedData={setSelectedData}
readOnly={readOnly}
showModal={showModal}
actionMode={actionMode}
/>
<ListBrandDevice />
</React.Fragment>
);
});
export default IndexBrandDevice;
export default IndexBrandDevice;

View File

@@ -1,310 +0,0 @@
import { useEffect, useState } from 'react';
import { Modal, Input, Divider, Typography, Switch, Button, ConfigProvider, Select } from 'antd';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
const { Text } = Typography;
const DetailBrandDevice = (props) => {
const [confirmLoading, setConfirmLoading] = useState(false);
const defaultData = {
brand_id: '',
brandName: '',
brandType: '',
manufacturer: '',
model: '',
status: 'Active',
};
const [FormData, setFormData] = useState(defaultData);
const handleCancel = () => {
props.setSelectedData(null);
props.setActionMode('list');
};
const handleSave = async () => {
setConfirmLoading(true);
// Validasi required fields
if (!FormData.brandName) {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Kolom Brand Name Tidak Boleh Kosong',
});
setConfirmLoading(false);
return;
}
if (!FormData.brandType) {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Kolom Type Tidak Boleh Kosong',
});
setConfirmLoading(false);
return;
}
if (!FormData.manufacturer) {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Kolom Manufacturer Tidak Boleh Kosong',
});
setConfirmLoading(false);
return;
}
if (!FormData.model) {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Kolom Model Tidak Boleh Kosong',
});
setConfirmLoading(false);
return;
}
if (!FormData.status) {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Kolom Status Tidak Boleh Kosong',
});
setConfirmLoading(false);
return;
}
const payload = {
brandName: FormData.brandName,
brandType: FormData.brandType,
manufacturer: FormData.manufacturer,
model: FormData.model,
status: FormData.status,
};
try {
// Simulate API call
await new Promise((resolve) => setTimeout(resolve, 500));
const response = {
statusCode: FormData.brand_id ? 200 : 201,
data: {
brandName: FormData.brandName,
},
};
console.log('Save Brand Device Response:', response);
// Check if response is successful
if (response && (response.statusCode === 200 || response.statusCode === 201)) {
NotifOk({
icon: 'success',
title: 'Berhasil',
message: `Data Brand Device "${
response.data?.brandName || FormData.brandName
}" berhasil ${FormData.brand_id ? 'diubah' : 'ditambahkan'}.`,
});
props.setActionMode('list');
} else {
NotifAlert({
icon: 'error',
title: 'Gagal',
message: response?.message || 'Terjadi kesalahan saat menyimpan data.',
});
}
} catch (error) {
console.error('Save Brand Device Error:', error);
NotifAlert({
icon: 'error',
title: 'Error',
message: error.message || 'Terjadi kesalahan pada server. Coba lagi nanti.',
});
}
setConfirmLoading(false);
};
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormData({
...FormData,
[name]: value,
});
};
const handleSelectChange = (name, value) => {
setFormData({
...FormData,
[name]: value,
});
};
const handleStatusToggle = (event) => {
const isChecked = event;
setFormData({
...FormData,
status: isChecked ? true : false,
});
};
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
if (props.selectedData != null) {
setFormData(props.selectedData);
} else {
setFormData(defaultData);
}
} else {
// navigate('/signin'); // Uncomment if useNavigate is imported
}
}, [props.showModal]);
return (
<Modal
title={`${
props.actionMode === 'add'
? 'Tambah'
: props.actionMode === 'preview'
? 'Preview'
: 'Edit'
} Brand Device`}
open={props.showModal}
onCancel={handleCancel}
footer={[
<>
<ConfigProvider
theme={{
token: { colorBgContainer: '#E9F6EF' },
components: {
Button: {
defaultBg: 'white',
defaultColor: '#23A55A',
defaultBorderColor: '#23A55A',
defaultHoverColor: '#23A55A',
defaultHoverBorderColor: '#23A55A',
},
},
}}
>
<Button onClick={handleCancel}>Batal</Button>
</ConfigProvider>
<ConfigProvider
theme={{
token: {
colorBgContainer: '#209652',
},
components: {
Button: {
defaultBg: '#23a55a',
defaultColor: '#FFFFFF',
defaultBorderColor: '#23a55a',
defaultHoverColor: '#FFFFFF',
defaultHoverBorderColor: '#23a55a',
},
},
}}
>
{!props.readOnly && (
<Button loading={confirmLoading} onClick={handleSave}>
Simpan
</Button>
)}
</ConfigProvider>
</>,
]}
>
{FormData && (
<div>
<div>
<div>
<Text strong>Status</Text>
</div>
<div
style={{
display: 'flex',
alignItems: 'center',
marginTop: '8px',
}}
>
<div style={{ marginRight: '8px' }}>
<Switch
disabled={props.readOnly}
style={{
backgroundColor:
FormData.status === true ? '#23A55A' : '#bfbfbf',
}}
checked={FormData.status === true}
onChange={handleStatusToggle}
/>
</div>
<div>
<Text>{FormData.status === true ? 'Active' : 'Inactive'}</Text>
</div>
</div>
</div>
<Divider style={{ margin: '12px 0' }} />
<div hidden>
<Text strong>Brand ID</Text>
<Input
name="brand_id"
value={FormData.brand_id}
onChange={handleInputChange}
disabled
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Brand Name</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="brandName"
value={FormData.brandName}
onChange={handleInputChange}
placeholder="Enter Brand Name"
readOnly={props.readOnly}
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Type</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="brandType"
value={FormData.brandType}
onChange={handleInputChange}
placeholder="Enter Type (e.g., PLC)"
readOnly={props.readOnly}
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Manufacturer</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="manufacturer"
value={FormData.manufacturer}
onChange={handleInputChange}
placeholder="Enter Manufacturer"
readOnly={props.readOnly}
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Model</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="model"
value={FormData.model}
onChange={handleInputChange}
placeholder="Enter Model"
readOnly={props.readOnly}
/>
</div>
</div>
)}
</Modal>
);
};
export default DetailBrandDevice;

View File

@@ -231,11 +231,6 @@ const ListBrandDevice = memo(function ListBrandDevice(props) {
props.setActionMode('edit');
};
const showAddModal = (param = null) => {
props.setSelectedData(param);
props.setActionMode('add');
};
const showDeleteDialog = (param) => {
NotifConfirmDialog({
icon: 'question',
@@ -320,7 +315,7 @@ const ListBrandDevice = memo(function ListBrandDevice(props) {
>
<Button
icon={<PlusOutlined />}
onClick={() => showAddModal()}
onClick={() => navigate('/master/brand-device/add')}
size="large"
>
Tambah Brand Device
@@ -350,4 +345,4 @@ const ListBrandDevice = memo(function ListBrandDevice(props) {
);
});
export default ListBrandDevice;
export default ListBrandDevice;