feat: add brand device management with error code handling and navigation
This commit is contained in:
325
src/pages/master/brandDevice/AddBrandDevice.jsx
Normal file
325
src/pages/master/brandDevice/AddBrandDevice.jsx
Normal 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;
|
||||
Reference in New Issue
Block a user