refactor: consolidate SolutionField components and remove obsolete files

This commit is contained in:
2025-11-24 21:44:44 +07:00
parent 3e384f89b1
commit 7e16bf63aa
4 changed files with 185 additions and 894 deletions

View File

@@ -1,394 +0,0 @@
import {
Form,
Divider,
Button,
Switch,
Input,
ConfigProvider,
Typography,
Upload,
message,
} from 'antd';
import { PlusOutlined, UploadOutlined, DeleteOutlined } from '@ant-design/icons';
import { NotifAlert } from '../../../../components/Global/ToastNotif';
import SolutionField from './SolutionField';
import { uploadFile, getFileUrl } from '../../../../api/file-uploads';
const { Text } = Typography;
const ErrorCodeForm = ({
errorCodeForm,
isErrorCodeFormReadOnly,
editingErrorCodeKey,
solutionFields,
solutionTypes,
solutionStatuses,
fileList,
solutionsToDelete,
firstSolutionValid,
onAddErrorCode,
onAddSolutionField,
onRemoveSolutionField,
onSolutionTypeChange,
onSolutionStatusChange,
onSolutionFileUpload,
onFileView,
onCreateNewErrorCode,
onResetForm,
errorCodes,
errorCodeIcon,
onErrorCodeIconUpload,
onErrorCodeIconRemove,
}) => {
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) {
// Extract folder and filename from the path
const pathParts = iconPath.split('/');
const folder = pathParts[0];
const filename = pathParts.slice(1).join('/');
onErrorCodeIconUpload({
name: file.name,
uploadPath: iconPath,
url: getFileUrl(folder, filename), // Use the same endpoint as file uploads
type_solution: fileType,
solutionId: 'icon',
});
message.success(`${file.name} uploaded successfully!`);
} else {
message.error('Failed to upload icon');
}
} catch (error) {
console.error('Error uploading icon:', error);
message.error('Failed to upload icon');
}
return false; // Prevent default upload behavior
};
const handleRemoveIcon = () => {
onErrorCodeIconRemove();
message.success('Icon removed');
};
const handleAddErrorCode = async () => {
try {
const values = await errorCodeForm.validateFields();
const solutions = [];
solutionFields.forEach((fieldId) => {
if (solutionsToDelete && solutionsToDelete.has(fieldId)) {
return;
}
const solutionName = values[`solution_name_${fieldId}`];
const textSolution = values[`text_solution_${fieldId}`];
const solutionStatus = values[`solution_status_${fieldId}`];
const filesForSolution = fileList.filter((file) => file.solutionId === fieldId);
const solutionType = values[`solution_type_${fieldId}`] || solutionTypes[fieldId];
if (solutionType === 'text') {
if (textSolution && textSolution.trim()) {
const solutionData = {
solution_name: solutionName || `Solution ${fieldId}`,
type_solution: 'text',
text_solution: textSolution.trim(),
path_solution: '',
is_active: solutionStatus !== undefined ? solutionStatus : true,
};
if (window.currentSolutionData && window.currentSolutionData[fieldId]) {
solutionData.brand_code_solution_id =
window.currentSolutionData[fieldId].brand_code_solution_id;
}
solutions.push(solutionData);
}
} else if (solutionType === 'file') {
filesForSolution.forEach((file) => {
const solutionData = {
solution_name:
solutionName ||
file.solution_name ||
file.name ||
`Solution ${fieldId}`,
type_solution:
file.type_solution ||
(file.type.startsWith('image/') ? 'image' : 'pdf'),
text_solution: '',
path_solution: file.uploadPath,
is_active: solutionStatus !== undefined ? solutionStatus : true,
};
if (window.currentSolutionData && window.currentSolutionData[fieldId]) {
solutionData.brand_code_solution_id =
window.currentSolutionData[fieldId].brand_code_solution_id;
}
solutions.push(solutionData);
});
}
});
if (solutions.length === 0) {
NotifAlert({
icon: 'warning',
title: 'Perhatian',
message:
'Setiap error code harus memiliki minimal 1 solution (text atau file)!',
});
return;
}
const newErrorCode = {
error_code: values.error_code,
error_code_name: values.error_code_name,
error_code_description: values.error_code_description,
error_code_color: values.error_code_color || '#000000',
path_icon: errorCodeIcon?.uploadPath || '',
status: values.status === undefined ? true : values.status,
solution: solutions,
key: editingErrorCodeKey || `temp-${Date.now()}`,
};
onAddErrorCode(newErrorCode);
} catch (error) {
NotifAlert({
icon: 'warning',
title: 'Perhatian',
message: 'Harap isi semua kolom wajib (error code + minimal 1 solution)!',
});
}
};
const handleResetForm = () => {
errorCodeForm.resetFields();
errorCodeForm.setFieldsValue({
status: true,
solution_status_0: true,
solution_type_0: 'text',
});
onResetForm();
};
return (
<>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 16,
}}
>
<Form.Item label="Status" style={{ margin: 0 }}>
<div style={{ display: 'flex', alignItems: 'center' }}>
<Form.Item name="status" valuePropName="checked" noStyle>
<Switch
style={{ backgroundColor: statusValue ? '#23A55A' : '#bfbfbf' }}
disabled={isErrorCodeFormReadOnly}
/>
</Form.Item>
<Text style={{ marginLeft: 8 }}>{statusValue ? 'Running' : 'Offline'}</Text>
</div>
</Form.Item>
{!isErrorCodeFormReadOnly && (
<ConfigProvider
theme={{
components: {
Button: {
defaultBg: '#23a55a',
defaultColor: '#FFFFFF',
defaultBorderColor: '#23a55a',
defaultHoverBg: '#209652',
defaultHoverColor: '#FFFFFF',
defaultHoverBorderColor: '#23a55a',
},
},
}}
>
<Button icon={<PlusOutlined />} onClick={handleAddErrorCode}>
{editingErrorCodeKey ? 'Update Error Code' : 'Tambah Error Code'}
</Button>
</ConfigProvider>
)}
</div>
<Form.Item
name="error_code"
label="Error Code"
rules={[{ required: true, message: 'Error Code wajib diisi' }]}
>
<Input disabled={isErrorCodeFormReadOnly} />
</Form.Item>
<Form.Item
name="error_code_name"
label="Error Code Name"
rules={[{ required: true, message: 'Error Code Name wajib diisi' }]}
>
<Input disabled={isErrorCodeFormReadOnly} />
</Form.Item>
<Form.Item label="Color & Icon">
<div style={{ display: 'flex', alignItems: 'center', gap: 24 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<Text style={{ fontSize: 14, minWidth: 40 }}>Icon:</Text>
{errorCodeIcon ? (
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<img
src={errorCodeIcon.url}
alt="Error Code Icon"
style={{
width: 32,
height: 32,
objectFit: 'cover',
border: '1px solid #d9d9d9',
borderRadius: 4,
}}
/>
<div>
<div style={{ fontSize: 11, color: '#666', marginBottom: 2 }}>
{errorCodeIcon.name.length > 15
? errorCodeIcon.name.substring(0, 15) + '...'
: errorCodeIcon.name}
</div>
{!isErrorCodeFormReadOnly && (
<Button
size="small"
type="text"
danger
icon={<DeleteOutlined />}
onClick={handleRemoveIcon}
style={{ height: 20, padding: '0 4px', fontSize: 10 }}
>
Remove
</Button>
)}
</div>
</div>
) : (
<Upload
accept="image/*"
beforeUpload={handleIconUpload}
showUploadList={false}
disabled={isErrorCodeFormReadOnly}
>
<Button
size="small"
icon={<UploadOutlined />}
disabled={isErrorCodeFormReadOnly}
style={{ height: 32 }}
>
Upload
</Button>
</Upload>
)}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<Text style={{ fontSize: 14, minWidth: 40 }}>Color:</Text>
<Form.Item name="error_code_color" noStyle>
<Input
type="color"
disabled={isErrorCodeFormReadOnly}
style={{
width: 50,
height: 32,
border: '1px solid #d9d9d9',
borderRadius: 4,
}}
/>
</Form.Item>
</div>
</div>
<div style={{ fontSize: 12, color: '#999', marginTop: 4 }}>
Choose color and upload icon (max 2MB, JPG/PNG/GIF)
</div>
</Form.Item>
<Form.Item
name="error_code_description"
label="Error Code Description"
rules={[{ required: true, message: 'Error Code Description wajib diisi' }]}
>
<Input.TextArea disabled={isErrorCodeFormReadOnly} />
</Form.Item>
<Divider>Solutions</Divider>
{solutionFields.map((fieldId, index) => (
<SolutionField
key={fieldId}
fieldId={fieldId}
index={index}
solutionType={solutionTypes[fieldId]}
solutionStatus={solutionStatuses[fieldId]}
isReadOnly={isErrorCodeFormReadOnly}
fileList={fileList.filter((file) => file.solutionId === fieldId)}
onRemove={() => onRemoveSolutionField(fieldId)}
onSolutionTypeChange={(type) => onSolutionTypeChange(fieldId, type)}
onSolutionStatusChange={(status) => onSolutionStatusChange(fieldId, status)}
onFileUpload={onSolutionFileUpload}
currentSolutionData={window.currentSolutionData?.[fieldId] || null}
onFileView={onFileView}
errorCodeForm={errorCodeForm}
/>
))}
{!isErrorCodeFormReadOnly && (
<Form.Item style={{ textAlign: 'center' }}>
<Button
icon={<PlusOutlined />}
onClick={onAddSolutionField}
style={{ width: '100%' }}
>
Add More Solution
</Button>
</Form.Item>
)}
{!isErrorCodeFormReadOnly && editingErrorCodeKey && (
<Form.Item style={{ textAlign: 'right', marginTop: 16 }}>
<Button onClick={handleResetForm}>Kembali</Button>
</Form.Item>
)}
{isErrorCodeFormReadOnly && editingErrorCodeKey && (
<Form.Item style={{ textAlign: 'right', marginTop: 16 }}>
<Button onClick={handleResetForm}>Kembali</Button>
</Form.Item>
)}
</>
);
};
export default ErrorCodeForm;

View File

@@ -1,94 +1,79 @@
import React, { useEffect } from 'react';
import { Form, Input, Button, Switch, Radio, Upload, Typography } from 'antd';
import { DeleteOutlined, UploadOutlined } from '@ant-design/icons';
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, NotifOk } from '../../../../components/Global/ToastNotif';
import { NotifAlert } from '../../../../components/Global/ToastNotif';
const { Text } = Typography;
const { TextArea } = Input;
const SolutionField = ({
fieldId,
const SolutionFieldNew = ({
fieldKey,
fieldName,
index,
solutionType,
solutionStatus,
isReadOnly,
fileList,
isReadOnly = false,
canRemove = true,
onTypeChange,
onStatusChange,
onRemove,
onSolutionTypeChange,
onSolutionStatusChange,
onFileUpload,
currentSolutionData,
onFileView,
errorCodeForm,
fileList = []
}) => {
// Watch the solution status from the form
const watchedStatus = Form.useWatch(`solution_status_${fieldId}`, errorCodeForm);
useEffect(() => {
if (currentSolutionData && errorCodeForm) {
if (currentSolutionData.solution_name) {
errorCodeForm.setFieldValue(
`solution_name_${fieldId}`,
currentSolutionData.solution_name
);
}
if (currentSolutionData.type_solution === 'text' && currentSolutionData.text_solution) {
errorCodeForm.setFieldValue(
`text_solution_${fieldId}`,
currentSolutionData.text_solution
);
}
if (currentSolutionData.type_solution) {
const formValue =
currentSolutionData.type_solution === 'image' ||
currentSolutionData.type_solution === 'pdf'
? 'file'
: currentSolutionData.type_solution;
errorCodeForm.setFieldValue(`solution_type_${fieldId}`, formValue);
}
// Only set status if it's not already set to prevent overwriting user changes
const currentStatus = errorCodeForm.getFieldValue(`solution_status_${fieldId}`);
if (currentSolutionData.is_active !== undefined && currentStatus === undefined) {
errorCodeForm.setFieldValue(
`solution_status_${fieldId}`,
currentSolutionData.is_active
);
}
}
}, [currentSolutionData, fieldId, errorCodeForm]);
const handleBeforeUpload = async (file) => {
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 Upload.LIST_IGNORE;
}
const [currentStatus, setCurrentStatus] = useState(solutionStatus ?? true);
// Watch form values
const getFieldValue = () => {
try {
// Upload file immediately to get path
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.solution_name = file.name;
file.solutionId = fieldId;
file.solutionId = fieldKey;
file.type_solution = fileType;
onFileUpload(file);
NotifOk({
NotifAlert({
icon: 'success',
title: 'Berhasil',
message: `${file.name} berhasil diupload!`,
@@ -108,208 +93,151 @@ const SolutionField = ({
message: `Gagal mengupload ${file.name}. Silakan coba lagi.`,
});
}
};
return false;
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
data-solution-id={fieldId}
style={{
marginBottom: 24,
padding: 16,
border: '1px solid #d9d9d9',
borderRadius: 8,
transition: 'all 0.3s ease',
}}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 12,
}}
>
<Text strong>Solution {index + 1}</Text>
<Button
type="text"
danger
size="small"
icon={<DeleteOutlined />}
onClick={() => onRemove(fieldId)}
disabled={isReadOnly}
style={{
borderColor: '#ff4d4f',
color: '#ff4d4f'
}}
/>
</div>
<Form.Item name={`solution_name_${fieldId}`} label="Solution Name">
<Input placeholder="Enter solution name" disabled={isReadOnly} />
</Form.Item>
<Form.Item label="Status">
<div style={{ display: 'flex', alignItems: 'center' }}>
<Form.Item name={`solution_status_${fieldId}`} valuePropName="checked" noStyle>
<Switch
<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}
onChange={(checked) => {
onSolutionStatusChange(fieldId, checked);
}}
style={{
backgroundColor: (watchedStatus ?? true) ? '#23A55A' : '#bfbfbf',
}}
/>
</Form.Item>
<Text style={{ marginLeft: 8 }}>
{(watchedStatus ?? true) ? 'Active' : 'Inactive'}
</Text>
</div>
</Form.Item>
<Form.Item label="Solution Type">
<Form.Item name={`solution_type_${fieldId}`} noStyle>
<Radio.Group
onChange={(e) => {
onSolutionTypeChange(fieldId, e.target.value);
}}
disabled={isReadOnly}
>
<Radio value="text">Text Solution</Radio>
<Radio value="file">File Upload</Radio>
</Radio.Group>
</Form.Item>
</Form.Item>
<Form.Item
shouldUpdate={(prevValues, currentValues) =>
prevValues[`solution_type_${fieldId}`] !==
currentValues[`solution_type_${fieldId}`]
}
noStyle
>
{({ getFieldValue }) => {
const currentType = getFieldValue(`solution_type_${fieldId}`) || 'text';
const displayType =
currentType === 'file' && currentSolutionData
? currentSolutionData.type_solution === 'image'
? 'image'
: currentSolutionData.type_solution === 'pdf'
? 'pdf'
: 'file'
: currentType;
return displayType === 'text' ? (
<Form.Item name={`text_solution_${fieldId}`} label="Text Solution">
<Input.TextArea
placeholder="Enter text solution"
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<Form.Item name={[fieldName, 'status']} valuePropName="checked" noStyle>
<Switch
disabled={isReadOnly}
rows={4}
onChange={(checked) => {
onStatusChange(fieldKey, checked);
setCurrentStatus(checked);
}}
style={{
backgroundColor: currentStatus ? '#23A55A' : '#bfbfbf'
}}
/>
</Form.Item>
) : (
<>
{/* Show existing file info for both preview and edit mode */}
{currentSolutionData &&
currentSolutionData.type_solution !== 'text' &&
currentSolutionData.path_solution && (
<Form.Item label="Current Document">
{(() => {
const solution = currentSolutionData;
const fileName =
solution.file_upload_name ||
solution.path_solution?.split('/')[1] ||
'File';
const fileType = solution.type_solution;
<Text style={{ fontSize: 12, color: '#666' }}>
{currentStatus ? 'Active' : 'Inactive'}
</Text>
</div>
if (fileType !== 'text' && solution.path_solution) {
return (
<div
style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
marginBottom: '8px',
}}
>
<Text>
{fileType === 'image'
? '[Image]'
: '[Document]'}{' '}
{fileName}
</Text>
<Button
type="link"
size="small"
onClick={() =>
onFileView(
solution.path_solution,
solution.type_solution
)
}
style={{
padding: 0,
height: 'auto',
fontSize: '12px',
}}
>
View Document
</Button>
</div>
);
}
return null;
})()}
</Form.Item>
)}
{canRemove && !isReadOnly && (
<Button
type="text"
danger
icon={<DeleteOutlined />}
onClick={onRemove}
/>
)}
</Space>
</div>
<Form.Item label="Upload File">
<Upload
multiple={true}
accept=".pdf,.jpg,.jpeg,.png,.gif"
disabled={isReadOnly}
fileList={[
...fileList.filter((file) => file.solutionId === fieldId),
// Add existing file to fileList if it exists
...(currentSolutionData &&
currentSolutionData.type_solution !== 'text' &&
currentSolutionData.path_solution
? [
{
uid: `existing-${fieldId}`,
name:
currentSolutionData.file_upload_name ||
currentSolutionData.path_solution?.split(
'/'
)[1] ||
'File',
status: 'done',
url: null, // We'll use the path_solution for viewing
solutionId: fieldId,
type_solution:
currentSolutionData.type_solution,
uploadPath: currentSolutionData.path_solution,
existingFile: true,
},
]
: []),
]}
onRemove={(file) => {}}
beforeUpload={handleBeforeUpload}
>
<Button icon={<UploadOutlined />} disabled={isReadOnly}>
Click to Upload (File or Image)
</Button>
</Upload>
</Form.Item>
</>
);
}}
<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 SolutionField;
export default SolutionFieldNew;

View File

@@ -1,243 +0,0 @@
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;

View File

@@ -1,7 +1,7 @@
import React from 'react';
import { Form, Card, Typography, Divider, Button } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import SolutionFieldNew from './SolutionFieldNew';
import SolutionFieldNew from './SolutionField';
const { Text } = Typography;
@@ -20,7 +20,7 @@ const SolutionForm = ({
onSolutionFileUpload,
onFileView,
isReadOnly = false,
onAddSolution
onAddSolution,
}) => {
return (
<div>
@@ -77,4 +77,4 @@ const SolutionForm = ({
);
};
export default SolutionForm;
export default SolutionForm;