Add forms and hooks for managing error codes and spare parts
This commit is contained in:
233
src/pages/master/brandDevice/component/ErrorCodeSimpleForm.jsx
Normal file
233
src/pages/master/brandDevice/component/ErrorCodeSimpleForm.jsx
Normal file
@@ -0,0 +1,233 @@
|
||||
import {
|
||||
Form,
|
||||
Input,
|
||||
Switch,
|
||||
Upload,
|
||||
Button,
|
||||
Typography,
|
||||
message,
|
||||
ConfigProvider,
|
||||
} from 'antd';
|
||||
import { UploadOutlined } from '@ant-design/icons';
|
||||
import { uploadFile } from '../../../../api/file-uploads';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
const ErrorCodeSimpleForm = ({
|
||||
errorCodeForm,
|
||||
isErrorCodeFormReadOnly = false,
|
||||
errorCodeIcon,
|
||||
onErrorCodeIconUpload,
|
||||
onErrorCodeIconRemove,
|
||||
onAddErrorCode,
|
||||
}) => {
|
||||
const statusValue = Form.useWatch('status', errorCodeForm);
|
||||
|
||||
const handleIconUpload = async (file) => {
|
||||
// Check if file is an image
|
||||
const isImage = file.type.startsWith('image/');
|
||||
if (!isImage) {
|
||||
message.error('You can only upload image files!');
|
||||
return Upload.LIST_IGNORE;
|
||||
}
|
||||
|
||||
// Check file size (max 2MB)
|
||||
const isLt2M = file.size / 1024 / 1024 < 2;
|
||||
if (!isLt2M) {
|
||||
message.error('Image must be smaller than 2MB!');
|
||||
return Upload.LIST_IGNORE;
|
||||
}
|
||||
|
||||
try {
|
||||
const fileExtension = file.name.split('.').pop().toLowerCase();
|
||||
const isImageFile = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(
|
||||
fileExtension
|
||||
);
|
||||
const fileType = isImageFile ? 'image' : 'pdf';
|
||||
const folder = 'images';
|
||||
|
||||
const uploadResponse = await uploadFile(file, folder);
|
||||
const iconPath = uploadResponse.data?.path_icon || uploadResponse.data?.path_solution || '';
|
||||
|
||||
if (iconPath) {
|
||||
onErrorCodeIconUpload({
|
||||
name: file.name,
|
||||
uploadPath: iconPath,
|
||||
fileExtension,
|
||||
isImage: isImageFile,
|
||||
size: file.size,
|
||||
});
|
||||
message.success(`${file.name} uploaded successfully!`);
|
||||
} else {
|
||||
message.error(`Failed to upload ${file.name}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error uploading icon:', error);
|
||||
message.error(`Failed to upload ${file.name}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleIconRemove = () => {
|
||||
onErrorCodeIconRemove();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Status Switch */}
|
||||
<Form.Item label="Status" name="status">
|
||||
<div style={{ display: 'flex', alignItems: 'center' }}>
|
||||
<Form.Item name="status" valuePropName="checked" noStyle>
|
||||
<Switch
|
||||
disabled={isErrorCodeFormReadOnly}
|
||||
style={{ backgroundColor: statusValue ? '#23A55A' : '#bfbfbf' }}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Text style={{ marginLeft: 8 }}>
|
||||
{statusValue ? 'Active' : 'Inactive'}
|
||||
</Text>
|
||||
</div>
|
||||
</Form.Item>
|
||||
|
||||
{/* Error Code */}
|
||||
<Form.Item
|
||||
label="Error Code"
|
||||
name="error_code"
|
||||
rules={[{ required: true, message: 'Error code wajib diisi!' }]}
|
||||
>
|
||||
<Input
|
||||
placeholder="Enter error code"
|
||||
disabled={isErrorCodeFormReadOnly}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{/* Error Name */}
|
||||
<Form.Item
|
||||
label="Error Name"
|
||||
name="error_code_name"
|
||||
rules={[{ required: true, message: 'Error name wajib diisi!' }]}
|
||||
>
|
||||
<Input
|
||||
placeholder="Enter error name"
|
||||
disabled={isErrorCodeFormReadOnly}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{/* Error Description */}
|
||||
<Form.Item
|
||||
label="Description"
|
||||
name="error_code_description"
|
||||
>
|
||||
<Input.TextArea
|
||||
placeholder="Enter error description"
|
||||
rows={3}
|
||||
disabled={isErrorCodeFormReadOnly}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{/* Color and Icon in same row */}
|
||||
<Form.Item label="Color & Icon">
|
||||
<Input.Group compact>
|
||||
<Form.Item
|
||||
name="error_code_color"
|
||||
noStyle
|
||||
>
|
||||
<input
|
||||
type="color"
|
||||
disabled={isErrorCodeFormReadOnly}
|
||||
style={{ width: '30%', height: '40px', border: '1px solid #d9d9d9', borderRadius: 4 }}
|
||||
defaultValue="#000000"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item noStyle style={{ width: '70%', paddingLeft: 8 }}>
|
||||
{!isErrorCodeFormReadOnly ? (
|
||||
<Upload
|
||||
beforeUpload={handleIconUpload}
|
||||
showUploadList={false}
|
||||
accept="image/*"
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
<Button icon={<UploadOutlined />} style={{ width: '100%' }}>
|
||||
Upload Icon
|
||||
</Button>
|
||||
</Upload>
|
||||
) : (
|
||||
<div style={{ padding: '8px 12px', border: '1px solid #d9d9d9', borderRadius: 4 }}>
|
||||
<Text type="secondary">No upload allowed</Text>
|
||||
</div>
|
||||
)}
|
||||
</Form.Item>
|
||||
</Input.Group>
|
||||
|
||||
{errorCodeIcon && (
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<img
|
||||
src={errorCodeIcon.uploadPath}
|
||||
alt="Error Code Icon"
|
||||
style={{
|
||||
width: 50,
|
||||
height: 50,
|
||||
objectFit: 'cover',
|
||||
border: '1px solid #d9d9d9',
|
||||
borderRadius: 4,
|
||||
}}
|
||||
/>
|
||||
<div>
|
||||
<Text style={{ fontSize: 12 }}>{errorCodeIcon.name}</Text>
|
||||
<br />
|
||||
<Text type="secondary" style={{ fontSize: 10 }}>
|
||||
Size: {(errorCodeIcon.size / 1024).toFixed(1)} KB
|
||||
</Text>
|
||||
</div>
|
||||
{!isErrorCodeFormReadOnly && (
|
||||
<Button
|
||||
type="text"
|
||||
danger
|
||||
size="small"
|
||||
onClick={handleIconRemove}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Form.Item>
|
||||
|
||||
{/* Add Error Code Button */}
|
||||
{!isErrorCodeFormReadOnly && (
|
||||
<Form.Item>
|
||||
<ConfigProvider
|
||||
theme={{
|
||||
token: { colorBgContainer: '#23a55ade' },
|
||||
components: {
|
||||
Button: {
|
||||
defaultBg: '#23a55a',
|
||||
defaultColor: '#FFFFFF',
|
||||
defaultBorderColor: '#23a55a',
|
||||
defaultHoverBg: '#209652',
|
||||
defaultHoverColor: '#FFFFFF',
|
||||
defaultHoverBorderColor: '#23a55a',
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
htmlType="button"
|
||||
onClick={() => {
|
||||
// Call parent function to add error code
|
||||
onAddErrorCode();
|
||||
}}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
+ Add Error Code
|
||||
</Button>
|
||||
</ConfigProvider>
|
||||
</Form.Item>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ErrorCodeSimpleForm;
|
||||
@@ -139,7 +139,10 @@ const SolutionField = ({
|
||||
icon={<DeleteOutlined />}
|
||||
onClick={() => onRemove(fieldId)}
|
||||
disabled={isReadOnly}
|
||||
style={{ borderColor: '#ff4d4f' }}
|
||||
style={{
|
||||
borderColor: '#ff4d4f',
|
||||
color: '#ff4d4f'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -161,7 +164,7 @@ const SolutionField = ({
|
||||
/>
|
||||
</Form.Item>
|
||||
<Text style={{ marginLeft: 8 }}>
|
||||
{(watchedStatus ?? true) ? 'Active' : 'Non Active'}
|
||||
{(watchedStatus ?? true) ? 'Active' : 'Inactive'}
|
||||
</Text>
|
||||
</div>
|
||||
</Form.Item>
|
||||
|
||||
243
src/pages/master/brandDevice/component/SolutionFieldNew.jsx
Normal file
243
src/pages/master/brandDevice/component/SolutionFieldNew.jsx
Normal file
@@ -0,0 +1,243 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Form, Input, Button, Switch, Radio, Upload, Typography, Space } from 'antd';
|
||||
import { DeleteOutlined, UploadOutlined, EyeOutlined } from '@ant-design/icons';
|
||||
import { uploadFile, getFolderFromFileType } from '../../../../api/file-uploads';
|
||||
import { NotifAlert } from '../../../../components/Global/ToastNotif';
|
||||
|
||||
const { Text } = Typography;
|
||||
const { TextArea } = Input;
|
||||
|
||||
const SolutionFieldNew = ({
|
||||
fieldKey,
|
||||
fieldName,
|
||||
index,
|
||||
solutionType,
|
||||
solutionStatus,
|
||||
isReadOnly = false,
|
||||
canRemove = true,
|
||||
onTypeChange,
|
||||
onStatusChange,
|
||||
onRemove,
|
||||
onFileUpload,
|
||||
onFileView,
|
||||
fileList = []
|
||||
}) => {
|
||||
const [currentStatus, setCurrentStatus] = useState(solutionStatus ?? true);
|
||||
|
||||
// Watch form values
|
||||
const getFieldValue = () => {
|
||||
try {
|
||||
const form = document.querySelector(`[data-field="${fieldName}"]`)?.form;
|
||||
if (form) {
|
||||
const formData = new FormData(form);
|
||||
return formData.get(`${fieldName}.status`) === 'on';
|
||||
}
|
||||
return currentStatus;
|
||||
} catch {
|
||||
return currentStatus;
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentStatus(solutionStatus ?? true);
|
||||
}, [solutionStatus]);
|
||||
const handleFileUpload = async (file) => {
|
||||
try {
|
||||
const isAllowedType = [
|
||||
'application/pdf',
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/gif',
|
||||
].includes(file.type);
|
||||
|
||||
if (!isAllowedType) {
|
||||
NotifAlert({
|
||||
icon: 'error',
|
||||
title: 'Error',
|
||||
message: `${file.name} bukan file PDF atau gambar yang diizinkan.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const fileExtension = file.name.split('.').pop().toLowerCase();
|
||||
const isImage = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(fileExtension);
|
||||
const fileType = isImage ? 'image' : 'pdf';
|
||||
const folder = getFolderFromFileType(fileType);
|
||||
|
||||
const uploadResponse = await uploadFile(file, folder);
|
||||
const actualPath = uploadResponse.data?.path_solution || '';
|
||||
|
||||
if (actualPath) {
|
||||
// Store the file info with the solution field
|
||||
file.uploadPath = actualPath;
|
||||
file.solutionId = fieldKey;
|
||||
file.type_solution = fileType;
|
||||
onFileUpload(file);
|
||||
NotifAlert({
|
||||
icon: 'success',
|
||||
title: 'Berhasil',
|
||||
message: `${file.name} berhasil diupload!`,
|
||||
});
|
||||
} else {
|
||||
NotifAlert({
|
||||
icon: 'error',
|
||||
title: 'Gagal',
|
||||
message: `Gagal mengupload ${file.name}`,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error uploading file:', error);
|
||||
NotifAlert({
|
||||
icon: 'error',
|
||||
title: 'Error',
|
||||
message: `Gagal mengupload ${file.name}. Silakan coba lagi.`,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const renderSolutionContent = () => {
|
||||
if (solutionType === 'text') {
|
||||
return (
|
||||
<Form.Item
|
||||
name={[fieldName, 'text']}
|
||||
rules={[{ required: true, message: 'Text solution wajib diisi!' }]}
|
||||
>
|
||||
<TextArea
|
||||
placeholder="Enter solution text"
|
||||
rows={3}
|
||||
disabled={isReadOnly}
|
||||
/>
|
||||
</Form.Item>
|
||||
);
|
||||
}
|
||||
|
||||
if (solutionType === 'file') {
|
||||
const currentFiles = fileList.filter(file => file.solutionId === fieldKey);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Form.Item
|
||||
name={[fieldName, 'file']}
|
||||
rules={[{ required: true, message: 'File solution wajib diupload!' }]}
|
||||
>
|
||||
<Upload
|
||||
beforeUpload={handleFileUpload}
|
||||
showUploadList={false}
|
||||
accept=".pdf,.jpg,.jpeg,.png,.gif"
|
||||
disabled={isReadOnly}
|
||||
>
|
||||
<Button
|
||||
icon={<UploadOutlined />}
|
||||
disabled={isReadOnly}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
Upload File (PDF/Image)
|
||||
</Button>
|
||||
</Upload>
|
||||
</Form.Item>
|
||||
|
||||
{currentFiles.length > 0 && (
|
||||
<div style={{ marginTop: 8 }}>
|
||||
{currentFiles.map((file, index) => (
|
||||
<div key={index} style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
padding: '4px 8px',
|
||||
border: '1px solid #d9d9d9',
|
||||
borderRadius: 4,
|
||||
marginBottom: 4
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<Text style={{ fontSize: 12 }}>{file.name}</Text>
|
||||
<Text type="secondary" style={{ fontSize: 10 }}>
|
||||
({(file.size / 1024).toFixed(1)} KB)
|
||||
</Text>
|
||||
</div>
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
icon={<EyeOutlined />}
|
||||
onClick={() => onFileView(file.uploadPath, file.type_solution)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
border: '1px solid #d9d9d9',
|
||||
borderRadius: 8,
|
||||
padding: 16,
|
||||
marginBottom: 16,
|
||||
backgroundColor: isReadOnly ? '#f5f5f5' : 'white'
|
||||
}}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
|
||||
<Text strong>Solution #{index + 1}</Text>
|
||||
<Space>
|
||||
<Form.Item
|
||||
name={[fieldName, 'name']}
|
||||
rules={[{ required: true, message: 'Solution name wajib diisi!' }]}
|
||||
style={{ margin: 0, width: 200 }}
|
||||
>
|
||||
<Input
|
||||
placeholder="Solution name"
|
||||
disabled={isReadOnly}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
|
||||
<Form.Item name={[fieldName, 'status']} valuePropName="checked" noStyle>
|
||||
<Switch
|
||||
disabled={isReadOnly}
|
||||
onChange={(checked) => {
|
||||
onStatusChange(fieldKey, checked);
|
||||
setCurrentStatus(checked);
|
||||
}}
|
||||
style={{
|
||||
backgroundColor: currentStatus ? '#23A55A' : '#bfbfbf'
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Text style={{ fontSize: 12, color: '#666' }}>
|
||||
{currentStatus ? 'Active' : 'Inactive'}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
{canRemove && !isReadOnly && (
|
||||
<Button
|
||||
type="text"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
onClick={onRemove}
|
||||
/>
|
||||
)}
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
<Form.Item
|
||||
name={[fieldName, 'type']}
|
||||
rules={[{ required: true, message: 'Solution type wajib diisi!' }]}
|
||||
>
|
||||
<Radio.Group
|
||||
onChange={(e) => onTypeChange(fieldKey, e.target.value)}
|
||||
disabled={isReadOnly}
|
||||
>
|
||||
<Radio value="text">Text Solution</Radio>
|
||||
<Radio value="file">File Solution</Radio>
|
||||
</Radio.Group>
|
||||
</Form.Item>
|
||||
|
||||
{renderSolutionContent()}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SolutionFieldNew;
|
||||
80
src/pages/master/brandDevice/component/SolutionForm.jsx
Normal file
80
src/pages/master/brandDevice/component/SolutionForm.jsx
Normal file
@@ -0,0 +1,80 @@
|
||||
import React from 'react';
|
||||
import { Form, Card, Typography, Divider, Button } from 'antd';
|
||||
import { PlusOutlined } from '@ant-design/icons';
|
||||
import SolutionFieldNew from './SolutionFieldNew';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
const SolutionForm = ({
|
||||
solutionForm,
|
||||
solutionFields,
|
||||
solutionTypes,
|
||||
solutionStatuses,
|
||||
fileList,
|
||||
solutionsToDelete,
|
||||
firstSolutionValid,
|
||||
onAddSolutionField,
|
||||
onRemoveSolutionField,
|
||||
onSolutionTypeChange,
|
||||
onSolutionStatusChange,
|
||||
onSolutionFileUpload,
|
||||
onFileView,
|
||||
isReadOnly = false,
|
||||
onAddSolution
|
||||
}) => {
|
||||
return (
|
||||
<div>
|
||||
<Form
|
||||
form={solutionForm}
|
||||
layout="vertical"
|
||||
initialValues={{
|
||||
solution_status_0: true,
|
||||
solution_type_0: 'text',
|
||||
}}
|
||||
>
|
||||
<Divider orientation="left">Solution Items</Divider>
|
||||
|
||||
{solutionFields.map((field, index) => (
|
||||
<SolutionFieldNew
|
||||
key={field.key}
|
||||
fieldKey={field.key}
|
||||
fieldName={field.name}
|
||||
index={index}
|
||||
solutionType={solutionTypes[field.key]}
|
||||
solutionStatus={solutionStatuses[field.key]}
|
||||
onTypeChange={onSolutionTypeChange}
|
||||
onStatusChange={onSolutionStatusChange}
|
||||
onRemove={() => onRemoveSolutionField(field.key)}
|
||||
onFileUpload={onSolutionFileUpload}
|
||||
onFileView={onFileView}
|
||||
fileList={fileList}
|
||||
isReadOnly={isReadOnly}
|
||||
canRemove={solutionFields.length > 1}
|
||||
/>
|
||||
))}
|
||||
|
||||
{!isReadOnly && (
|
||||
<>
|
||||
<Form.Item>
|
||||
<Button
|
||||
type="dashed"
|
||||
onClick={onAddSolutionField}
|
||||
icon={<PlusOutlined />}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
+ Add Solution
|
||||
</Button>
|
||||
</Form.Item>
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<Text type="secondary">
|
||||
* At least one solution is required for each error code.
|
||||
</Text>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SolutionForm;
|
||||
259
src/pages/master/brandDevice/component/SparepartForm.jsx
Normal file
259
src/pages/master/brandDevice/component/SparepartForm.jsx
Normal file
@@ -0,0 +1,259 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Form, Input, Button, Divider, Typography, Switch, Space, Card, Upload, message } from 'antd';
|
||||
import { PlusOutlined, DeleteOutlined, UploadOutlined } from '@ant-design/icons';
|
||||
import { uploadFile } from '../../../../api/file-uploads';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
const SparepartForm = ({
|
||||
sparepartForm,
|
||||
sparepartFields,
|
||||
onAddSparepartField,
|
||||
onRemoveSparepartField,
|
||||
onSparepartTypeChange,
|
||||
onSparepartStatusChange,
|
||||
onSparepartImageUpload,
|
||||
onSparepartImageRemove,
|
||||
sparepartImages = {},
|
||||
isReadOnly = false
|
||||
}) => {
|
||||
const [fieldStatuses, setFieldStatuses] = useState({});
|
||||
|
||||
// Watch form values for each field
|
||||
const getFieldValue = (fieldName) => {
|
||||
try {
|
||||
const values = sparepartForm?.getFieldsValue();
|
||||
return values?.sparepart_items?.[fieldName]?.status ?? true;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// Update field statuses when form changes
|
||||
const newStatuses = {};
|
||||
sparepartFields.forEach(field => {
|
||||
newStatuses[field.key] = getFieldValue(field.key);
|
||||
});
|
||||
setFieldStatuses(newStatuses);
|
||||
}, [sparepartFields, sparepartForm]);
|
||||
|
||||
const handleImageUpload = async (fieldKey, file) => {
|
||||
// Check if file is an image
|
||||
const isImage = file.type.startsWith('image/');
|
||||
if (!isImage) {
|
||||
message.error('You can only upload image files!');
|
||||
return Upload.LIST_IGNORE;
|
||||
}
|
||||
|
||||
// Check file size (max 2MB)
|
||||
const isLt2M = file.size / 1024 / 1024 < 2;
|
||||
if (!isLt2M) {
|
||||
message.error('Image must be smaller than 2MB!');
|
||||
return Upload.LIST_IGNORE;
|
||||
}
|
||||
|
||||
try {
|
||||
const fileExtension = file.name.split('.').pop().toLowerCase();
|
||||
const isImageFile = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(fileExtension);
|
||||
const fileType = isImageFile ? 'image' : 'pdf';
|
||||
const folder = 'images';
|
||||
|
||||
const uploadResponse = await uploadFile(file, folder);
|
||||
const imagePath = uploadResponse.data?.path_icon || uploadResponse.data?.path_solution || '';
|
||||
|
||||
if (imagePath) {
|
||||
onSparepartImageUpload && onSparepartImageUpload(fieldKey, {
|
||||
name: file.name,
|
||||
uploadPath: imagePath,
|
||||
fileExtension,
|
||||
isImage: isImageFile,
|
||||
size: file.size,
|
||||
});
|
||||
message.success(`${file.name} uploaded successfully!`);
|
||||
} else {
|
||||
message.error(`Failed to upload ${file.name}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error uploading image:', error);
|
||||
message.error(`Failed to upload ${file.name}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImageRemove = (fieldKey) => {
|
||||
onSparepartImageRemove && onSparepartImageRemove(fieldKey);
|
||||
};
|
||||
return (
|
||||
<div>
|
||||
<Text strong style={{ marginBottom: 16, display: 'block' }}>
|
||||
{isReadOnly ? 'Sparepart Details' : 'Tambah Sparepart'}
|
||||
</Text>
|
||||
|
||||
<Form
|
||||
form={sparepartForm}
|
||||
layout="vertical"
|
||||
initialValues={{
|
||||
sparepart_status_0: true,
|
||||
sparepart_type_0: 'required',
|
||||
}}
|
||||
>
|
||||
{/* Dynamic Sparepart Fields */}
|
||||
<Divider orientation="left">Sparepart Items</Divider>
|
||||
|
||||
{sparepartFields.map((field, index) => (
|
||||
<Card
|
||||
key={field.key}
|
||||
size="small"
|
||||
style={{ marginBottom: 16 }}
|
||||
title={
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<Text strong>Sparepart {index + 1}</Text>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
|
||||
<Form.Item name={[field.name, 'status']} valuePropName="checked" noStyle>
|
||||
<Switch
|
||||
disabled={isReadOnly}
|
||||
size="small"
|
||||
onChange={(checked) => {
|
||||
onSparepartStatusChange && onSparepartStatusChange(field.key, checked);
|
||||
setFieldStatuses(prev => ({ ...prev, [field.key]: checked }));
|
||||
}}
|
||||
style={{
|
||||
backgroundColor: fieldStatuses[field.key] ? '#23A55A' : '#bfbfbf'
|
||||
}}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Text style={{ fontSize: 12, color: '#666' }}>
|
||||
{fieldStatuses[field.key] ? 'Active' : 'Inactive'}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Form
|
||||
layout="vertical"
|
||||
style={{ border: 'none' }}
|
||||
>
|
||||
{/* Sparepart Name */}
|
||||
<Form.Item
|
||||
name={[field.name, 'name']}
|
||||
rules={[{ required: true, message: 'Sparepart name wajib diisi!' }]}
|
||||
>
|
||||
<Input
|
||||
placeholder="Enter sparepart name"
|
||||
disabled={isReadOnly}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{/* Description */}
|
||||
<Form.Item
|
||||
name={[field.name, 'description']}
|
||||
>
|
||||
<Input.TextArea
|
||||
placeholder="Enter sparepart description (optional)"
|
||||
rows={2}
|
||||
disabled={isReadOnly}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
{/* Image Upload */}
|
||||
<Form.Item label="Sparepart Image">
|
||||
{!isReadOnly ? (
|
||||
<Upload
|
||||
beforeUpload={(file) => handleImageUpload(field.key, file)}
|
||||
showUploadList={false}
|
||||
accept="image/*"
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
<Button icon={<UploadOutlined />} style={{ width: '100%' }}>
|
||||
Upload Sparepart Image
|
||||
</Button>
|
||||
</Upload>
|
||||
) : (
|
||||
<div style={{ padding: '8px 12px', border: '1px solid #d9d9d9', borderRadius: 4 }}>
|
||||
<Text type="secondary">No upload allowed</Text>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{sparepartImages[field.key] && (
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<img
|
||||
src={sparepartImages[field.key].uploadPath}
|
||||
alt="Sparepart Image"
|
||||
style={{
|
||||
width: 50,
|
||||
height: 50,
|
||||
objectFit: 'cover',
|
||||
border: '1px solid #d9d9d9',
|
||||
borderRadius: 4,
|
||||
}}
|
||||
/>
|
||||
<div>
|
||||
<Text style={{ fontSize: 12 }}>{sparepartImages[field.key].name}</Text>
|
||||
<br />
|
||||
<Text type="secondary" style={{ fontSize: 10 }}>
|
||||
Size: {(sparepartImages[field.key].size / 1024).toFixed(1)} KB
|
||||
</Text>
|
||||
</div>
|
||||
{!isReadOnly && (
|
||||
<Button
|
||||
type="text"
|
||||
danger
|
||||
size="small"
|
||||
onClick={() => handleImageRemove(field.key)}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Form.Item>
|
||||
|
||||
{/* Delete Button */}
|
||||
{!isReadOnly && sparepartFields.length > 1 && (
|
||||
<div style={{ textAlign: 'right' }}>
|
||||
<Button
|
||||
type="text"
|
||||
danger
|
||||
icon={<DeleteOutlined />}
|
||||
onClick={() => onRemoveSparepartField(field.key)}
|
||||
style={{
|
||||
borderColor: '#ff4d4f',
|
||||
color: '#ff4d4f'
|
||||
}}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Form>
|
||||
</Card>
|
||||
))}
|
||||
|
||||
{!isReadOnly && (
|
||||
<Form.Item>
|
||||
<Button
|
||||
type="dashed"
|
||||
onClick={() => onAddSparepartField()}
|
||||
icon={<PlusOutlined />}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
+ Add Sparepart
|
||||
</Button>
|
||||
</Form.Item>
|
||||
)}
|
||||
|
||||
{!isReadOnly && (
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<Text type="secondary">
|
||||
* Add at least one sparepart for this error code.
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SparepartForm;
|
||||
166
src/pages/master/brandDevice/hooks/solution.js
Normal file
166
src/pages/master/brandDevice/hooks/solution.js
Normal file
@@ -0,0 +1,166 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
export const useSolutionLogic = (solutionForm) => {
|
||||
const [solutionFields, setSolutionFields] = useState([
|
||||
{ name: ['solution_items', 0], key: 0 }
|
||||
]);
|
||||
const [solutionTypes, setSolutionTypes] = useState({ 0: 'text' });
|
||||
const [solutionStatuses, setSolutionStatuses] = useState({ 0: true });
|
||||
const [solutionsToDelete, setSolutionsToDelete] = useState([]);
|
||||
|
||||
const handleAddSolutionField = () => {
|
||||
const newKey = Date.now(); // Use timestamp for unique key
|
||||
const newField = { name: ['solution_items', newKey], key: newKey };
|
||||
|
||||
setSolutionFields(prev => [...prev, newField]);
|
||||
setSolutionTypes(prev => ({ ...prev, [newKey]: 'text' }));
|
||||
setSolutionStatuses(prev => ({ ...prev, [newKey]: true }));
|
||||
|
||||
// Set default values for the new field
|
||||
setTimeout(() => {
|
||||
solutionForm.setFieldValue(['solution_items', newKey, 'name'], '');
|
||||
solutionForm.setFieldValue(['solution_items', newKey, 'type'], 'text');
|
||||
solutionForm.setFieldValue(['solution_items', newKey, 'text'], '');
|
||||
}, 0);
|
||||
};
|
||||
|
||||
const handleRemoveSolutionField = (key) => {
|
||||
if (solutionFields.length <= 1) {
|
||||
return; // Keep at least one solution field
|
||||
}
|
||||
|
||||
setSolutionFields(prev => prev.filter(field => field.key !== key));
|
||||
|
||||
// Clean up type and status
|
||||
const newTypes = { ...solutionTypes };
|
||||
const newStatuses = { ...solutionStatuses };
|
||||
delete newTypes[key];
|
||||
delete newStatuses[key];
|
||||
|
||||
setSolutionTypes(newTypes);
|
||||
setSolutionStatuses(newStatuses);
|
||||
};
|
||||
|
||||
const handleSolutionTypeChange = (key, value) => {
|
||||
setSolutionTypes(prev => ({ ...prev, [key]: value }));
|
||||
};
|
||||
|
||||
const handleSolutionStatusChange = (key, value) => {
|
||||
setSolutionStatuses(prev => ({ ...prev, [key]: value }));
|
||||
};
|
||||
|
||||
const resetSolutionFields = () => {
|
||||
setSolutionFields([{ name: ['solution_items', 0], key: 0 }]);
|
||||
setSolutionTypes({ 0: 'text' });
|
||||
setSolutionStatuses({ 0: true });
|
||||
|
||||
// Reset form values
|
||||
solutionForm.resetFields();
|
||||
solutionForm.setFieldsValue({
|
||||
solution_status_0: true,
|
||||
solution_type_0: 'text',
|
||||
});
|
||||
};
|
||||
|
||||
const checkFirstSolutionValid = () => {
|
||||
const values = solutionForm.getFieldsValue();
|
||||
const firstSolution = values.solution_items?.[0];
|
||||
|
||||
if (!firstSolution || !firstSolution.name || firstSolution.name.trim() === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (solutionTypes[0] === 'text' && (!firstSolution.text || firstSolution.text.trim() === '')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const getSolutionData = () => {
|
||||
const values = solutionForm.getFieldsValue();
|
||||
|
||||
const result = solutionFields.map(field => {
|
||||
const key = field.key;
|
||||
// Access form values using the key from field.name (AntD stores with comma)
|
||||
const solutionPath = field.name.join(',');
|
||||
const solution = values[solutionPath];
|
||||
|
||||
const validSolution = solution && solution.name && solution.name.trim() !== '';
|
||||
|
||||
if (validSolution) {
|
||||
return {
|
||||
solution_name: solution.name || 'Default Solution',
|
||||
type_solution: solutionTypes[key] || 'text',
|
||||
text_solution: solution.text || '',
|
||||
path_solution: solution.file || '',
|
||||
is_active: solution.status !== false, // Use form value directly
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}).filter(Boolean);
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const setSolutionsForExistingRecord = (solutions, form) => {
|
||||
if (!solutions || solutions.length === 0) return;
|
||||
|
||||
const newFields = solutions.map((solution, index) => ({
|
||||
name: ['solution_items', solution.id || index],
|
||||
key: solution.id || index
|
||||
}));
|
||||
|
||||
setSolutionFields(newFields);
|
||||
|
||||
// Set solution values
|
||||
const solutionsValues = {};
|
||||
const newTypes = {};
|
||||
const newStatuses = {};
|
||||
|
||||
solutions.forEach((solution, index) => {
|
||||
const key = solution.id || index;
|
||||
solutionsValues[key] = {
|
||||
name: solution.solution_name || '',
|
||||
type: solution.type_solution || 'text',
|
||||
text: solution.text_solution || '',
|
||||
file: solution.path_solution || '',
|
||||
};
|
||||
newTypes[key] = solution.type_solution || 'text';
|
||||
newStatuses[key] = solution.is_active !== false;
|
||||
});
|
||||
|
||||
// Set all form values at once
|
||||
const formValues = {};
|
||||
Object.keys(solutionsValues).forEach(key => {
|
||||
const solution = solutionsValues[key];
|
||||
formValues[`solution_items,${key}`] = {
|
||||
name: solution.name,
|
||||
type: solution.type,
|
||||
text: solution.text,
|
||||
file: solution.file,
|
||||
status: solution.is_active !== false
|
||||
};
|
||||
});
|
||||
|
||||
form.setFieldsValue(formValues);
|
||||
setSolutionTypes(newTypes);
|
||||
setSolutionStatuses(newStatuses);
|
||||
};
|
||||
|
||||
return {
|
||||
solutionFields,
|
||||
solutionTypes,
|
||||
solutionStatuses,
|
||||
solutionsToDelete,
|
||||
firstSolutionValid: checkFirstSolutionValid(),
|
||||
handleAddSolutionField,
|
||||
handleRemoveSolutionField,
|
||||
handleSolutionTypeChange,
|
||||
handleSolutionStatusChange,
|
||||
resetSolutionFields,
|
||||
checkFirstSolutionValid,
|
||||
getSolutionData,
|
||||
setSolutionsForExistingRecord,
|
||||
};
|
||||
};
|
||||
115
src/pages/master/brandDevice/hooks/sparepart.js
Normal file
115
src/pages/master/brandDevice/hooks/sparepart.js
Normal file
@@ -0,0 +1,115 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
export const useSparepartLogic = (sparepartForm) => {
|
||||
const [sparepartFields, setSparepartFields] = useState([
|
||||
{ name: ['sparepart_items', 0], key: 0 }
|
||||
]);
|
||||
const [sparepartTypes, setSparepartTypes] = useState({ 0: 'required' });
|
||||
const [sparepartStatuses, setSparepartStatuses] = useState({ 0: true });
|
||||
|
||||
const handleAddSparepartField = () => {
|
||||
const newKey = Date.now(); // Use timestamp for unique key
|
||||
const newField = { name: ['sparepart_items', newKey], key: newKey };
|
||||
|
||||
setSparepartFields(prev => [...prev, newField]);
|
||||
setSparepartTypes(prev => ({ ...prev, [newKey]: 'required' }));
|
||||
setSparepartStatuses(prev => ({ ...prev, [newKey]: true }));
|
||||
|
||||
// Set default values for the new field
|
||||
setTimeout(() => {
|
||||
sparepartForm.setFieldValue(['sparepart_items', newKey, 'type'], 'required');
|
||||
sparepartForm.setFieldValue(['sparepart_items', newKey, 'quantity'], 1);
|
||||
}, 0);
|
||||
};
|
||||
|
||||
const handleRemoveSparepartField = (key) => {
|
||||
if (sparepartFields.length <= 1) {
|
||||
return; // Keep at least one sparepart field
|
||||
}
|
||||
|
||||
setSparepartFields(prev => prev.filter(field => field.key !== key));
|
||||
|
||||
// Clean up type and status
|
||||
const newTypes = { ...sparepartTypes };
|
||||
const newStatuses = { ...sparepartStatuses };
|
||||
delete newTypes[key];
|
||||
delete newStatuses[key];
|
||||
|
||||
setSparepartTypes(newTypes);
|
||||
setSparepartStatuses(newStatuses);
|
||||
};
|
||||
|
||||
const handleSparepartTypeChange = (key, value) => {
|
||||
setSparepartTypes(prev => ({ ...prev, [key]: value }));
|
||||
};
|
||||
|
||||
const handleSparepartStatusChange = (key, value) => {
|
||||
setSparepartStatuses(prev => ({ ...prev, [key]: value }));
|
||||
};
|
||||
|
||||
const resetSparepartFields = () => {
|
||||
setSparepartFields([{ name: ['sparepart_items', 0], key: 0 }]);
|
||||
setSparepartTypes({ 0: 'required' });
|
||||
setSparepartStatuses({ 0: true });
|
||||
|
||||
// Reset form values
|
||||
sparepartForm.resetFields();
|
||||
sparepartForm.setFieldsValue({
|
||||
sparepart_status_0: true,
|
||||
sparepart_type_0: 'required',
|
||||
});
|
||||
};
|
||||
|
||||
const getSparepartData = () => {
|
||||
const values = sparepartForm.getFieldsValue();
|
||||
return sparepartFields.map(field => {
|
||||
const key = field.key;
|
||||
const sparepartPath = field.name.join(',');
|
||||
const sparepart = values[sparepartPath];
|
||||
|
||||
return sparepart && sparepart.name && sparepart.name.trim() !== '' ? {
|
||||
name: sparepart.name || '',
|
||||
description: sparepart.description || '',
|
||||
is_active: sparepart.status !== false,
|
||||
} : null;
|
||||
}).filter(Boolean);
|
||||
};
|
||||
|
||||
const setSparepartForExistingRecord = (spareparts, form) => {
|
||||
if (!spareparts || spareparts.length === 0) return;
|
||||
|
||||
const newFields = spareparts.map((sparepart, index) => ({
|
||||
name: ['sparepart_items', sparepart.id || index],
|
||||
key: sparepart.id || index
|
||||
}));
|
||||
|
||||
setSparepartFields(newFields);
|
||||
|
||||
// Set sparepart values
|
||||
const formValues = {};
|
||||
Object.keys(spareparts).forEach(index => {
|
||||
const key = spareparts[index].id || index;
|
||||
const sparepart = spareparts[index];
|
||||
formValues[`sparepart_items,${key}`] = {
|
||||
name: sparepart.name || '',
|
||||
description: sparepart.description || '',
|
||||
status: sparepart.is_active !== false,
|
||||
};
|
||||
});
|
||||
|
||||
form.setFieldsValue(formValues);
|
||||
};
|
||||
|
||||
return {
|
||||
sparepartFields,
|
||||
sparepartTypes,
|
||||
sparepartStatuses,
|
||||
handleAddSparepartField,
|
||||
handleRemoveSparepartField,
|
||||
handleSparepartTypeChange,
|
||||
handleSparepartStatusChange,
|
||||
resetSparepartFields,
|
||||
getSparepartData,
|
||||
setSparepartForExistingRecord,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user