repair: brandDevice sparepart integration

This commit is contained in:
2025-12-02 11:10:36 +07:00
parent 1c2ddca9d4
commit 1797058526
15 changed files with 1544 additions and 1279 deletions

View File

@@ -9,7 +9,7 @@ import {
Row,
Col,
Card,
ConfigProvider,
Spin,
Table,
Tag,
Space,
@@ -19,44 +19,44 @@ import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb';
import { createBrand } from '../../../api/master-brand';
import BrandForm from './component/BrandForm';
import ErrorCodeSimpleForm from './component/ErrorCodeSimpleForm';
import ErrorCodeListModal from './component/ErrorCodeListModal';
import FormActions from './component/FormActions';
import SolutionForm from './component/SolutionForm';
import SparepartForm from './component/SparepartForm';
import FormActions from './component/FormActions';
import ListErrorCode from './component/ListErrorCode';
import { useErrorCodeLogic } from './hooks/errorCode';
import { useSolutionLogic } from './hooks/solution';
import { useSparepartLogic } from './hooks/sparepart';
import { uploadFile, getFolderFromFileType } from '../../../api/file-uploads';
import { EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { EditOutlined, DeleteOutlined, EyeOutlined, PlusOutlined } from '@ant-design/icons';
import { useBrandDeviceLogic } from './hooks/useBrandDeviceLogic';
const { Title } = Typography;
const { Step } = Steps;
const defaultData = {
brand_name: '',
brand_type: '',
brand_model: '',
brand_manufacture: '',
is_active: true,
brand_code: '',
};
const AddBrandDevice = () => {
const navigate = useNavigate();
const { setBreadcrumbItems } = useBreadcrumb();
const [brandForm] = Form.useForm();
const [errorCodeForm] = Form.useForm();
const [solutionForm] = Form.useForm();
const [sparepartForm] = Form.useForm();
const [confirmLoading, setConfirmLoading] = useState(false);
const [currentStep, setCurrentStep] = useState(0);
const [fileList, setFileList] = useState([]);
const [isErrorCodeFormReadOnly, setIsErrorCodeFormReadOnly] = useState(false);
const [editingErrorCodeKey, setEditingErrorCodeKey] = useState(null);
const [loading, setLoading] = useState(false);
const [formData, setFormData] = useState(defaultData);
const [formData, setFormData] = useState({
brand_name: '',
brand_type: '',
brand_model: '',
brand_manufacture: '',
is_active: true,
});
const [errorCodes, setErrorCodes] = useState([]);
const [pendingErrorCodes, setPendingErrorCodes] = useState([]);
const [errorCodeIcon, setErrorCodeIcon] = useState(null);
const [solutionForm] = Form.useForm();
const [selectedSparepartIds, setSelectedSparepartIds] = useState([]);
const [editingErrorCodeKey, setEditingErrorCodeKey] = useState(null);
const [isErrorCodeFormReadOnly, setIsErrorCodeFormReadOnly] = useState(false);
const { errorCodeFields, addErrorCode, removeErrorCode, editErrorCode } = useErrorCodeLogic(
errorCodeForm,
[]
);
const {
solutionFields,
@@ -64,47 +64,21 @@ const AddBrandDevice = () => {
solutionStatuses,
solutionsToDelete,
firstSolutionValid,
checkFirstSolutionValid,
handleAddSolutionField,
handleRemoveSolutionField,
handleSolutionTypeChange,
handleSolutionStatusChange,
resetSolutionFields,
checkFirstSolutionValid,
getSolutionData,
setSolutionsForExistingRecord,
} = useSolutionLogic(solutionForm);
// For spareparts, we'll use the local state directly since it's just an array of IDs
const handleSparepartChange = (values) => {
setSelectedSparepartIds(values || []);
};
const resetSparepartFields = () => {
setSelectedSparepartIds([]);
};
const getSparepartData = () => {
return selectedSparepartIds;
};
const setSparepartsForExistingRecord = (sparepartData) => {
if (!sparepartData) {
setSelectedSparepartIds([]);
return;
}
if (Array.isArray(sparepartData)) {
setSelectedSparepartIds(sparepartData);
} else if (typeof sparepartData === 'object' && sparepartData.spareparts) {
setSelectedSparepartIds(sparepartData.spareparts || []);
} else {
setSelectedSparepartIds(sparepartData.map(sp => sp.sparepart_id || sp.brand_sparepart_id || sp.id).filter(id => id));
}
};
useEffect(() => {
setBreadcrumbItems([
{ title: <span style={{ fontSize: '14px', fontWeight: 'bold' }}> Master</span> },
{
title: <span style={{ fontSize: '14px', fontWeight: 'bold' }}> Master</span>
},
{
title: (
<span
@@ -131,7 +105,16 @@ const AddBrandDevice = () => {
const handleNextStep = async () => {
try {
await brandForm.validateFields();
const currentFormData = await brandForm.validateFields();
setFormData({
brand_name: currentFormData.brand_name,
brand_type: currentFormData.brand_type || '',
brand_model: currentFormData.brand_model || '',
brand_manufacture: currentFormData.brand_manufacture || '',
is_active: currentFormData.is_active,
});
setCurrentStep(1);
} catch (error) {
NotifAlert({
@@ -145,47 +128,33 @@ const AddBrandDevice = () => {
const handleFinish = async () => {
setConfirmLoading(true);
try {
// Validation: Ensure at least one error code
if (errorCodes.length === 0) {
NotifAlert({
icon: 'warning',
title: 'Perhatian',
message: 'Setidaknya tambahkan 1 error code!',
});
setConfirmLoading(false);
return;
}
const transformedErrorCodes = errorCodes.map((ec) => ({
const transformedErrorCodes = pendingErrorCodes.length > 0 ? pendingErrorCodes.map(ec => ({
error_code: ec.error_code,
error_code_name: ec.error_code_name || '',
error_code_name: ec.error_code_name,
error_code_description: ec.error_code_description || '',
error_code_color: ec.error_code_color || '#000000',
error_code_color: ec.error_code_color || '#ad4141ff',
path_icon: ec.path_icon || '',
is_active: ec.status !== undefined ? ec.status : true,
solution: (ec.solution || []).map((sol) => ({
solution: (ec.solution || []).map(sol => ({
solution_name: sol.solution_name,
type_solution: sol.type_solution,
text_solution: sol.text_solution || '',
path_solution: sol.path_solution || '',
is_active: sol.is_active !== false,
})),
}));
is_active: sol.is_active
}))
})) : [];
const sparepartData = getSparepartData();
const finalFormData = {
const brandData = {
brand_name: formData.brand_name,
brand_type: formData.brand_type || '',
brand_model: formData.brand_model || '',
brand_manufacture: formData.brand_manufacture,
brand_manufacture: formData.brand_manufacture || '',
is_active: formData.is_active,
spareparts: sparepartData,
spareparts: selectedSparepartIds,
error_code: transformedErrorCodes,
};
console.log('Final form data:', finalFormData); // Debug log
const response = await createBrand(finalFormData);
const response = await createBrand(brandData);
if (response && (response.statusCode === 200 || response.statusCode === 201)) {
NotifOk({
@@ -202,7 +171,6 @@ const AddBrandDevice = () => {
});
}
} catch (error) {
console.error('Finish Error:', error);
NotifAlert({
icon: 'error',
title: 'Gagal',
@@ -221,60 +189,46 @@ const AddBrandDevice = () => {
error_code_color: record.error_code_color,
status: record.status,
});
setFileList(record.fileList || []);
setErrorCodeIcon(record.errorCodeIcon || null);
setIsErrorCodeFormReadOnly(true);
setEditingErrorCodeKey(null);
setEditingErrorCodeKey(record.key);
if (record.solution && record.solution.length > 0) {
setSolutionsForExistingRecord(record.solution, solutionForm);
}
if (record.sparepart && record.sparepart.length > 0) {
setSparepartsForExistingRecord(record.sparepart);
} else {
resetSolutionFields();
}
};
const handleEditErrorCode = (record) => {
// Prevent infinite loop
if (editingErrorCodeKey === record.key) {
return;
}
errorCodeForm.setFieldsValue({
error_code: record.error_code,
error_code_name: record.error_code_name,
error_code_description: record.error_code_description,
error_code_color: record.error_code_color || '#000000',
status: record.status !== false,
error_code_color: record.error_code_color,
status: record.status,
});
setFileList(record.fileList || []);
setErrorCodeIcon(record.errorCodeIcon || null);
setIsErrorCodeFormReadOnly(false);
setEditingErrorCodeKey(record.key);
if (record.solution && record.solution.length > 0) {
// Reset solution fields first
resetSolutionFields();
// Then load new solutions
setTimeout(() => {
setSolutionsForExistingRecord(record.solution, solutionForm);
}, 0);
} else {
resetSolutionFields();
setSolutionsForExistingRecord(record.solution, solutionForm);
}
if (record.sparepart && record.sparepart.length > 0) {
setSparepartsForExistingRecord(record.sparepart);
const formElement = document.querySelector('.ant-form');
if (formElement) {
formElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
};
const handleAddErrorCode = async () => {
try {
const formValues = errorCodeForm.getFieldsValue();
const errorCodeValues = await errorCodeForm.validateFields();
const solutionData = getSolutionData();
// Validation
if (!formValues.error_code || !formValues.error_code_name) {
// Validate error code fields
if (!errorCodeValues.error_code || !errorCodeValues.error_code_name) {
NotifAlert({
icon: 'warning',
title: 'Perhatian',
@@ -283,10 +237,8 @@ const AddBrandDevice = () => {
return;
}
// Validate at least 1 solution
const solutions = getSolutionData();
if (solutions.length === 0) {
// Validate solution data
if (!solutionData || solutionData.length === 0) {
NotifAlert({
icon: 'warning',
title: 'Perhatian',
@@ -295,31 +247,48 @@ const AddBrandDevice = () => {
return;
}
// Validate each solution has name
const invalidSolution = solutionData.find(sol => !sol.solution_name || sol.solution_name.trim() === '');
if (invalidSolution) {
NotifAlert({
icon: 'warning',
title: 'Perhatian',
message: 'Setiap solution harus memiliki nama!',
});
return;
}
const newErrorCode = {
key: Date.now(),
error_code: formValues.error_code,
error_code_name: formValues.error_code_name || '',
error_code_description: formValues.error_code_description || '',
error_code_color: formValues.error_code_color || '#000000',
error_code: errorCodeValues.error_code,
error_code_name: errorCodeValues.error_code_name,
error_code_description: errorCodeValues.error_code_description,
error_code_color: errorCodeValues.error_code_color || '#000000',
path_icon: errorCodeIcon?.uploadPath || '',
status: formValues.status !== false,
is_active: errorCodeValues.status === undefined ? true : errorCodeValues.status,
solution: solutionData,
errorCodeIcon: errorCodeIcon,
solution: solutions,
key: editingErrorCodeKey || `temp-${Date.now()}`,
};
let updatedPendingErrorCodes;
if (editingErrorCodeKey) {
const updatedCodes = errorCodes.map((item) =>
item.key === editingErrorCodeKey ? newErrorCode : item
);
setErrorCodes(updatedCodes);
updatedPendingErrorCodes = pendingErrorCodes.map((item) => {
if (item.key === editingErrorCodeKey) {
return {
...item,
...newErrorCode,
error_code_id: item.error_code_id || newErrorCode.error_code_id,
};
}
return item;
});
NotifOk({
icon: 'success',
title: 'Berhasil',
message: 'Error code berhasil diupdate!',
});
} else {
const updatedCodes = [...errorCodes, newErrorCode];
setErrorCodes(updatedCodes);
updatedPendingErrorCodes = [...pendingErrorCodes, newErrorCode];
NotifOk({
icon: 'success',
title: 'Berhasil',
@@ -327,15 +296,17 @@ const AddBrandDevice = () => {
});
}
// Reset all forms
resetErrorCodeForm();
resetSolutionFields();
setPendingErrorCodes(updatedPendingErrorCodes);
setErrorCodes(updatedPendingErrorCodes);
setTimeout(() => {
resetErrorCodeForm();
}, 100);
} catch (error) {
console.error('Error adding error code:', error);
NotifAlert({
icon: 'error',
title: 'Error',
message: 'Gagal menambahkan error code',
icon: 'warning',
title: 'Perhatian',
message: 'Harap isi semua kolom wajib (error code + minimal 1 solution)!',
});
}
};
@@ -344,22 +315,14 @@ const AddBrandDevice = () => {
errorCodeForm.resetFields();
errorCodeForm.setFieldsValue({
status: true,
solution_status_0: true,
solution_type_0: 'text',
});
setFileList([]);
setErrorCodeIcon(null);
resetSolutionFields();
resetSparepartFields();
setIsErrorCodeFormReadOnly(false);
setEditingErrorCodeKey(null);
};
const handleCreateNewErrorCode = () => {
resetErrorCodeForm();
};
const handleDeleteErrorCode = (key) => {
const handleDeleteErrorCode = async (key) => {
if (errorCodes.length <= 1) {
NotifAlert({
icon: 'warning',
@@ -369,7 +332,8 @@ const AddBrandDevice = () => {
return;
}
setErrorCodes(errorCodes.filter((item) => item.key !== key));
const updatedErrorCodes = errorCodes.filter((item) => item.key !== key);
setErrorCodes(updatedErrorCodes);
NotifOk({
icon: 'success',
title: 'Berhasil',
@@ -377,75 +341,12 @@ const AddBrandDevice = () => {
});
};
const handleFileView = (pathSolution, fileType) => {
const filePath = pathSolution || '';
if (!filePath) return;
const parts = filePath.split('/');
if (parts.length < 2) return;
const [folder, filename] = parts;
const encodedFileName = encodeURIComponent(filename);
const navigationPath = `/master/brand-device/view/temp/files/${folder}/${encodedFileName}`;
navigate(navigationPath);
};
const handleSolutionFileUpload = 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) {
file.uploadPath = actualPath;
file.solution_name = file.name;
file.solutionId = solutionFields[0];
file.type_solution = fileType;
setFileList((prevList) => [...prevList, file]);
NotifOk({
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 handleFileRemove = (file) => {
const newFileList = fileList.filter((item) => item.uid !== file.uid);
setFileList(newFileList);
const handleCreateNewErrorCode = () => {
resetErrorCodeForm();
resetSolutionFields();
setErrorCodeIcon(null);
setIsErrorCodeFormReadOnly(false);
setEditingErrorCodeKey(null);
};
const handleErrorCodeIconUpload = (iconData) => {
@@ -466,6 +367,9 @@ const AddBrandDevice = () => {
setFormData((prev) => ({ ...prev, ...allValues }))
}
isEdit={false}
selectedSparepartIds={selectedSparepartIds}
onSparepartChange={setSelectedSparepartIds}
showSparepartSection={true}
/>
);
}
@@ -473,10 +377,22 @@ const AddBrandDevice = () => {
if (currentStep === 1) {
return (
<>
<Row gutter={16} style={{ marginBottom: 24 }}>
{/* Error Code Form Column */}
<Col span={8}>
<Card size="small" title="Error Code">
<Row gutter={24}>
<Col span={6}>
<Card
title={
<Title level={5} style={{ margin: 0 }}>
{isErrorCodeFormReadOnly
? editingErrorCodeKey
? 'View Error Code'
: 'Error Code Form'
: editingErrorCodeKey
? 'Edit Error Code'
: 'Error Code'}
</Title>
}
size="small"
>
<Form
form={errorCodeForm}
layout="vertical"
@@ -495,10 +411,15 @@ const AddBrandDevice = () => {
</Form>
</Card>
</Col>
{/* Solution Form Column */}
<Col span={8}>
<Card size="small" title="Solutions">
<Col span={6}>
<Card
title={
<Title level={5} style={{ margin: 0 }}>
Solutions
</Title>
}
size="small"
>
<Form
form={solutionForm}
layout="vertical"
@@ -513,132 +434,46 @@ const AddBrandDevice = () => {
solutionFields={solutionFields}
solutionTypes={solutionTypes}
solutionStatuses={solutionStatuses}
fileList={fileList}
solutionsToDelete={solutionsToDelete}
firstSolutionValid={firstSolutionValid}
onAddSolutionField={handleAddSolutionField}
onRemoveSolutionField={handleRemoveSolutionField}
onSolutionTypeChange={handleSolutionTypeChange}
onSolutionStatusChange={handleSolutionStatusChange}
onSolutionFileUpload={handleSolutionFileUpload}
onFileView={handleFileView}
checkFirstSolutionValid={checkFirstSolutionValid}
isReadOnly={isErrorCodeFormReadOnly}
/>
</Form>
</Card>
</Col>
<Col span={8}>
<Card size="small" title="Spareparts">
<Form
form={sparepartForm}
layout="vertical"
>
<SparepartForm
sparepartForm={sparepartForm}
selectedSparepartIds={selectedSparepartIds}
onSparepartChange={handleSparepartChange}
isReadOnly={isErrorCodeFormReadOnly}
/>
</Form>
</Card>
</Col>
{/* Error Codes Table Column */}
<Col span={24} style={{ marginTop: 16 }}>
<Card size="small" title={`Error Codes (${errorCodes.length})`}>
<Table
dataSource={errorCodes}
columns={[
{
title: 'Error Code',
dataIndex: 'error_code',
key: 'error_code',
width: '25%',
},
{
title: 'Sol',
key: 'Sol',
width: '10%',
align: 'center',
render: (_, record) => {
const solutionCount = record.solution
? record.solution.length
: 0;
return (
<Tag
color={solutionCount > 0 ? 'green' : 'red'}
>
{solutionCount} Sol
</Tag>
);
},
},
{
title: 'Status',
dataIndex: 'status',
key: 'status',
width: '20%',
align: 'center',
render: (_, { status }) => (
<Tag color={status ? 'green' : 'red'}>
{status ? 'Active' : 'Inactive'}
</Tag>
),
},
{
title: 'Action',
key: 'action',
align: 'center',
width: '15%',
render: (_, record) => (
<Space>
<Button
type="text"
style={{ borderColor: '#1890ff' }}
size="small"
icon={
<EyeOutlined
style={{ color: '#1890ff' }}
/>
}
onClick={() =>
handlePreviewErrorCode(record)
}
/>
<Button
type="text"
style={{ borderColor: '#faad14' }}
size="small"
icon={
<EditOutlined
style={{ color: '#faad14' }}
/>
}
onClick={() => handleEditErrorCode(record)}
/>
<Button
type="text"
danger
style={{ borderColor: 'red' }}
size="small"
icon={<DeleteOutlined />}
onClick={() =>
handleDeleteErrorCode(record.key)
}
/>
</Space>
),
},
]}
rowKey="key"
pagination={{
pageSize: 10,
showSizeChanger: false,
hideOnSinglePage: true,
}}
size="small"
scroll={{ y: 300 }}
<Col span={12}>
<Card
title={
<Title level={5} style={{ margin: 0 }}>
Error Codes ({errorCodes.length})
</Title>
}
size="small"
>
<ListErrorCode
errorCodes={errorCodes}
loading={loading}
onPreview={handlePreviewErrorCode}
onEdit={handleEditErrorCode}
onDelete={handleDeleteErrorCode}
/>
<div style={{ marginTop: 16, textAlign: 'center' }}>
<Button
type="dashed"
onClick={handleCreateNewErrorCode}
style={{
width: '100%',
borderColor: '#23A55A',
color: '#23A55A'
}}
>
+ Add New Error Code
</Button>
</div>
</Card>
</Col>
</Row>
@@ -657,7 +492,37 @@ const AddBrandDevice = () => {
<Step title="Brand Device Details" />
<Step title="Error Codes & Solutions" />
</Steps>
<div style={{ marginTop: 24 }}>{renderStepContent()}</div>
<div style={{ position: 'relative' }}>
{loading && (
<div
style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(255, 255, 255, 0.6)',
backdropFilter: 'blur(0.8px)',
filter: 'blur(0.5px)',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
zIndex: 10,
borderRadius: '8px',
}}
>
<Spin size="large" />
</div>
)}
<div
style={{
filter: loading ? 'blur(0.5px)' : 'none',
transition: 'filter 0.3s ease',
}}
>
{renderStepContent()}
</div>
</div>
<Divider />
<FormActions
currentStep={currentStep}
@@ -672,4 +537,4 @@ const AddBrandDevice = () => {
);
};
export default AddBrandDevice;
export default AddBrandDevice;