Compare commits

...

5 Commits

Author SHA1 Message Date
96d6367dbd add: image viewer 2025-12-12 12:46:05 +07:00
8afff23ffe update: brand device 2025-12-12 12:45:46 +07:00
512282f367 repair: sollution brand-device 2025-12-12 12:45:00 +07:00
4fab5df300 repair: error code brand-device 2025-12-12 12:44:16 +07:00
9e8191f8f8 repair: sparepart brand-device 2025-12-12 12:43:14 +07:00
20 changed files with 2902 additions and 1215 deletions

View File

@@ -52,6 +52,9 @@ import SvgAirDryerC from './pages/home/SvgAirDryerC';
import IndexHistoryAlarm from './pages/history/alarm/IndexHistoryAlarm';
import IndexHistoryEvent from './pages/history/event/IndexHistoryEvent';
// Image Viewer
import ImageViewer from './Utils/ImageViewer';
const App = () => {
return (
<BrowserRouter>
@@ -76,6 +79,8 @@ const App = () => {
<Route path="blank" element={<Blank />} />
</Route>
<Route path="/image-viewer/:fileName" element={<ImageViewer />} />
<Route path="/dashboard-svg" element={<ProtectedRoute />}>
<Route path="overview-compressor" element={<SvgOverviewCompressor />} />
<Route path="compressor-a" element={<SvgCompressorA />} />
@@ -148,7 +153,6 @@ const App = () => {
<Route index element={<IndexJadwalShift />} />
</Route>
{/* Catch-all */}
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>

248
src/Utils/ImageViewer.jsx Normal file
View File

@@ -0,0 +1,248 @@
import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { getFileUrl, getFolderFromFileType } from '../api/file-uploads';
const ImageViewer = () => {
const { fileName } = useParams();
const [fileUrl, setFileUrl] = useState('');
const [error, setError] = useState('');
const [zoom, setZoom] = useState(1);
const [isImage, setIsImage] = useState(false);
useEffect(() => {
if (!fileName) {
setError('No file specified');
return;
}
try {
const decodedFileName = decodeURIComponent(fileName);
const fileExtension = decodedFileName.split('.').pop()?.toLowerCase();
const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
setIsImage(imageExtensions.includes(fileExtension));
const folder = getFolderFromFileType(fileExtension);
const url = getFileUrl(folder, decodedFileName);
setFileUrl(url);
document.title = `File Viewer - ${decodedFileName}`;
} catch (error) {
setError('Failed to load file');
}
}, [fileName]);
useEffect(() => {
const handleKeyDown = (e) => {
if (!isImage) return;
if (e.key === '+' || e.key === '=') {
setZoom(prev => Math.min(prev + 0.1, 3));
} else if (e.key === '-' || e.key === '_') {
setZoom(prev => Math.max(prev - 0.1, 0.1));
} else if (e.key === '0') {
setZoom(1);
} else if (e.key === 'Escape') {
window.close();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [isImage]);
const handleWheel = (e) => {
if (!isImage || !e.ctrlKey) return;
e.preventDefault();
const delta = e.deltaY > 0 ? -0.1 : 0.1;
setZoom(prev => Math.min(Math.max(prev + delta, 0.1), 3));
};
const handleZoomIn = () => setZoom(prev => Math.min(prev + 0.1, 3));
const handleZoomOut = () => setZoom(prev => Math.max(prev - 0.1, 0.1));
const handleResetZoom = () => setZoom(1);
if (error) {
return (
<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
fontFamily: 'Arial, sans-serif',
backgroundColor: '#f5f5f5'
}}>
<div style={{ textAlign: 'center' }}>
<h1>Error</h1>
<p>{error}</p>
</div>
</div>
);
}
if (!isImage) {
return (
<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
fontFamily: 'Arial, sans-serif',
backgroundColor: '#f5f5f5'
}}>
<div style={{ textAlign: 'center' }}>
<h1>File Type Not Supported</h1>
<p>Image viewer only supports image files.</p>
<p>Please use direct file preview for PDFs and other documents.</p>
</div>
</div>
);
}
return (
<div
style={{
margin: 0,
padding: 0,
height: '100vh',
width: '100vw',
backgroundColor: '#000',
overflow: 'hidden',
position: 'relative'
}}
onWheel={handleWheel}
>
{isImage && (
<div style={{
position: 'fixed',
top: '20px',
right: '20px',
display: 'flex',
gap: '10px',
backgroundColor: 'rgba(0, 0, 0, 0.7)',
padding: '10px',
borderRadius: '8px',
zIndex: 1000
}}>
<button
onClick={handleZoomOut}
style={{
backgroundColor: 'rgba(255, 255, 255, 0.2)',
color: '#fff',
border: '1px solid rgba(255, 255, 255, 0.3)',
padding: '8px 12px',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '16px'
}}
title="Zoom Out (-)"
>
</button>
<span style={{
color: '#fff',
padding: '8px 12px',
minWidth: '60px',
textAlign: 'center',
fontSize: '14px'
}}>
{Math.round(zoom * 100)}%
</span>
<button
onClick={handleZoomIn}
style={{
backgroundColor: 'rgba(255, 255, 255, 0.2)',
color: '#fff',
border: '1px solid rgba(255, 255, 255, 0.3)',
padding: '8px 12px',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '16px'
}}
title="Zoom In (+)"
>
+
</button>
<button
onClick={handleResetZoom}
style={{
backgroundColor: 'rgba(255, 255, 255, 0.2)',
color: '#fff',
border: '1px solid rgba(255, 255, 255, 0.3)',
padding: '8px 12px',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '14px'
}}
title="Reset Zoom (0)"
>
Reset
</button>
</div>
)}
{isImage && fileUrl ? (
<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100%',
overflow: 'auto'
}}>
<img
src={fileUrl}
alt={decodeURIComponent(fileName)}
style={{
maxWidth: 'none',
maxHeight: 'none',
transform: `scale(${zoom})`,
transformOrigin: 'center',
transition: 'transform 0.1s ease-out',
cursor: zoom > 1 ? 'move' : 'default'
}}
onError={() => setError('Failed to load image')}
draggable={false}
/>
</div>
) : isImage ? (
<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
color: '#fff',
fontFamily: 'Arial, sans-serif'
}}>
<p>Loading image...</p>
</div>
) : null}
{isImage && (
<div style={{
position: 'fixed',
bottom: '20px',
left: '20px',
backgroundColor: 'rgba(0, 0, 0, 0.7)',
color: '#fff',
padding: '10px 15px',
borderRadius: '8px',
fontSize: '12px',
zIndex: 1000
}}>
<div>Mouse wheel + Ctrl: Zoom</div>
<div>Keyboard: +/ Zoom, 0: Reset, ESC: Close</div>
</div>
)}
</div>
);
};
export default ImageViewer;

File diff suppressed because it is too large Load Diff

View File

@@ -10,13 +10,13 @@ import {
Spin,
Upload,
} from 'antd';
import { ArrowLeftOutlined, UploadOutlined } from '@ant-design/icons';
import { getBrandById, getErrorCodeById, updateBrand, getErrorCodesByBrandId, createErrorCode, updateErrorCode } from '../../../api/master-brand';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { getErrorCodeById, createErrorCode, updateErrorCode } from '../../../api/master-brand';
import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb';
import ErrorCodeSimpleForm from './component/ErrorCodeSimpleForm';
import ErrorCodeForm from './component/ErrorCodeForm';
import SolutionForm from './component/SolutionForm';
import { useSolutionLogic } from './hooks/solution';
import SingleSparepartSelect from './component/SingleSparepartSelect';
import SparepartSelect from './component/SparepartSelect';
import { NotifAlert, NotifOk } from '../../../components/Global/ToastNotif';
const { Title } = Typography;
@@ -29,10 +29,9 @@ const AddEditErrorCode = () => {
const currentBrandId = routeBrandId;
const isFromAddBrand = location.pathname.includes('/master/brand-device/') && location.pathname.includes('/error-code/') &&
(location.pathname.includes('/add') || (location.pathname.includes('/edit/') && !location.pathname.includes('/edit/')));
const isFromAddBrand = location.pathname.includes('/master/brand-device/') && location.pathname.includes('/error-code/') &&
(location.pathname.includes('/add') || (location.pathname.includes('/edit/') && !location.pathname.includes('/edit/')));
// Forms
const [errorCodeForm] = Form.useForm();
const [solutionForm] = Form.useForm();
@@ -62,7 +61,6 @@ const AddEditErrorCode = () => {
const isEditMode = errorCodeId && errorCodeId !== 'add';
setIsEdit(isEditMode);
// Initialize solution form with proper structure
if (!isEditMode) {
resetSolutionFields();
}
@@ -172,13 +170,13 @@ const AddEditErrorCode = () => {
}
};
const handleSave = async () => {
const handleSave = async () => {
try {
await errorCodeForm.validateFields();
const solutionData = getSolutionData();
// Validate that at least one solution exists and is valid
if (!solutionData || solutionData.length === 0) {
NotifAlert({
icon: 'warning',
@@ -188,16 +186,16 @@ const AddEditErrorCode = () => {
return;
}
// Validate solutions based on their type
const invalidSolutions = solutionData.filter(solution => {
if (solution.type_solution === 'text') {
return !solution.text_solution || solution.text_solution.trim() === '';
} else if (solution.type_solution === 'file') {
} else if (solution.type_solution !== 'text') {
return !solution.path_solution || solution.path_solution.trim() === '';
}
return false;
});
if (invalidSolutions.length > 0) {
const invalidNames = invalidSolutions.map(s => s.solution_name).join(', ');
NotifAlert({
@@ -229,14 +227,20 @@ const AddEditErrorCode = () => {
payload.error_code = errorCodeValues.error_code;
}
let response;
if (isEdit && errorCodeId) {
response = await updateErrorCode(currentBrandId, errorCodeId, payload);
let cleanErrorCodeId = errorCodeId;
if (errorCodeId.startsWith('existing_')) {
cleanErrorCodeId = errorCodeId.replace('existing_', '');
}
response = await updateErrorCode(currentBrandId, cleanErrorCodeId, payload);
} else {
response = await createErrorCode(currentBrandId, payload);
}
if (response && (response.statusCode === 200 || response.statusCode === 201)) {
NotifOk({
icon: 'success',
@@ -247,7 +251,9 @@ const AddEditErrorCode = () => {
if (isFromAddBrand) {
navigate(`/master/brand-device/add`);
} else {
navigate(`/master/brand-device/edit/${currentBrandId}?tab=error-codes`);
navigate(`/master/brand-device/edit/${currentBrandId}?tab=error-codes`, {
state: { refreshErrorCodes: true }
});
}
} else {
NotifAlert({
@@ -303,7 +309,6 @@ const AddEditErrorCode = () => {
};
const handleSolutionFileUpload = (fileObject) => {
// Handle solution file upload if needed
};
const resetForm = () => {
@@ -373,7 +378,7 @@ const AddEditErrorCode = () => {
error_code_color: '#000000',
}}
>
<ErrorCodeSimpleForm
<ErrorCodeForm
errorCodeForm={errorCodeForm}
isErrorCodeFormReadOnly={false}
errorCodeIcon={errorCodeIcon}
@@ -404,9 +409,8 @@ const AddEditErrorCode = () => {
solutionStatuses={solutionStatuses}
firstSolutionValid={firstSolutionValid}
checkFirstSolutionValid={() => {
// console.log('🔍 checkFirstSolutionValid function:', typeof checkFirstSolutionValid);
return checkFirstSolutionValid();
}}
return checkFirstSolutionValid();
}}
onAddSolutionField={handleAddSolutionField}
onRemoveSolutionField={handleRemoveSolutionField}
onSolutionTypeChange={handleSolutionTypeChange}
@@ -430,7 +434,7 @@ const AddEditErrorCode = () => {
size="small"
style={{ height: 'fit-content' }}
>
<SingleSparepartSelect
<SparepartSelect
selectedSparepartIds={selectedSparepartIds}
onSparepartChange={setSelectedSparepartIds}
isReadOnly={false}
@@ -456,7 +460,7 @@ const AddEditErrorCode = () => {
</div>
</div>
</Card>
</Card>
);
};

View File

@@ -15,18 +15,17 @@ import {
Input,
} from 'antd';
import { EyeOutlined, EditOutlined, DeleteOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons';
import TableList from '../../../components/Global/TableList';
import { ConfigProvider } from 'antd';
import { NotifAlert, NotifOk, NotifConfirmDialog } from '../../../components/Global/ToastNotif';
import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb';
import { getBrandById, getErrorCodesByBrandId, deleteErrorCode } from '../../../api/master-brand';
import { getBrandById, getErrorCodesByBrandId, getErrorCodeById, deleteErrorCode, updateErrorCode as updateErrorCodeAPI, createErrorCode as createErrorCodeAPI } from '../../../api/master-brand';
import { getFileUrl } from '../../../api/file-uploads';
import { SendRequest } from '../../../components/Global/ApiRequest';
import BrandForm from './component/BrandForm';
import ErrorCodeSimpleForm from './component/ErrorCodeSimpleForm';
import ErrorCodeForm from './component/ErrorCodeForm';
import SolutionForm from './component/SolutionForm';
import FormActions from './component/FormActions';
import { useSolutionLogic } from './hooks/solution';
import SingleSparepartSelect from './component/SingleSparepartSelect';
import SparepartSelect from './component/SparepartSelect';
import ListErrorCode from './component/ListErrorCode';
const { Title } = Typography;
const { Step } = Steps;
@@ -50,18 +49,180 @@ const EditBrandDevice = () => {
const [searchText, setSearchText] = useState('');
const [apiErrorCodes, setApiErrorCodes] = useState([]);
const [trigerFilter, setTrigerFilter] = useState(false);
const [searchValue, setSearchValue] = useState('');
const [brandInfo, setBrandInfo] = useState({});
const [tempErrorCodes, setTempErrorCodes] = useState([]);
const [existingErrorCodes, setExistingErrorCodes] = useState([]);
const [selectedErrorCode, setSelectedErrorCode] = useState(null);
const [solutionFields, setSolutionFields] = useState([0]);
const [solutionTypes, setSolutionTypes] = useState({ 0: 'text' });
const [solutionStatuses, setSolutionStatuses] = useState({ 0: true });
const [currentSolutionData, setCurrentSolutionData] = useState([]);
const {
resetSolutionFields,
getSolutionData,
setSolutionsForExistingRecord,
} = useSolutionLogic(solutionForm);
const getSolutionData = () => {
if (!solutionForm) return [];
try {
const values = solutionForm.getFieldsValue(true);
let solutions = [];
if (values.solution_items) {
if (Array.isArray(values.solution_items)) {
solutions = values.solution_items.filter(Boolean);
} else if (typeof values.solution_items === 'object') {
solutions = Object.values(values.solution_items).filter(Boolean);
}
}
return solutions;
} catch (error) {
return [];
}
};
const resetSolutionFields = () => {
if (solutionForm && solutionForm.resetFields) {
solutionForm.resetFields();
solutionForm.setFieldsValue({
solution_items: {
0: {
name: '',
type: 'text',
text: '',
status: true
}
}
});
}
setCurrentSolutionData([]);
};
const setSolutionsForExistingRecord = (solutions, targetForm) => {
if (!targetForm || !solutions || solutions.length === 0) {
return;
}
targetForm.resetFields();
const solutionItems = {};
const newSolutionFields = [];
const newSolutionTypes = {};
const newSolutionStatuses = {};
solutions.forEach((solution, index) => {
const fieldKey = index;
newSolutionFields.push(fieldKey);
const isFileType = solution.type_solution && solution.type_solution !== 'text';
newSolutionTypes[fieldKey] = isFileType ? 'file' : 'text';
newSolutionStatuses[fieldKey] = solution.is_active !== false;
let fileObject = null;
if (isFileType && (solution.path_solution || solution.path_document)) {
fileObject = {
uploadPath: solution.path_solution || solution.path_document,
path_solution: solution.path_solution || solution.path_document,
name: solution.file_upload_name || (solution.path_solution || solution.path_document).split('/').pop() || 'File',
type_solution: solution.type_solution,
isExisting: true,
size: 0,
url: solution.path_solution || solution.path_document
};
}
solutionItems[fieldKey] = {
brand_code_solution_id: solution.brand_code_solution_id,
name: solution.solution_name || '',
type: isFileType ? 'file' : 'text',
text: solution.text_solution || '',
status: solution.is_active !== false,
file: fileObject,
fileUpload: fileObject,
path_solution: solution.path_solution || solution.path_document || null,
fileName: solution.file_upload_name || null
};
});
setSolutionFields(newSolutionFields);
setSolutionTypes(newSolutionTypes);
setSolutionStatuses(newSolutionStatuses);
targetForm.resetFields();
setTimeout(() => {
targetForm.setFieldsValue({
solution_items: solutionItems
});
setTimeout(() => {
Object.keys(solutionItems).forEach(key => {
const solution = solutionItems[key];
targetForm.setFieldValue(['solution_items', key, 'name'], solution.name);
targetForm.setFieldValue(['solution_items', key, 'type'], solution.type);
targetForm.setFieldValue(['solution_items', key, 'text'], solution.text);
targetForm.setFieldValue(['solution_items', key, 'file'], solution.file);
targetForm.setFieldValue(['solution_items', key, 'fileUpload'], solution.fileUpload);
targetForm.setFieldValue(['solution_items', key, 'status'], solution.status);
targetForm.setFieldValue(['solution_items', key, 'path_solution'], solution.path_solution);
targetForm.setFieldValue(['solution_items', key, 'fileName'], solution.fileName);
});
const finalValues = targetForm.getFieldsValue();
}, 100);
}, 100);
};
const handleAddSolutionField = () => {
const newKey = Math.max(...solutionFields, 0) + 1;
setSolutionFields(prev => [...prev, newKey]);
setSolutionTypes(prev => ({ ...prev, [newKey]: 'text' }));
setSolutionStatuses(prev => ({ ...prev, [newKey]: true }));
};
const handleRemoveSolutionField = (fieldKey) => {
if (solutionFields.length > 1) {
setSolutionFields(prev => prev.filter(key => key !== fieldKey));
const newTypes = { ...solutionTypes };
const newStatuses = { ...solutionStatuses };
delete newTypes[fieldKey];
delete newStatuses[fieldKey];
setSolutionTypes(newTypes);
setSolutionStatuses(newStatuses);
const currentValues = solutionForm.getFieldsValue();
if (currentValues.solution_items && currentValues.solution_items[fieldKey]) {
delete currentValues.solution_items[fieldKey];
solutionForm.setFieldsValue(currentValues);
}
}
};
const handleSolutionTypeChange = (fieldKey, type) => {
setSolutionTypes(prev => ({ ...prev, [fieldKey]: type }));
if (type === 'file') {
solutionForm.setFieldValue(['solution_items', fieldKey, 'text'], '');
}
if (type === 'text') {
solutionForm.setFieldValue(['solution_items', fieldKey, 'file'], null);
solutionForm.setFieldValue(['solution_items', fieldKey, 'fileUpload'], null);
}
};
const handleSolutionStatusChange = (fieldKey, status) => {
setSolutionStatuses(prev => ({ ...prev, [fieldKey]: status }));
};
useEffect(() => {
errorCodeForm.setFieldsValue({
status: true,
});
const fetchBrandData = async () => {
const token = localStorage.getItem('token');
if (!token) {
@@ -129,7 +290,6 @@ const EditBrandDevice = () => {
setApiErrorCodes(existingCodes);
}
} catch (error) {
console.error('Error fetching error codes:', error);
}
}
@@ -160,18 +320,35 @@ const EditBrandDevice = () => {
setCurrentStep(tab === 'brand' ? 0 : 1);
}, [searchParams]);
useEffect(() => {
if (currentStep === 1 && id) {
setTrigerFilter(prev => !prev);
}
}, [currentStep, id]);
// Local functions to replace context methods
// Auto refresh error codes when returning from add/edit error code
useEffect(() => {
if (location.state?.refreshErrorCodes) {
// Trigger refresh of error codes list
setTrigerFilter(prev => !prev);
// Clear the state to prevent infinite refresh
const state = { ...location.state };
delete state.refreshErrorCodes;
navigate(location.pathname + location.search, {
replace: true,
state
});
}
}, [location, navigate]);
const addErrorCode = (newErrorCode) => {
// Generate unique tempId with timestamp and random number
const uniqueId = `temp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
const errorCodeWithId = {
...newErrorCode,
tempId: Date.now().toString(),
tempId: uniqueId,
status: 'new'
};
setTempErrorCodes(prev => [...prev, errorCodeWithId]);
@@ -228,7 +405,7 @@ const EditBrandDevice = () => {
navigate('/master/brand-device');
};
const handleErrorCodeIconUpload = (iconData) => {
setErrorCodeIcon(iconData);
};
@@ -251,6 +428,7 @@ const EditBrandDevice = () => {
const handleCreateNewErrorCode = () => {
resetErrorCodeForm();
setCurrentSolutionData([]);
};
const handleSaveErrorCode = async () => {
@@ -276,106 +454,138 @@ const EditBrandDevice = () => {
return;
}
const newErrorCode = {
error_code: errorCodeValues.error_code,
const formattedSolutions = solutionData.map(solution => {
const solutionType = solution.type || 'text';
let typeSolution = solutionType === 'text' ? 'text' : 'image';
if (solution.file && solution.file.type_solution) {
typeSolution = solution.file.type_solution;
} else if (solution.fileUpload && solution.fileUpload.type_solution) {
typeSolution = solution.fileUpload.type_solution;
}
const formattedSolution = {
solution_name: solution.name,
type_solution: typeSolution,
is_active: solution.status !== false,
};
if (typeSolution === 'text') {
formattedSolution.text_solution = solution.text || '';
formattedSolution.path_solution = '';
} else {
formattedSolution.text_solution = '';
formattedSolution.path_solution = solution.path_solution || solution.file?.uploadPath || solution.fileUpload?.uploadPath || '';
}
if (formattedSolution.brand_code_solution_id) {
delete formattedSolution.brand_code_solution_id;
}
return formattedSolution;
});
const payload = {
error_code_name: errorCodeValues.error_code_name,
error_code_description: errorCodeValues.error_code_description,
error_code_description: errorCodeValues.error_code_description || '',
error_code_color: errorCodeValues.error_code_color || '#000000',
path_icon: errorCodeIcon?.uploadPath || '',
is_active: errorCodeValues.status === undefined ? true : errorCodeValues.status,
solution: solutionData,
spareparts: selectedSparepartIds
solution: formattedSolutions,
spareparts: selectedSparepartIds || []
};
if (editingErrorCodeKey) {
updateErrorCode(editingErrorCodeKey, newErrorCode);
NotifOk({
icon: 'success',
title: 'Berhasil',
message: 'Error code berhasil diupdate!',
});
} else {
addErrorCode(newErrorCode);
NotifOk({
icon: 'success',
title: 'Berhasil',
message: 'Error code berhasil ditambahkan!',
});
if (!editingErrorCodeKey || !editingErrorCodeKey.startsWith('existing_')) {
payload.error_code = errorCodeValues.error_code;
}
resetErrorCodeForm();
let response;
if (editingErrorCodeKey && editingErrorCodeKey.startsWith('existing_')) {
const errorCodeId = editingErrorCodeKey.replace('existing_', '');
response = await updateErrorCodeAPI(id, errorCodeId, payload);
} else {
response = await createErrorCodeAPI(id, payload);
}
if (response && (response.statusCode === 200 || response.statusCode === 201)) {
NotifOk({
icon: 'success',
title: 'Berhasil',
message: editingErrorCodeKey ? 'Error code berhasil diupdate!' : 'Error code berhasil ditambahkan!',
});
// Clear temp error codes after successful save to prevent duplication
setTempErrorCodes(prev => prev.filter(ec => {
// Keep existing error codes that weren't just saved
if (ec.status === 'existing' || ec.tempId.startsWith('existing_')) {
return true;
}
// Remove the newly saved error code to prevent duplication
return ec.tempId !== editingErrorCodeKey;
}));
setTrigerFilter(prev => !prev);
resetErrorCodeForm();
} else {
NotifAlert({
icon: 'error',
title: 'Gagal',
message: response?.message || 'Gagal menyimpan error code',
});
}
} catch (error) {
NotifAlert({
icon: 'warning',
title: 'Perhatian',
message: 'Harap isi semua kolom wajib!',
message: error.message || 'Harap isi semua kolom wajib!',
});
}
};
const loadErrorCodeData = (errorCode, isPreview = false) => {
if (errorCode) {
const formValues = {
error_code: errorCode.error_code,
error_code_name: errorCode.error_code_name,
error_code_description: errorCode.error_code_description || '',
error_code_color: errorCode.error_code_color && errorCode.error_code_color !== '' ? errorCode.error_code_color : '#000000',
status: errorCode.is_active,
};
errorCodeForm.setFieldsValue(formValues);
if (errorCode.path_icon && errorCode.path_icon !== '') {
const iconData = {
name: errorCode.path_icon.split('/').pop(),
uploadPath: errorCode.path_icon,
};
setErrorCodeIcon(iconData);
} else {
setErrorCodeIcon(null);
}
setIsErrorCodeFormReadOnly(isPreview);
const editingKey = errorCode.tempId || `existing_${errorCode.error_code_id}`;
setEditingErrorCodeKey(editingKey);
}
};
const handlePreviewErrorCode = (record) => {
const errorCode = getErrorCodeById(record.tempId || record.error_code_id);
if (errorCode) {
errorCodeForm.setFieldsValue({
error_code: errorCode.error_code,
error_code_name: errorCode.error_code_name,
error_code_description: errorCode.error_code_description,
error_code_color: errorCode.error_code_color,
status: errorCode.is_active,
});
setErrorCodeIcon(errorCode.path_icon ? {
name: errorCode.path_icon.split('/').pop(),
uploadPath: errorCode.path_icon,
} : null);
setIsErrorCodeFormReadOnly(true);
setEditingErrorCodeKey(errorCode.tempId);
if (errorCode.solution && errorCode.solution.length > 0) {
setSolutionsForExistingRecord(errorCode.solution, solutionForm);
} else {
resetSolutionFields();
}
if (errorCode.spareparts && errorCode.spareparts.length > 0) {
setSelectedSparepartIds(errorCode.spareparts);
}
}
loadErrorCodeData(errorCode, true);
};
const handleEditErrorCode = (record) => {
const errorCode = getErrorCodeById(record.tempId || record.error_code_id);
if (errorCode) {
errorCodeForm.setFieldsValue({
error_code: errorCode.error_code,
error_code_name: errorCode.error_code_name,
error_code_description: errorCode.error_code_description,
error_code_color: errorCode.error_code_color,
status: errorCode.is_active,
});
setErrorCodeIcon(errorCode.path_icon ? {
name: errorCode.path_icon.split('/').pop(),
uploadPath: errorCode.path_icon,
} : null);
setIsErrorCodeFormReadOnly(false);
setEditingErrorCodeKey(errorCode.tempId);
if (errorCode.solution && errorCode.solution.length > 0) {
setSolutionsForExistingRecord(errorCode.solution, solutionForm);
}
if (errorCode.spareparts && errorCode.spareparts.length > 0) {
setSelectedSparepartIds(errorCode.spareparts);
}
}
loadErrorCodeData(errorCode, false);
};
const handleEditErrorCodeNavigate = (record) => {
const errorCodeId = record.status === 'existing' ? record.error_code_id : record.tempId;
const currentBrandId = id;
if (errorCodeId && currentBrandId) {
navigate(`/master/brand-device/${currentBrandId}/error-code/edit/${errorCodeId}`);
}
};
const handleDeleteErrorCode = async (record) => {
NotifConfirmDialog({
@@ -418,7 +628,7 @@ const EditBrandDevice = () => {
});
}
},
onCancel: () => {}
onCancel: () => { }
});
};
@@ -518,25 +728,22 @@ const EditBrandDevice = () => {
}, [setBrandInfo]);
const handleSearch = () => {
setSearchText(searchValue);
setTrigerFilter((prev) => !prev);
};
const handleSearchClear = () => {
setSearchValue('');
setSearchText('');
setTrigerFilter((prev) => !prev);
};
const getErrorCodesData = async (params) => {
try {
const search = params.get('search') || '';
const criteria = params.get('criteria') || '';
const page = parseInt(params.get('page')) || 1;
const limit = parseInt(params.get('limit')) || 10;
const currentBrandId = id;
if (!currentBrandId) {
console.warn('Brand ID is not available');
return {
data: [],
pagination: {
@@ -551,7 +758,7 @@ const EditBrandDevice = () => {
const queryParams = new URLSearchParams({
page: page.toString(),
limit: limit.toString(),
...(search && { search })
...(criteria && { criteria })
});
const response = await getErrorCodesByBrandId(currentBrandId, queryParams);
@@ -576,7 +783,6 @@ const EditBrandDevice = () => {
spareparts: contextModified.spareparts || ec.spareparts || []
};
} else {
// Use original API data
return {
...ec,
tempId: `existing_${ec.error_code_id}`,
@@ -587,7 +793,6 @@ const EditBrandDevice = () => {
}
});
// Filter out deleted error codes
const activeExistingCodes = existingCodes.filter(ec => ec.status !== 'deleted');
const allErrorCodes = [...activeExistingCodes, ...tempErrorCodes.filter(ec => ec.status !== 'deleted')];
@@ -626,7 +831,6 @@ const EditBrandDevice = () => {
}
};
} catch (error) {
console.error('Error fetching error codes:', error);
return {
data: [],
pagination: {
@@ -672,90 +876,321 @@ const EditBrandDevice = () => {
}
if (currentStep === 1) {
const queryParams = new URLSearchParams();
if (searchText) {
queryParams.set('search', searchText);
}
const handleErrorCodeSelect = async (errorCode) => {
setSelectedErrorCode(errorCode);
try {
const directResponse = await SendRequest({
method: 'get',
prefix: `error-code/${errorCode.error_code_id}`,
});
const apiResponse = directResponse.data;
if (apiResponse && apiResponse.statusCode === 200 && apiResponse.data) {
const fullErrorCodeData = {
...apiResponse.data,
tempId: `existing_${apiResponse.data.error_code_id}`
};
loadErrorCodeData(fullErrorCodeData, false);
if (apiResponse.data.solution && apiResponse.data.solution.length > 0) {
setCurrentSolutionData(apiResponse.data.solution);
setSolutionsForExistingRecord(apiResponse.data.solution, solutionForm);
}
if (apiResponse.data.spareparts && apiResponse.data.spareparts.length > 0) {
setSelectedSparepartIds(apiResponse.data.spareparts.map(sp => sp.sparepart_id));
} else {
setSelectedSparepartIds([]);
}
} else {
const basicErrorCodeData = {
...errorCode,
tempId: `existing_${errorCode.error_code_id}`
};
loadErrorCodeData(basicErrorCodeData, false);
resetSolutionFields();
setSelectedSparepartIds([]);
}
} catch (error) {
const basicErrorCodeData = {
...errorCode,
tempId: `existing_${errorCode.error_code_id}`
};
loadErrorCodeData(basicErrorCodeData, false);
}
};
const handleAddNew = () => {
setSelectedErrorCode(null);
resetErrorCodeForm();
};
return (
<Card>
<Row>
<Col xs={24}>
<Row justify="space-between" align="middle" gutter={[8, 8]}>
<Col xs={24} sm={24} md={12} lg={12}>
<Input.Search
placeholder="Search error codes..."
value={searchText}
onChange={(e) => {
const value = e.target.value;
setSearchText(value);
if (value === '') {
setTrigerFilter((prev) => !prev);
}
}}
onSearch={handleSearch}
allowClear={{
clearIcon: <span onClick={handleSearchClear}></span>,
}}
enterButton={
<Row gutter={[16, 8]} style={{ minHeight: '70vh' }}>
<Col xs={24} md={8} lg={8}>
<ListErrorCode
brandId={id}
selectedErrorCode={selectedErrorCode}
onErrorCodeSelect={handleErrorCodeSelect}
tempErrorCodes={tempErrorCodes}
trigerFilter={trigerFilter}
searchText={searchText}
onSearchChange={(value) => {
setSearchText(value);
if (value === '') {
setTrigerFilter((prev) => !prev);
}
}}
onSearch={handleSearch}
onSearchClear={handleSearchClear}
/>
</Col>
<Col xs={24} md={16} lg={16}>
<div style={{
paddingLeft: '12px'
}}>
<Card
title={
<span style={{
fontSize: '16px',
fontWeight: '600',
color: '#262626',
display: 'flex',
alignItems: 'center',
gap: '8px'
}}>
<span style={{
width: '4px',
height: '20px',
backgroundColor: '#23A55A',
borderRadius: '2px'
}}></span>
Error Code Form
</span>
}
style={{
width: '100%',
boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
borderRadius: '12px'
}}
styles={{
body: { padding: '16px 24px 12px 24px' },
header: {
padding: '16px 24px',
borderBottom: '1px solid #f0f0f0',
backgroundColor: '#fafafa'
}
}}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
<div style={{
padding: '16px',
border: '1px solid #f0f0f0',
borderRadius: '10px',
backgroundColor: '#ffffff',
marginBottom: '0',
transition: 'all 0.3s ease',
boxShadow: '0 1px 3px rgba(0,0,0,0.04)'
}}>
<div style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
marginBottom: '12px',
paddingBottom: '8px',
borderBottom: '1px solid #f5f5f5'
}}>
<div style={{
width: '3px',
height: '16px',
backgroundColor: '#23A55A',
borderRadius: '2px'
}}></div>
<h4 style={{ margin: 0, color: '#262626', fontSize: '14px', fontWeight: '600' }}>
Error Code Details
</h4>
</div>
<ErrorCodeForm
errorCodeForm={errorCodeForm}
isErrorCodeFormReadOnly={isErrorCodeFormReadOnly}
errorCodeIcon={errorCodeIcon}
onErrorCodeIconUpload={handleErrorCodeIconUpload}
onErrorCodeIconRemove={handleErrorCodeIconRemove}
isEdit={editingErrorCodeKey !== null}
/>
</div>
<Row gutter={[20, 0]} style={{ marginTop: '0' }}>
<Col xs={24} md={12} lg={12}>
<div style={{
padding: '16px',
border: '1px solid #f0f0f0',
borderRadius: '10px',
backgroundColor: '#ffffff',
transition: 'all 0.3s ease',
boxShadow: '0 1px 3px rgba(0,0,0,0.04)'
}}>
<div style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
marginBottom: '12px',
paddingBottom: '8px',
borderBottom: '1px solid #f5f5f5'
}}>
<div style={{
width: '3px',
height: '16px',
backgroundColor: '#1890ff',
borderRadius: '2px'
}}></div>
<h4 style={{ margin: 0, color: '#262626', fontSize: '14px', fontWeight: '600' }}>
Solution
</h4>
</div>
<SolutionForm
solutionForm={solutionForm}
solutionFields={solutionFields}
solutionTypes={solutionTypes}
solutionStatuses={solutionStatuses}
onAddSolutionField={handleAddSolutionField}
onRemoveSolutionField={handleRemoveSolutionField}
onSolutionTypeChange={handleSolutionTypeChange}
onSolutionStatusChange={handleSolutionStatusChange}
onSolutionFileUpload={(fileData) => {
}}
onFileView={(fileData) => {
if (fileData && (fileData.url || fileData.uploadPath)) {
window.open(fileData.url || fileData.uploadPath, '_blank');
}
}}
isReadOnly={false}
solutionData={currentSolutionData}
/>
</div>
</Col>
<Col xs={24} md={12} lg={12}>
<div style={{
padding: '16px',
border: '1px solid #f0f0f0',
borderRadius: '10px',
backgroundColor: '#ffffff',
transition: 'all 0.3s ease',
boxShadow: '0 1px 3px rgba(0,0,0,0.04)'
}}>
<div style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
marginBottom: '12px',
paddingBottom: '8px',
borderBottom: '1px solid #f5f5f5'
}}>
<div style={{
width: '3px',
height: '16px',
backgroundColor: '#faad14',
borderRadius: '2px'
}}></div>
<h4 style={{ margin: 0, color: '#262626', fontSize: '14px', fontWeight: '600' }}>
Sparepart Selection
</h4>
</div>
<div style={{
maxHeight: '45vh',
overflow: 'auto',
border: '1px solid #e8e8e8',
borderRadius: '8px',
padding: '12px',
backgroundColor: '#fafafa'
}}>
<SparepartSelect
selectedSparepartIds={selectedSparepartIds}
onSparepartChange={setSelectedSparepartIds}
isReadOnly={isErrorCodeFormReadOnly}
/>
</div>
</div>
</Col>
</Row>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
padding: '16px 0 0 0',
borderTop: '1px solid #f0f0f0',
marginTop: '12px'
}}>
{/* Cancel Button - Only show when editing existing error code */}
{editingErrorCodeKey && (
<Button
size="large"
onClick={handleCreateNewErrorCode}
style={{
backgroundColor: '#fff',
borderColor: '#d9d9d9',
color: '#666',
borderRadius: '8px',
height: '40px',
padding: '0 24px',
fontWeight: '500',
transition: 'all 0.3s ease'
}}
onMouseEnter={(e) => {
e.target.style.borderColor = '#ff4d4f';
e.target.style.color = '#ff4d4f';
}}
onMouseLeave={(e) => {
e.target.style.borderColor = '#d9d9d9';
e.target.style.color = '#666';
}}
>
Cancel
</Button>
)}
{/* Save Button - Always show on right */}
<div style={{ marginLeft: editingErrorCodeKey ? '0' : 'auto' }}>
<Button
type="primary"
icon={<SearchOutlined />}
size="large"
onClick={handleSaveErrorCode}
style={{
backgroundColor: '#23A55A',
borderColor: '#23A55A',
borderRadius: '8px',
height: '40px',
padding: '0 24px',
fontWeight: '500',
boxShadow: '0 2px 4px rgba(35, 165, 90, 0.2)',
transition: 'all 0.3s ease'
}}
onMouseEnter={(e) => {
e.target.style.boxShadow = '0 4px 8px rgba(35, 165, 90, 0.3)';
}}
onMouseLeave={(e) => {
e.target.style.boxShadow = '0 2px 4px rgba(35, 165, 90, 0.2)';
}}
>
Search
{editingErrorCodeKey ? 'Update Error Code' : 'Simpan Error Code'}
</Button>
}
size="large"
/>
</Col>
<Col>
<Space wrap size="small">
<ConfigProvider
theme={{
token: { colorBgContainer: '#E9F6EF' },
components: {
Button: {
defaultBg: 'white',
defaultColor: '#23A55A',
defaultBorderColor: '#23A55A',
defaultHoverColor: '#23A55A',
defaultHoverBorderColor: '#23A55A',
},
},
}}
>
<Button
icon={<PlusOutlined />}
onClick={() => navigate(`/master/brand-device/${id}/error-code/add`)}
size="large"
>
Add Error Code
</Button>
</ConfigProvider>
</Space>
</Col>
</Row>
</Col>
<Col xs={24} sm={24} md={24} lg={24} xl={24} style={{ marginTop: '16px' }}>
<TableList
mobile
cardColor={'#42AAFF'}
header={'error_code'}
showPreviewModal={handlePreviewErrorCode}
showEditModal={handleEditErrorCodeNavigate}
showDeleteDialog={handleDeleteErrorCode}
getData={getErrorCodesData}
queryParams={queryParams}
columns={errorCodeColumns(handlePreviewErrorCode, handleEditErrorCodeNavigate, handleDeleteErrorCode)}
triger={trigerFilter}
/>
</Col>
</Row>
</Card>
</div>
</div>
</div>
</Card>
</div>
</Col>
</Row>
);
}
return null;
@@ -763,9 +1198,6 @@ const EditBrandDevice = () => {
return (
<Card>
<Title level={4} style={{ margin: '0 0 24px 0' }}>
Edit Brand Device
</Title>
<Steps current={currentStep} style={{ marginBottom: 24 }}>
<Step title="Brand Device Details" />
<Step title="Error Codes & Solutions" />
@@ -788,6 +1220,7 @@ const EditBrandDevice = () => {
<Button
type="primary"
onClick={handleNextStep}
loading={loading}
style={{
backgroundColor: '#23A55A',
borderColor: '#23A55A',
@@ -805,7 +1238,7 @@ const EditBrandDevice = () => {
borderColor: '#23A55A',
}}
>
Kembali
Selesai
</Button>
)}
</div>

View File

@@ -138,12 +138,6 @@ const ViewFilePage = () => {
const targetPhase = savedPhase ? parseInt(savedPhase) : 1;
console.log({
savedPhase,
targetPhase,
id: fallbackId || id
});
navigate(`/master/brand-device/edit/${fallbackId || id}`, {
state: { phase: targetPhase, fromFileViewer: true },
replace: true
@@ -174,9 +168,7 @@ const ViewFilePage = () => {
const isImage = ['jpg', 'jpeg', 'png', 'gif'].includes(fileExtension);
const isPdf = fileExtension === 'pdf';
// const fileUrl = loading ? null : getFileUrl(getFolderFromFileType(fallbackFileType || fileType), actualFileName);
// Show placeholder when loading
if (loading) {
return (
<div style={{ textAlign: 'center', padding: '50px' }}>
@@ -318,7 +310,6 @@ const ViewFilePage = () => {
</Button>
<Button
onClick={() => {
// Retry loading PDF
setPdfLoading(true);
const folder = getFolderFromFileType('pdf');
getFile(folder, actualFileName)

View File

@@ -7,9 +7,18 @@ const BrandForm = ({
form,
onValuesChange,
isEdit = false,
brandInfo = null,
}) => {
const isActive = Form.useWatch('is_active', form) ?? true;
React.useEffect(() => {
if (brandInfo && brandInfo.brand_code) {
form.setFieldsValue({
brand_code: brandInfo.brand_code
});
}
}, [brandInfo, form]);
return (
<div>
<Form

View File

@@ -20,7 +20,6 @@ const CustomSparepartCard = ({
}) => {
const [previewModalVisible, setPreviewModalVisible] = useState(false);
// Construct image source with proper fallback
const getImageSrc = () => {
if (sparepart.sparepart_foto) {
if (sparepart.sparepart_foto.startsWith('http')) {
@@ -56,7 +55,6 @@ const CustomSparepartCard = ({
const getCardActions = () => {
const actions = [];
// Preview button
if (showPreview) {
actions.push(
<Button
@@ -73,7 +71,6 @@ const CustomSparepartCard = ({
);
}
// Delete button without confirmation
if (showDelete && !isReadOnly) {
actions.push(
<Button
@@ -93,7 +90,6 @@ const CustomSparepartCard = ({
return actions;
};
// Get card styling based on size
const getCardStyle = () => {
const baseStyle = {
borderRadius: '12px',
@@ -132,11 +128,13 @@ const CustomSparepartCard = ({
<Card
hoverable={!!onCardClick && !isReadOnly}
style={getCardStyle()}
bodyStyle={{
padding: 0,
height: 'calc(100% - 48px)',
display: 'flex',
flexDirection: 'column'
styles={{
body: {
padding: 0,
height: 'calc(100% - 48px)',
display: 'flex',
flexDirection: 'column'
}
}}
actions={getCardActions()}
onClick={handleCardClick}
@@ -244,55 +242,65 @@ const CustomSparepartCard = ({
{sparepart.sparepart_name || sparepart.name || 'Unnamed'}
</Title>
{size !== 'small' && (
<>
<Text
type="secondary"
{/* Stock and Quantity Information */}
<div style={{ marginBottom: size === 'small' ? '6px' : '8px' }}>
{/* Stock Status Tag */}
<div style={{ marginBottom: '4px' }}>
<Tag
color={sparepart.sparepart_stok === 'Available' ? 'green' : 'red'}
style={{
fontSize: '12px',
display: 'block',
marginBottom: '6px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
fontSize: size === 'small' ? '9px' : '10px',
padding: '0 4px',
margin: 0,
height: 'auto'
}}
>
Stock: {sparepart.sparepart_stock || sparepart.sparepart_stok || '0'} {sparepart.sparepart_unit || 'pcs'}
{sparepart.sparepart_stok || 'Not Available'}
</Tag>
</div>
{/* Quantity */}
<div style={{ display: 'flex', alignItems: 'center' }}>
<Text
style={{
fontSize: size === 'small' ? '10px' : '11px',
fontWeight: 500,
color: '#262626',
marginRight: '4px'
}}
>
qty:
</Text>
<Text
style={{
fontSize: size === 'small' ? '10px' : '11px',
color: sparepart.sparepart_qty > 0 ? '#52c41a' : '#ff4d4f',
fontWeight: 600
}}
>
{sparepart.sparepart_qty || 0}
{sparepart.sparepart_unit ? ` ${sparepart.sparepart_unit}` : ''}
</Text>
</div>
</div>
<div style={{ marginBottom: '6px' }}>
<Text
code
style={{
fontSize: '11px',
backgroundColor: '#f5f5f5',
padding: '2px 6px',
borderRadius: '3px'
}}
>
{sparepart.sparepart_code || 'No code'}
</Text>
</div>
</>
)}
{size === 'small' && (
<div style={{ marginBottom: size === 'small' ? '4px' : '6px' }}>
<Text
code
style={{
fontSize: '10px',
fontSize: size === 'small' ? '10px' : '11px',
backgroundColor: '#f5f5f5',
display: 'block',
marginBottom: '4px'
padding: '2px 6px',
borderRadius: '3px'
}}
>
{sparepart.sparepart_code || 'No code'}
</Text>
)}
</div>
{(sparepart.sparepart_merk || sparepart.sparepart_model) && (
<div style={{
fontSize: size === 'small' ? '10px' : '11px',
fontSize: size === 'small' ? '9px' : '10px',
color: '#666',
lineHeight: '1.4',
marginBottom: '4px'
@@ -332,23 +340,24 @@ const CustomSparepartCard = ({
Close
</Button>
]}
width={700}
width={800}
centered
bodyStyle={{ padding: '24px' }}
styles={{ body: { padding: '24px' } }}
>
<Row gutter={[24, 24]}>
<Col span={8}>
<Col span={10}>
<div style={{ textAlign: 'center' }}>
<div
style={{
backgroundColor: '#f0f0f0',
width: '200px',
height: '200px',
width: '220px',
height: '220px',
margin: '0 auto 16px',
position: 'relative',
borderRadius: '8px',
borderRadius: '12px',
overflow: 'hidden',
border: '1px solid #E0E0E0',
boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
}}
>
<img
@@ -360,116 +369,138 @@ const CustomSparepartCard = ({
objectFit: 'cover'
}}
onError={(e) => {
e.target.src = 'https://via.placeholder.com/200x200/d9d9d9/666666?text=No+Image';
e.target.src = 'https://via.placeholder.com/220x220/d9d9d9/666666?text=No+Image';
}}
/>
</div>
{/* Item Type Tag */}
{sparepart.sparepart_item_type && (
<Tag color="blue" style={{ marginTop: '12px' }}>
{sparepart.sparepart_item_type}
</Tag>
)}
</div>
</Col>
<Col span={16}>
<div>
<Title level={3} style={{ marginBottom: '16px' }}>
{sparepart.sparepart_name || 'Unnamed'}
</Title>
<Row gutter={[16, 16]} style={{ marginBottom: '16px' }}>
<Col span={12}>
<div style={{ marginBottom: '8px' }}>
<Text strong style={{ fontSize: '16px', color: '#262626' }}>
Code:
</Text>
<Text style={{ fontSize: '16px', marginLeft: '8px' }}>
{sparepart.sparepart_code || 'N/A'}
</Text>
</div>
</Col>
<Col span={12}>
<div style={{ marginBottom: '8px' }}>
<Text strong style={{ fontSize: '16px', color: '#262626' }}>
Status:
</Text>
<Tag
color={sparepart.is_active ? 'green' : 'red'}
style={{ marginLeft: '8px', fontSize: '14px' }}
>
{sparepart.is_active ? 'Active' : 'Inactive'}
</Tag>
</div>
</Col>
</Row>
{sparepart.sparepart_description && (
<div style={{ marginBottom: '16px' }}>
<Text strong style={{ fontSize: '16px', color: '#262626' }}>
Description:
</Text>
<Text style={{ fontSize: '16px', marginLeft: '8px' }}>
{sparepart.sparepart_description}
</Text>
<div style={{ marginBottom: '12px' }}>
<Tag color="blue" style={{ fontSize: '14px', padding: '4px 12px' }}>
{sparepart.sparepart_item_type}
</Tag>
</div>
)}
<div style={{ marginBottom: '16px' }}>
<Text strong style={{ fontSize: '16px', color: '#262626' }}>
Stock:
</Text>
<Text style={{ fontSize: '16px', marginLeft: '8px' }}>
{sparepart.sparepart_stock || sparepart.sparepart_stok || '0'}
{sparepart.sparepart_unit ? ` ${sparepart.sparepart_unit}` : ' units'}
</Text>
{/* Stock Status and Quantity */}
<div style={{
textAlign: 'left',
background: '#f8f9fa',
padding: '12px',
borderRadius: '8px',
marginTop: '25px'
}}>
<div style={{ marginBottom: '8px' }}>
<Text strong style={{ fontSize: '14px', color: '#262626' }}>Stock Status:</Text>
<Tag
color={sparepart.sparepart_stok === 'Available' ? 'green' : 'red'}
style={{ marginLeft: '8px', fontSize: '12px' }}
>
{sparepart.sparepart_stok || 'Not Available'}
</Tag>
</div>
<div>
<Text strong style={{ fontSize: '14px', color: '#262626' }}>Quantity:</Text>
<Text style={{ fontSize: '14px', marginLeft: '8px', fontWeight: 600 }}>
{sparepart.sparepart_qty || 0} {sparepart.sparepart_unit || ''}
</Text>
</div>
</div>
</div>
</Col>
<Col span={14}>
<div>
{/* Sparepart Name */}
<Title level={3} style={{ marginBottom: '20px', color: '#262626' }}>
{sparepart.sparepart_name || 'Unnamed'}
</Title>
{/* Basic Information */}
<div style={{ marginBottom: '24px' }}>
<Row gutter={[16, 12]}>
<Col span={24}>
<div style={{
padding: '12px',
backgroundColor: '#fafafa',
borderRadius: '8px',
border: '1px solid #f0f0f0'
}}>
<Row gutter={16}>
<Col span={8}>
<div>
<Text type="secondary" style={{ fontSize: '12px' }}>Code</Text>
<div style={{ fontSize: '15px', fontWeight: 500, marginTop: '2px' }}>
{sparepart.sparepart_code || 'N/A'}
</div>
</div>
</Col>
<Col span={8}>
<div>
<Text type="secondary" style={{ fontSize: '12px' }}>Brand</Text>
<div style={{ fontSize: '15px', fontWeight: 500, marginTop: '2px' }}>
{sparepart.sparepart_merk || '-'}
</div>
</div>
</Col>
<Col span={8}>
<div>
<Text type="secondary" style={{ fontSize: '12px' }}>Unit</Text>
<div style={{ fontSize: '15px', fontWeight: 500, marginTop: '2px' }}>
{sparepart.sparepart_unit || '-'}
</div>
</div>
</Col>
</Row>
</div>
</Col>
{sparepart.sparepart_model && (
<Col span={24}>
<div>
<Text type="secondary" style={{ fontSize: '12px' }}>Model</Text>
<div style={{ fontSize: '15px', fontWeight: 500, marginTop: '2px' }}>
{sparepart.sparepart_model}
</div>
</div>
</Col>
)}
{sparepart.sparepart_description && (
<Col span={24}>
<div>
<Text type="secondary" style={{ fontSize: '12px' }}>Description</Text>
<div style={{ fontSize: '15px', marginTop: '2px', lineHeight: '1.5' }}>
{sparepart.sparepart_description}
</div>
</div>
</Col>
)}
</Row>
</div>
<Row gutter={[16, 16]} style={{ marginBottom: '16px' }}>
{sparepart.sparepart_merk && (
<Col span={8}>
<div>
<Text strong style={{ fontSize: '14px', color: '#262626' }}>
Brand:
</Text>
<Text style={{ fontSize: '14px', marginLeft: '8px' }}>
{sparepart.sparepart_merk}
</Text>
</div>
</Col>
)}
{sparepart.sparepart_model && (
<Col span={8}>
<div>
<Text strong style={{ fontSize: '14px', color: '#262626' }}>
Model:
</Text>
<Text style={{ fontSize: '14px', marginLeft: '8px' }}>
{sparepart.sparepart_model}
</Text>
</div>
</Col>
)}
{sparepart.sparepart_unit && (
<Col span={8}>
<div>
<Text strong style={{ fontSize: '14px', color: '#262626' }}>
Unit:
</Text>
<Text style={{ fontSize: '14px', marginLeft: '8px' }}>
{sparepart.sparepart_unit}
</Text>
</div>
</Col>
)}
</Row>
{sparepart.updated_at && (
<div style={{ marginTop: '24px', paddingTop: '16px', borderTop: '1px solid #f0f0f0' }}>
<Text type="secondary" style={{ fontSize: '14px' }}>
Last updated: {dayjs(sparepart.updated_at).format('DD MMMM YYYY, HH:mm')}
</Text>
{/* Timeline Information */}
{sparepart.created_at && (
<div>
<Row gutter={16}>
<Col span={12}>
<div>
<Text type="secondary" style={{ fontSize: '12px' }}>Created</Text>
<div style={{ fontSize: '13px', marginTop: '2px' }}>
{dayjs(sparepart.created_at).format('DD MMM YYYY, HH:mm')}
</div>
</div>
</Col>
<Col span={12}>
<div>
<Text type="secondary" style={{ fontSize: '12px' }}>Last Updated</Text>
<div style={{ fontSize: '13px', marginTop: '2px' }}>
{dayjs(sparepart.updated_at).format('DD MMM YYYY, HH:mm')}
</div>
</div>
</Col>
</Row>
</div>
)}
</div>

View File

@@ -0,0 +1,279 @@
import React, { useState, useEffect } from 'react';
import { Form, Input, Switch, Typography, ConfigProvider, Card, Button } from 'antd';
import { FileOutlined, EyeOutlined, DeleteOutlined } from '@ant-design/icons';
import FileUploadHandler from './FileUploadHandler';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
import { getFileUrl, getFolderFromFileType } from '../../../../api/file-uploads';
const { Text } = Typography;
const ErrorCodeForm = ({
errorCodeForm,
isErrorCodeFormReadOnly = false,
errorCodeIcon,
onErrorCodeIconUpload,
onErrorCodeIconRemove,
isEdit = false,
}) => {
const [statusValue, setStatusValue] = useState(true);
const [currentIcon, setCurrentIcon] = useState(null);
useEffect(() => {
if (errorCodeIcon && typeof errorCodeIcon === 'object' && Object.keys(errorCodeIcon).length > 0) {
setCurrentIcon(errorCodeIcon);
} else {
setCurrentIcon(null);
}
}, [errorCodeIcon]);
const handleIconRemove = () => {
setCurrentIcon(null);
onErrorCodeIconRemove();
};
const renderIconUpload = () => {
if (currentIcon) {
const displayFileName = currentIcon.name || currentIcon.uploadPath?.split('/').pop() || currentIcon.url?.split('/').pop() || 'Icon File';
return (
<Card
style={{
marginTop: 8,
borderRadius: 8,
boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
border: '1px solid #e8e8e8'
}}
styles={{ body: { padding: '16px' } }}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: 48,
height: 48,
borderRadius: 8,
backgroundColor: '#f0f5ff',
flexShrink: 0
}}>
<FileOutlined style={{ fontSize: 24, color: '#1890ff' }} />
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{
fontSize: 13,
fontWeight: 600,
color: '#262626',
marginBottom: 4,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
}}>
{displayFileName}
</div>
<div style={{ fontSize: 12, color: '#8c8c8c' }}>
{currentIcon.size ? `${(currentIcon.size / 1024).toFixed(1)} KB` : 'Icon uploaded'}
</div>
</div>
<div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
<Button
type="primary"
size="middle"
icon={<EyeOutlined />}
style={{
fontSize: 12,
display: 'flex',
alignItems: 'center',
gap: 4
}}
onClick={() => {
try {
let iconUrl = '';
let actualFileName = '';
const filePath = currentIcon.uploadPath || currentIcon.url || currentIcon.path || '';
const iconDisplayName = currentIcon.name || '';
if (iconDisplayName) {
actualFileName = iconDisplayName;
} else if (filePath) {
actualFileName = filePath.split('/').pop();
}
if (actualFileName) {
const fileExtension = actualFileName.split('.').pop()?.toLowerCase();
const folder = getFolderFromFileType(fileExtension);
iconUrl = getFileUrl(folder, actualFileName);
}
if (!iconUrl && filePath) {
iconUrl = filePath.startsWith('http') ? filePath : `${import.meta.env.VITE_API_SERVER}/${filePath}`;
}
if (iconUrl && actualFileName) {
const fileExtension = actualFileName.split('.').pop()?.toLowerCase();
const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
const pdfExtensions = ['pdf'];
if (imageExtensions.includes(fileExtension) || pdfExtensions.includes(fileExtension)) {
const viewerUrl = `/image-viewer/${encodeURIComponent(actualFileName)}`;
window.open(viewerUrl, '_blank', 'noopener,noreferrer');
} else {
window.open(iconUrl, '_blank', 'noopener,noreferrer');
}
} else {
NotifAlert({
icon: 'error',
title: 'Error',
message: `File URL not found. FileName: ${actualFileName}, FilePath: ${filePath}`
});
}
} catch (error) {
NotifAlert({
icon: 'error',
title: 'Error',
message: `Failed to open file preview: ${error.message}`
});
}
}}
/>
<Button
danger
size="middle"
icon={<DeleteOutlined />}
style={{
fontSize: 12,
display: 'flex',
alignItems: 'center',
}}
onClick={handleIconRemove}
disabled={isErrorCodeFormReadOnly}
/>
</div>
</div>
</Card>
);
} else {
return (
<FileUploadHandler
type="error_code"
existingFile={null}
accept="image/*"
onFileUpload={(fileData) => {
setCurrentIcon(fileData);
onErrorCodeIconUpload(fileData);
}}
onFileRemove={handleIconRemove}
buttonText="Upload Icon"
buttonStyle={{
width: '100%',
borderColor: '#23A55A',
color: '#23A55A',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '8px'
}}
uploadText="Upload error code icon"
disabled={isErrorCodeFormReadOnly}
/>
);
}
};
return (
<ConfigProvider
theme={{
components: {
Switch: {
colorPrimary: '#23A55A',
colorPrimaryHover: '#23A55A',
},
},
}}
>
<Form
form={errorCodeForm}
layout="vertical"
initialValues={{
status: true,
error_code_color: '#000000'
}}
>
<Form.Item
label="Status"
name="status"
valuePropName="checked"
>
<div style={{ display: 'flex', alignItems: 'center' }}>
<Switch
defaultChecked={true}
onChange={(checked) => {
setStatusValue(checked);
}}
/>
<Text style={{ marginLeft: 8 }}>
{statusValue ? 'Active' : 'Inactive'}
</Text>
</div>
</Form.Item>
<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>
<Form.Item
label="Error Name"
name="error_code_name"
rules={[{ required: true, message: 'Error name wajib diisi!' }]}
>
<Input placeholder="Enter error name" />
</Form.Item>
<Form.Item label="Description" name="error_code_description">
<Input.TextArea
placeholder="Enter error description"
rows={3}
/>
</Form.Item>
<Form.Item label="Color & Icon">
<div style={{ display: 'flex', gap: '12px', alignItems: 'flex-start' }}>
<Form.Item
name="error_code_color"
noStyle
style={{ flex: '0 0 auto' }}
getValueFromEvent={(e) => e.target.value}
getValueProps={(value) => ({ value: value || '#000000' })}
>
<input
type="color"
style={{
width: '120px',
height: '40px',
border: '1px solid #d9d9d9',
borderRadius: 4,
}}
/>
</Form.Item>
<Form.Item noStyle style={{ flex: '1 1 auto' }}>
{renderIconUpload()}
</Form.Item>
</div>
</Form.Item>
</Form>
</ConfigProvider>
);
};
export default ErrorCodeForm;

View File

@@ -1,108 +0,0 @@
import React from 'react';
import { Form, Input, Switch, Typography, ConfigProvider } from 'antd';
import FileUploadHandler from './FileUploadHandler';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
const { Text } = Typography;
const ErrorCodeSimpleForm = ({
errorCodeForm,
isErrorCodeFormReadOnly = false,
errorCodeIcon,
onErrorCodeIconUpload,
onErrorCodeIconRemove,
onAddErrorCode,
isEdit = false, // Add isEdit prop to check if we're in edit mode
}) => {
const statusValue = Form.useWatch('status', errorCodeForm);
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
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" />
</Form.Item>
{/* Error Description */}
<Form.Item label="Description" name="error_code_description">
<Input.TextArea
placeholder="Enter error description"
rows={3}
/>
</Form.Item>
{/* Color and Icon */}
<Form.Item label="Color & Icon">
<div style={{ display: 'flex', gap: '12px', alignItems: 'flex-start' }}>
<Form.Item name="error_code_color" noStyle style={{ flex: '0 0 auto' }}>
<input
type="color"
style={{
width: '120px',
height: '40px',
border: '1px solid #d9d9d9',
borderRadius: 4,
}}
/>
</Form.Item>
<Form.Item noStyle style={{ flex: '1 1 auto' }}>
<FileUploadHandler
type="error_code"
existingFile={errorCodeIcon}
accept="image/*"
onFileUpload={onErrorCodeIconUpload}
onFileRemove={handleIconRemove}
buttonText="Upload Icon"
buttonStyle={{
width: '100%',
borderColor: '#23A55A',
color: '#23A55A',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '8px'
}}
uploadText="Upload error code icon"
/>
</Form.Item>
</div>
</Form.Item>
</>
);
};
export default ErrorCodeSimpleForm;

View File

@@ -12,12 +12,13 @@ const FileUploadHandler = ({
accept = '.pdf,.jpg,.jpeg,.png,.gif',
disabled = false,
// File management
fileList = [],
onFileUpload,
onFileRemove,
existingFile = null,
clearSignal = null,
debugProps = {},
uploadText = 'Click or drag file to this area to upload',
uploadHint = 'Support for PDF and image files only',
@@ -34,6 +35,12 @@ const FileUploadHandler = ({
const [isUploading, setIsUploading] = useState(false);
const [uploadedFile, setUploadedFile] = useState(null);
React.useEffect(() => {
if (clearSignal !== null && clearSignal > 0) {
setUploadedFile(null);
}
}, [clearSignal, debugProps]);
const getBase64 = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
@@ -140,6 +147,7 @@ const FileUploadHandler = ({
}
}
if (actualPath) {
let fileObject;
@@ -176,7 +184,6 @@ const FileUploadHandler = ({
setIsUploading(false);
return false;
} else {
console.error('Failed to extract file path from upload response:', uploadResponse);
NotifAlert({
icon: 'error',
title: 'Gagal',
@@ -186,7 +193,6 @@ const FileUploadHandler = ({
return false;
}
} catch (error) {
console.error('Upload error:', error);
NotifAlert({
icon: 'error',
title: 'Error',
@@ -204,16 +210,9 @@ const FileUploadHandler = ({
};
const handleRemove = () => {
console.log('🗑️ FileUploadHandler handleRemove called:', {
existingFile,
onFileRemove: typeof onFileRemove,
hasExistingFile: !!existingFile
});
if (existingFile && onFileRemove) {
onFileRemove(existingFile);
} else if (onFileRemove) {
// Call onFileRemove even without existingFile to trigger form cleanup
onFileRemove(null);
}
};
@@ -221,17 +220,9 @@ const FileUploadHandler = ({
const renderExistingFile = () => {
const fileToShow = existingFile || uploadedFile;
if (!fileToShow) {
console.log('❌ FileUploadHandler renderExistingFile: No file to render');
return null;
}
console.log('✅ FileUploadHandler renderExistingFile: File found', {
existingFile: !!existingFile,
uploadedFile: !!uploadedFile,
fileName: fileToShow.name,
shouldShowDeleteButton: true
});
const filePath = fileToShow.uploadPath || fileToShow.url || fileToShow.path_icon || fileToShow.path_solution;
const fileName = fileToShow.name || filePath?.split('/').pop() || 'Unknown file';
const fileType = getFileType(fileName);
@@ -257,7 +248,6 @@ const FileUploadHandler = ({
});
}
} else {
// For PDFs and other files, open in new tab
const folder = fileToShow.type_solution === 'pdf' ? 'pdf' : 'images';
const filename = filePath.split('/').pop();
const fileUrl = getFileUrl(folder, filename);
@@ -404,7 +394,9 @@ const FileUploadHandler = ({
</Upload>
)}
{renderExistingFile()}
{/* renderExistingFile() is disabled because SolutionField.jsx already handles file card rendering */}
{/* This prevents duplicate card rendering */}
{/* {renderExistingFile()} */}
{showPreview && (
<Modal

View File

@@ -91,9 +91,9 @@ const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [
const ListBrandDevice = memo(function ListBrandDevice(props) {
const [trigerFilter, setTrigerFilter] = useState(false);
const defaultFilter = { search: '' };
const defaultFilter = { criteria: '' };
const [formDataFilter, setFormDataFilter] = useState(defaultFilter);
const [searchValue, setSearchValue] = useState('');
const [searchText, setSearchText] = useState('');
const navigate = useNavigate();
@@ -114,13 +114,13 @@ const ListBrandDevice = memo(function ListBrandDevice(props) {
};
const handleSearch = () => {
setFormDataFilter({ search: searchValue });
setFormDataFilter({ criteria: searchText });
setTrigerFilter((prev) => !prev);
};
const handleSearchClear = () => {
setSearchValue('');
setFormDataFilter({ search: '' });
setSearchText('');
setFormDataFilter({ criteria: '' });
setTrigerFilter((prev) => !prev);
};
@@ -182,12 +182,12 @@ const ListBrandDevice = memo(function ListBrandDevice(props) {
<Col xs={24} sm={24} md={12} lg={12}>
<Input.Search
placeholder="Search brand device..."
value={searchValue}
value={searchText}
onChange={(e) => {
const value = e.target.value;
setSearchValue(value);
setSearchText(value);
if (value === '') {
setFormDataFilter({ search: '' });
setFormDataFilter({ criteria: '' });
setTrigerFilter((prev) => !prev);
}
}}

View File

@@ -0,0 +1,307 @@
import React, { useState, useEffect, useMemo } from 'react';
import { Card, Input, Button, Row, Col, Empty } from 'antd';
import { PlusOutlined, SearchOutlined, DeleteOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons';
import { getErrorCodesByBrandId, deleteErrorCode } from '../../../../api/master-brand';
import { NotifAlert, NotifOk, NotifConfirmDialog } from '../../../../components/Global/ToastNotif';
const ListErrorCode = ({
brandId,
selectedErrorCode,
onErrorCodeSelect,
onAddNew,
tempErrorCodes = [],
trigerFilter,
searchText,
onSearchChange,
onSearch,
onSearchClear
}) => {
const [errorCodes, setErrorCodes] = useState([]);
const [loading, setLoading] = useState(false);
const [pagination, setPagination] = useState({
current_page: 1,
current_limit: 15,
total_limit: 0,
total_page: 0,
});
const [currentPage, setCurrentPage] = useState(1);
const pageSize = 15; // Fixed limit 15 items per page
const queryParams = useMemo(() => {
const params = new URLSearchParams();
params.set('page', currentPage.toString());
params.set('limit', pageSize.toString());
if (searchText) {
params.set('criteria', searchText);
}
return params;
}, [searchText, currentPage, pageSize]);
const fetchErrorCodes = async () => {
if (!brandId) {
setErrorCodes([]);
return;
}
setLoading(true);
try {
const response = await getErrorCodesByBrandId(brandId, queryParams);
if (response && response.statusCode === 200) {
const apiErrorData = response.data || [];
const allErrorCodes = [
...apiErrorData.map(ec => ({
...ec,
tempId: `existing_${ec.error_code_id}`,
status: 'existing'
})),
...tempErrorCodes.filter(ec => ec.status !== 'deleted')
];
setErrorCodes(allErrorCodes);
if (response.paging) {
setPagination({
current_page: response.paging.current_page || 1,
current_limit: response.paging.current_limit || 15,
total_limit: response.paging.total_limit || 0,
total_page: response.paging.total_page || 0,
});
}
} else {
setErrorCodes([]);
}
} catch (error) {
setErrorCodes([]);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchErrorCodes();
}, [brandId, queryParams, tempErrorCodes, trigerFilter]);
const handlePrevious = () => {
if (pagination.current_page > 1) {
setCurrentPage(pagination.current_page - 1);
}
};
const handleNext = () => {
if (pagination.current_page < pagination.total_page) {
setCurrentPage(pagination.current_page + 1);
}
};
const handleSearch = () => {
setCurrentPage(1);
if (onSearch) {
onSearch();
}
};
const handleSearchClear = () => {
setCurrentPage(1);
if (onSearchClear) {
onSearchClear();
}
};
const handleDelete = async (item, e) => {
e.stopPropagation();
if (item.status === 'existing' && item.error_code_id) {
NotifConfirmDialog({
icon: 'warning',
title: 'Hapus Error Code',
message: `Apakah Anda yakin ingin menghapus error code ${item.error_code}?`,
onConfirm: () => performDelete(item),
onCancel: () => {},
confirmButtonText: 'Hapus'
});
}
};
const performDelete = async (item) => {
try {
// Additional validation
if (!item.error_code_id || item.error_code_id === 'undefined') {
NotifAlert({
icon: 'error',
title: 'Error',
message: 'Error code ID tidak valid'
});
return;
}
if (!item.brand_id || item.brand_id === 'undefined') {
NotifAlert({
icon: 'error',
title: 'Error',
message: 'Brand ID tidak valid'
});
return;
}
const response = await deleteErrorCode(item.brand_id, item.error_code_id);
if (response && response.statusCode === 200) {
NotifOk({
icon: 'success',
title: 'Berhasil',
message: 'Error code berhasil dihapus'
});
fetchErrorCodes();
} else {
NotifAlert({
icon: 'error',
title: 'Gagal',
message: 'Gagal menghapus error code'
});
}
} catch (error) {
NotifAlert({
icon: 'error',
title: 'Error',
message: 'Terjadi kesalahan saat menghapus error code'
});
}
};
return (
<Card
title="Daftar Error Code"
style={{ width: '100%', minWidth: '472px' }}
styles={{ body: { padding: '12px' } }}
>
<Input.Search
placeholder="Cari error code..."
value={searchText}
onChange={(e) => {
const value = e.target.value;
if (onSearchChange) {
onSearchChange(value);
}
}}
onSearch={handleSearch}
allowClear
enterButton={
<Button
type="primary"
icon={<SearchOutlined />}
onClick={handleSearch}
style={{
backgroundColor: '#23A55A',
borderColor: '#23A55A',
height: '32px'
}}
>
Search
</Button>
}
size="default"
style={{
marginBottom: 12,
height: '32px',
width: '100%',
maxWidth: '300px'
}}
/>
<div style={{
height: '90vh',
border: '1px solid #d9d9d9',
borderRadius: '6px',
overflow: 'auto',
marginBottom: 12,
backgroundColor: '#fafafa'
}}>
{errorCodes.length === 0 ? (
<Empty
description="Belum ada error code"
style={{ marginTop: 50 }}
/>
) : (
<div style={{ padding: '8px' }}>
{errorCodes.map((item) => (
<div
key={item.tempId || item.error_code_id}
style={{
cursor: 'pointer',
padding: '8px 12px',
borderRadius: '6px',
marginBottom: '4px',
border: selectedErrorCode?.tempId === item.tempId ? '2px solid #23A55A' : '1px solid #d9d9d9',
backgroundColor: selectedErrorCode?.tempId === item.tempId ? '#f6ffed' : '#fff',
transition: 'all 0.2s ease'
}}
onClick={() => onErrorCodeSelect(item)}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div style={{ flex: 1 }}>
<div style={{ fontWeight: 'bold', fontSize: '12px' }}>
{item.error_code}
</div>
<div style={{ fontSize: '11px', color: '#666' }}>
{item.error_code_name}
</div>
</div>
{item.status === 'existing' && (
<Button
type="text"
danger
size="small"
icon={<DeleteOutlined />}
onClick={(e) => handleDelete(item, e)}
style={{
padding: '2px 6px',
height: '24px',
fontSize: '11px',
border: '1px solid #ff4d4f'
}}
/>
)}
</div>
</div>
))}
</div>
)}
</div>
{pagination.total_limit > 0 && (
<Row justify="space-between" align="middle" gutter={16}>
<Col flex="auto">
<span style={{ fontSize: '12px', color: '#666' }}>
Menampilkan {pagination.current_limit} data halaman{' '}
{pagination.current_page} dari total {pagination.total_limit} data
</span>
</Col>
<Col flex="none">
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
<Button
icon={<LeftOutlined />}
onClick={handlePrevious}
disabled={pagination.current_page <= 1}
size="small"
>
</Button>
<span style={{ fontSize: '12px', color: '#666', minWidth: '60px', textAlign: 'center' }}>
{pagination.current_page} / {pagination.total_page}
</span>
<Button
icon={<RightOutlined />}
onClick={handleNext}
disabled={pagination.current_page >= pagination.total_page}
size="small"
>
</Button>
</div>
</Col>
</Row>
)}
</Card>
);
};
export default ListErrorCode;

View File

@@ -1,8 +1,9 @@
import React, { useState } from 'react';
import { Form, Input, Button, Switch, Radio, Typography, Space } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import { Form, Input, Button, Switch, Radio, Typography, Space, Card } from 'antd';
import { DeleteOutlined, EyeOutlined, FileOutlined } from '@ant-design/icons';
import FileUploadHandler from './FileUploadHandler';
import { NotifAlert } from '../../../../components/Global/ToastNotif';
import { getFileUrl, getFolderFromFileType } from '../../../../api/file-uploads';
const { Text } = Typography;
const { TextArea } = Input;
@@ -20,50 +21,89 @@ const SolutionFieldNew = ({
onRemove,
onFileUpload,
onFileView,
fileList = []
fileList = [],
originalSolutionData = null
}) => {
const form = Form.useFormInstance();
const existingFile = Form.useWatch([`solution_items,${fieldKey}`, 'fileUpload'], form) ||
Form.useWatch([`solution_items,${fieldKey}`, 'file'], form);
const [currentFile, setCurrentFile] = useState(null);
const [isDeleted, setIsDeleted] = useState(false);
// Get form values for debugging and file data extraction
const allFormValues = form.getFieldsValue(true);
const solutionData = allFormValues[`solution_items,${fieldKey}`] || {};
const fileUpload = Form.useWatch(['solution_items', fieldKey, 'fileUpload'], form);
const file = Form.useWatch(['solution_items', fieldKey, 'file'], form);
// Extract file data from form values for preview
const getFileFromFormValues = () => {
if (solutionData.fileUpload && typeof solutionData.fileUpload === 'object' && Object.keys(solutionData.fileUpload).length > 0) {
return solutionData.fileUpload;
const getSolutionData = () => {
try {
return form.getFieldValue(['solution_items', fieldKey]) || {};
} catch (error) {
return {};
}
if (solutionData.file && typeof solutionData.file === 'object' && Object.keys(solutionData.file).length > 0) {
return solutionData.file;
}
return null;
};
const fileFromForm = getFileFromFormValues();
const displayFile = existingFile || fileFromForm;
const nameValue = Form.useWatch(['solution_items', fieldKey, 'name'], form);
const typeValue = Form.useWatch(['solution_items', fieldKey, 'type'], form);
const textValue = Form.useWatch(['solution_items', fieldKey, 'text'], form);
const fileNameValue = Form.useWatch(['solution_items', fieldKey, 'fileName'], form);
const pathSolution = Form.useWatch(['solution_items', fieldKey, 'path_solution'], form);
const [deleteCounter, setDeleteCounter] = useState(0);
React.useEffect(() => {
const getFileFromFormValues = () => {
const hasValidFileUpload = fileUpload && typeof fileUpload === 'object' && Object.keys(fileUpload).length > 0;
const hasValidFile = file && typeof file === 'object' && Object.keys(file).length > 0;
const hasValidPath = pathSolution && pathSolution.trim() !== '';
const wasExplicitlyDeleted =
(fileUpload === null || file === null || pathSolution === null) &&
!hasValidFileUpload &&
!hasValidFile &&
!hasValidPath;
if (wasExplicitlyDeleted) {
return null;
}
if (solutionType === 'text') {
return null;
}
if (hasValidFileUpload) {
return fileUpload;
}
if (hasValidFile) {
return file;
}
if (hasValidPath) {
return {
name: fileNameValue || pathSolution.split('/').pop() || 'File',
uploadPath: pathSolution,
url: pathSolution,
path: pathSolution
};
}
return null;
};
const fileFromForm = getFileFromFormValues();
if (JSON.stringify(currentFile) !== JSON.stringify(fileFromForm)) {
setCurrentFile(fileFromForm);
}
}, [fileUpload, file, pathSolution, solutionType, deleteCounter, fileNameValue, fieldKey]);
console.log(`🔍 SolutionField ${fieldKey}:`, {
solutionType,
hasPathSolution: !!solutionData.path_solution,
pathSolution: solutionData.path_solution,
fileFromForm,
existingFile,
displayFile,
shouldRenderPreview: !!displayFile
});
const renderSolutionContent = () => {
if (solutionType === 'text') {
return (
<Form.Item
name={[`solution_items,${fieldKey}`, 'text']}
name={['solution_items', fieldKey, 'text']}
rules={[{ required: true, message: 'Text solution wajib diisi!' }]}
>
<TextArea
placeholder="Enter solution text"
rows={2}
rows={3}
disabled={isReadOnly}
style={{ fontSize: 12 }}
/>
@@ -72,46 +112,251 @@ const SolutionFieldNew = ({
}
if (solutionType === 'file') {
return (
<div>
const hasOriginalFile = originalSolutionData && (
originalSolutionData.path_solution ||
originalSolutionData.path_document
);
let displayFile = null;
if (currentFile && Object.keys(currentFile).length > 0) {
displayFile = currentFile;
}
else if (hasOriginalFile && !isDeleted) {
displayFile = {
name: originalSolutionData.file_upload_name ||
(originalSolutionData.path_solution || originalSolutionData.path_document)?.split('/').pop() ||
'File',
uploadPath: originalSolutionData.path_solution || originalSolutionData.path_document,
url: originalSolutionData.path_solution || originalSolutionData.path_document,
path: originalSolutionData.path_solution || originalSolutionData.path_document,
isExisting: true
};
}
else if (fileUpload && typeof fileUpload === 'object' && Object.keys(fileUpload).length > 0) {
displayFile = fileUpload;
}
else if (file && typeof file === 'object' && Object.keys(file).length > 0) {
displayFile = file;
}
else if (pathSolution && pathSolution.trim() !== '') {
displayFile = {
name: pathSolution.split('/').pop() || 'File',
uploadPath: pathSolution,
url: pathSolution,
path: pathSolution
};
}
if (displayFile) {
const getFileNameFromPath = () => {
const filePath = displayFile.uploadPath || displayFile.url || displayFile.path || '';
if (filePath) {
const fileName = filePath.split('/').pop();
return fileName || 'Uploaded File';
}
return displayFile.name || 'Uploaded File';
};
const displayFileName = getFileNameFromPath();
return (
<Card
style={{
marginBottom: 8,
borderRadius: 8,
boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
border: '1px solid #e8e8e8'
}}
styles={{ body: { padding: '16px' } }}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: 48,
height: 48,
borderRadius: 8,
backgroundColor: '#f0f5ff',
flexShrink: 0
}}>
<FileOutlined style={{ fontSize: 24, color: '#1890ff' }} />
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{
fontSize: 13,
fontWeight: 600,
color: '#262626',
marginBottom: 4,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
}}>
{displayFileName}
</div>
<div style={{ fontSize: 12, color: '#8c8c8c' }}>
{displayFile.size ? `${(displayFile.size / 1024).toFixed(1)} KB` : 'File uploaded'}
</div>
</div>
<div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
<Button
type="primary"
size="middle"
icon={<EyeOutlined />}
style={{
fontSize: 12,
display: 'flex',
alignItems: 'center',
gap: 4
}}
onClick={() => {
try {
let fileUrl = '';
let actualFileName = '';
const filePath = displayFile.uploadPath || displayFile.url || displayFile.path || '';
if (filePath) {
actualFileName = filePath.split('/').pop();
if (actualFileName) {
const fileExtension = actualFileName.split('.').pop()?.toLowerCase();
const folder = getFolderFromFileType(fileExtension);
fileUrl = getFileUrl(folder, actualFileName);
}
}
if (!fileUrl && filePath) {
fileUrl = filePath.startsWith('http') ? filePath : `${import.meta.env.VITE_API_SERVER}/${filePath}`;
}
if (fileUrl && actualFileName) {
const fileExtension = actualFileName.split('.').pop()?.toLowerCase();
const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
if (imageExtensions.includes(fileExtension)) {
const viewerUrl = `/image-viewer/${encodeURIComponent(actualFileName)}`;
window.open(viewerUrl, '_blank', 'noopener,noreferrer');
} else {
window.open(fileUrl, '_blank', 'noopener,noreferrer');
}
} else {
NotifAlert({
icon: 'error',
title: 'Error',
message: 'File URL not found'
});
}
} catch (error) {
NotifAlert({
icon: 'error',
title: 'Error',
message: 'Failed to open file preview'
});
}
}}
/>
<Button
danger
size="middle"
icon={<DeleteOutlined />}
style={{
fontSize: 12,
display: 'flex',
alignItems: 'center',
}}
onClick={() => {
setIsDeleted(true);
form.setFieldValue(['solution_items', fieldKey, 'fileUpload'], null);
form.setFieldValue(['solution_items', fieldKey, 'file'], null);
form.setFieldValue(['solution_items', fieldKey, 'path_solution'], null);
form.setFieldValue(['solution_items', fieldKey, 'fileName'], null);
setCurrentFile(null);
if (onFileUpload && typeof onFileUpload === 'function') {
onFileUpload(null);
}
setDeleteCounter(prev => prev + 1);
setTimeout(() => {
form.validateFields(['solution_items', fieldKey]);
}, 50);
}}
/>
</div>
</div>
</Card>
);
} else {
return (
<FileUploadHandler
type="solution"
existingFile={displayFile}
existingFile={null}
clearSignal={deleteCounter}
debugProps={{
currentFile: !!currentFile,
deleteCounter,
shouldClear: !currentFile && deleteCounter > 0
}}
onFileUpload={(fileObject) => {
setIsDeleted(false);
const filePath = fileObject.path_solution || fileObject.uploadPath || fileObject.path || fileObject.url;
const fileWithKey = {
...fileObject,
solutionId: fieldKey
solutionId: fieldKey,
path_solution: filePath,
uploadPath: filePath
};
if (onFileUpload && typeof onFileUpload === 'function') {
onFileUpload(fileWithKey);
}
form.setFieldValue([`solution_items,${fieldKey}`, 'fileUpload'], fileWithKey);
form.setFieldValue([`solution_items,${fieldKey}`, 'file'], fileWithKey);
form.setFieldValue([`solution_items,${fieldKey}`, 'type'], 'file');
form.setFieldValue(['solution_items', fieldKey, 'fileUpload'], fileWithKey);
form.setFieldValue(['solution_items', fieldKey, 'file'], fileWithKey);
form.setFieldValue(['solution_items', fieldKey, 'type'], 'file');
form.setFieldValue(['solution_items', fieldKey, 'path_solution'], filePath);
form.setFieldValue(['solution_items', fieldKey, 'fileName'], fileObject.name);
setTimeout(() => {
const values = form.getFieldValue(['solution_items', fieldKey]);
const pathSolutionValue = form.getFieldValue(['solution_items', fieldKey, 'path_solution']);
}, 100);
setCurrentFile(fileWithKey);
}}
onFileRemove={() => {
console.log(`🗑️ Removing file from solution ${fieldKey}`);
form.setFieldValue(['solution_items', fieldKey, 'fileUpload'], null);
form.setFieldValue(['solution_items', fieldKey, 'file'], null);
form.setFieldValue(['solution_items', fieldKey, 'path_solution'], null);
// Clear file form values only, keep type as file and status active
form.setFieldValue([`solution_items,${fieldKey}`, 'fileUpload'], null);
form.setFieldValue([`solution_items,${fieldKey}`, 'file'], null);
setCurrentFile(null);
// Call parent callback if exists
if (onFileUpload && typeof onFileUpload === 'function') {
onFileUpload(null);
}
console.log(`✅ File removed from solution ${fieldKey} - type and status preserved`);
setDeleteCounter(prev => prev + 1);
}}
disabled={isReadOnly}
buttonText={displayFile ? 'Replace File' : 'Upload File'}
buttonText="Upload File"
buttonStyle={{ width: '100%', fontSize: 12 }}
uploadText="Upload solution file"
uploadText="Upload solution file (includes images, PDF, documents)"
acceptFileTypes="*"
/>
</div>
);
);
}
}
return null;
@@ -140,7 +385,7 @@ const SolutionFieldNew = ({
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<Form.Item name={[`solution_items,${fieldKey}`, 'status']} valuePropName="checked" noStyle>
<Form.Item name={['solution_items', fieldKey, 'status']} valuePropName="checked" noStyle>
<Switch
size="small"
disabled={isReadOnly}
@@ -180,7 +425,7 @@ const SolutionFieldNew = ({
</div>
<Form.Item
name={[`solution_items,${fieldKey}`, 'name']}
name={['solution_items', fieldKey, 'name']}
rules={[{ required: true, message: 'Solution name wajib diisi!' }]}
style={{ margin: 0 }}
>
@@ -192,16 +437,36 @@ const SolutionFieldNew = ({
/>
</Form.Item>
</div>
</div>
<Form.Item
name={[`solution_items,${fieldKey}`, 'type']}
name={['solution_items', fieldKey, 'type']}
rules={[{ required: true, message: 'Solution type wajib diisi!' }]}
style={{ marginBottom: 8 }}
initialValue={solutionType || 'text'}
>
<Radio.Group
onChange={(e) => onTypeChange(fieldKey, e.target.value)}
onChange={(e) => {
const newType = e.target.value;
if (newType === 'text') {
form.setFieldValue(['solution_items', fieldKey, 'fileUpload'], null);
form.setFieldValue(['solution_items', fieldKey, 'file'], null);
form.setFieldValue(['solution_items', fieldKey, 'path_solution'], null);
form.setFieldValue(['solution_items', fieldKey, 'fileName'], null);
setCurrentFile(null);
setIsDeleted(true);
if (onFileUpload && typeof onFileUpload === 'function') {
onFileUpload(null);
}
} else if (newType === 'file') {
form.setFieldValue(['solution_items', fieldKey, 'text'], null);
setIsDeleted(false);
}
onTypeChange(fieldKey, newType);
}}
disabled={isReadOnly}
size="small"
>
@@ -211,7 +476,7 @@ const SolutionFieldNew = ({
</Form.Item>
<Form.Item
name={[`solution_items,${fieldKey}`, 'status']}
name={['solution_items', fieldKey, 'status']}
initialValue={solutionStatus !== false ? true : false}
noStyle
>

View File

@@ -1,5 +1,5 @@
import React from 'react';
import { Typography, Divider, Button } from 'antd';
import { Typography, Divider, Button, Form } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import SolutionFieldNew from './SolutionField';
@@ -10,77 +10,66 @@ const SolutionForm = ({
solutionFields,
solutionTypes,
solutionStatuses,
firstSolutionValid,
onAddSolutionField,
onRemoveSolutionField,
onSolutionTypeChange,
onSolutionStatusChange,
checkFirstSolutionValid,
onSolutionFileUpload,
onFileView,
fileList,
isReadOnly = false,
solutionData = [],
}) => {
// console.log('SolutionForm props:', {
// solutionFields,
// solutionTypes,
// solutionStatuses,
// firstSolutionValid,
// onAddSolutionField: typeof onAddSolutionField,
// onRemoveSolutionField: typeof onRemoveSolutionField,
// checkFirstSolutionValid: typeof checkFirstSolutionValid,
// onSolutionFileUpload: typeof onSolutionFileUpload,
// onFileView: typeof onFileView,
// fileList: fileList ? fileList.length : 0
// });
return (
<div style={{ marginBottom: 0 }}>
<Divider orientation="left">Solution Items</Divider>
<div style={{
maxHeight: '400px',
overflowY: 'auto',
paddingRight: '8px'
}}>
{solutionFields.map((field, displayIndex) => (
<SolutionFieldNew
key={field}
fieldKey={field}
fieldName={['solution_items', field]}
index={displayIndex}
solutionType={solutionTypes[field]}
solutionStatus={solutionStatuses[field]}
onTypeChange={onSolutionTypeChange}
onStatusChange={onSolutionStatusChange}
onRemove={() => onRemoveSolutionField(field)}
onFileUpload={onSolutionFileUpload}
onFileView={onFileView}
fileList={fileList}
isReadOnly={isReadOnly}
canRemove={solutionFields.length > 1 && displayIndex > 0}
/>
))}
</div>
{!isReadOnly && (
<div style={{ marginBottom: 8 }}>
<Button
type="dashed"
onClick={onAddSolutionField}
icon={<PlusOutlined />}
style={{
width: '100%',
borderColor: '#23A55A',
color: '#23A55A',
height: '32px',
fontSize: '12px'
}}
>
Add More Solution
</Button>
<Form form={solutionForm} layout="vertical">
<div style={{
maxHeight: '400px',
overflowY: 'auto',
paddingRight: '8px'
}}>
{solutionFields.map((field, displayIndex) => (
<SolutionFieldNew
key={field}
fieldKey={field}
fieldName={['solution_items', field]}
index={displayIndex}
solutionType={solutionTypes[field]}
solutionStatus={solutionStatuses[field]}
onTypeChange={onSolutionTypeChange}
onStatusChange={onSolutionStatusChange}
onRemove={() => onRemoveSolutionField(field)}
onFileUpload={onSolutionFileUpload}
onFileView={onFileView}
fileList={fileList}
isReadOnly={isReadOnly}
canRemove={solutionFields.length > 1 && displayIndex > 0}
originalSolutionData={solutionData[displayIndex]}
/>
))}
</div>
)}
{!isReadOnly && (
<div style={{ marginBottom: 8, marginTop: 12 }}>
<Button
type="dashed"
onClick={onAddSolutionField}
icon={<PlusOutlined />}
style={{
width: '100%',
borderColor: '#23A55A',
color: '#23A55A',
height: '32px',
fontSize: '12px'
}}
>
Add sollution
</Button>
</div>
)}
</Form>
</div>
);
};

View File

@@ -1,249 +0,0 @@
import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Typography, Tag, Space, Spin, Button, Empty, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { getAllSparepart } from '../../../../api/sparepart';
import { addSparepartToBrand, removeSparepartFromBrand } from '../../../../api/master-brand';
import CustomSparepartCard from './CustomSparepartCard';
const { Text, Title } = Typography;
const SparepartCardSelect = ({
selectedSparepartIds = [],
onSparepartChange,
isLoading: externalLoading = false,
isReadOnly = false,
brandId = null
}) => {
const [spareparts, setSpareparts] = useState([]);
const [loading, setLoading] = useState(false);
const [searchTerm, setSearchTerm] = useState('');
useEffect(() => {
loadSpareparts();
}, []);
const loadSpareparts = async () => {
setLoading(true);
try {
const params = new URLSearchParams();
params.set('limit', '1000'); // Get all spareparts
const response = await getAllSparepart(params);
if (response && (response.statusCode === 200 || response.data)) {
const sparepartData = response.data?.data || response.data || [];
setSpareparts(sparepartData);
} else {
// For demo purposes, use mock data if API fails
setSpareparts([
{
sparepart_id: 1,
sparepart_name: 'Compressor Oil Filter',
sparepart_description: 'Oil filter for compressor',
sparepart_foto: null,
sparepart_code: 'SP-001',
sparepart_merk: 'Brand A',
sparepart_model: 'Model X'
},
{
sparepart_id: 2,
sparepart_name: 'Air Intake Filter',
sparepart_description: 'Air intake filter',
sparepart_foto: null,
sparepart_code: 'SP-002',
sparepart_merk: 'Brand B',
sparepart_model: 'Model Y'
},
{
sparepart_id: 3,
sparepart_name: 'Cooling Fan Motor',
sparepart_description: 'Motor for cooling fan',
sparepart_foto: null,
sparepart_code: 'SP-003',
sparepart_merk: 'Brand C',
sparepart_model: 'Model Z'
},
]);
}
} catch (error) {
// Default mock data
setSpareparts([
{
sparepart_id: 1,
sparepart_name: 'Compressor Oil Filter',
sparepart_description: 'Oil filter for compressor',
sparepart_foto: null,
sparepart_code: 'SP-001',
sparepart_merk: 'Brand A',
sparepart_model: 'Model X'
},
{
sparepart_id: 2,
sparepart_name: 'Air Intake Filter',
sparepart_description: 'Air intake filter',
sparepart_foto: null,
sparepart_code: 'SP-002',
sparepart_merk: 'Brand B',
sparepart_model: 'Model Y'
},
{
sparepart_id: 3,
sparepart_name: 'Cooling Fan Motor',
sparepart_description: 'Motor for cooling fan',
sparepart_foto: null,
sparepart_code: 'SP-003',
sparepart_merk: 'Brand C',
sparepart_model: 'Model Z'
},
]);
} finally {
setLoading(false);
}
};
const filteredSpareparts = spareparts.filter(sp =>
sp.sparepart_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
sp.sparepart_code.toLowerCase().includes(searchTerm.toLowerCase()) ||
sp.sparepart_merk?.toLowerCase().includes(searchTerm.toLowerCase()) ||
sp.sparepart_model?.toLowerCase().includes(searchTerm.toLowerCase())
);
const handleSparepartToggle = async (sparepartId) => {
if (isReadOnly) return;
const isCurrentlySelected = selectedSparepartIds.includes(sparepartId);
// If brandId is provided, save immediately to database
if (brandId) {
try {
setLoading(true);
if (isCurrentlySelected) {
// Remove from database
await removeSparepartFromBrand(brandId, sparepartId);
message.success('Sparepart removed from brand successfully');
} else {
// Add to database
await addSparepartToBrand(brandId, sparepartId);
message.success('Sparepart added to brand successfully');
}
// Update local state
const newSelectedIds = isCurrentlySelected
? selectedSparepartIds.filter(id => id !== sparepartId)
: [...selectedSparepartIds, sparepartId];
onSparepartChange(newSelectedIds);
} catch (error) {
message.error(error.message || 'Failed to update sparepart');
} finally {
setLoading(false);
}
} else {
// If no brandId (add mode), just update local state
const newSelectedIds = isCurrentlySelected
? selectedSparepartIds.filter(id => id !== sparepartId)
: [...selectedSparepartIds, sparepartId];
onSparepartChange(newSelectedIds);
}
};
const isSelected = (sparepartId) => selectedSparepartIds.includes(sparepartId);
const combinedLoading = loading || externalLoading;
return (
<div>
<div style={{ marginBottom: 16 }}>
<Space style={{ width: '100%', justifyContent: 'space-between' }}>
<Title level={5} style={{ margin: 0 }}>
Select Spareparts
</Title>
<div style={{ position: 'relative', width: '200px' }}>
<input
type="text"
placeholder="Search spareparts..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
style={{
padding: '8px 30px 8px 12px',
border: '1px solid #d9d9d9',
borderRadius: '6px',
width: '100%'
}}
/>
<SearchOutlined
style={{
position: 'absolute',
right: '10px',
top: '50%',
transform: 'translateY(-50%)',
color: '#bfbfbf'
}}
/>
</div>
</Space>
</div>
{combinedLoading ? (
<div style={{ textAlign: 'center', padding: '40px' }}>
<Spin size="large" />
</div>
) : filteredSpareparts.length === 0 ? (
<Empty
description="No spareparts found"
image={Empty.PRESENTED_IMAGE_SIMPLE}
/>
) : (
<Row gutter={[16, 16]}>
{filteredSpareparts.map(sparepart => (
<Col xs={24} sm={12} md={12} lg={12} key={sparepart.sparepart_id}>
<CustomSparepartCard
sparepart={sparepart}
isSelected={isSelected(sparepart.sparepart_id)}
isReadOnly={isReadOnly}
showPreview={true}
showDelete={true}
onCardClick={() => handleSparepartToggle(sparepart.sparepart_id)}
onDelete={() => {
// When delete button is clicked, remove from selection
const newSelectedIds = selectedSparepartIds.filter(id => id !== sparepart.sparepart_id);
onSparepartChange(newSelectedIds);
// Also remove from database if brandId exists
if (brandId) {
removeSparepartFromBrand(brandId, sparepart.sparepart_id)
.then(() => message.success('Sparepart removed successfully'))
.catch(error => message.error(error.message || 'Failed to remove sparepart'));
}
}}
/>
</Col>
))}
</Row>
)}
{selectedSparepartIds.length > 0 && (
<div style={{ marginTop: 16 }}>
<Text strong>Selected Spareparts: </Text>
<Space wrap>
{selectedSparepartIds.map(id => {
const sparepart = spareparts.find(sp => sp.sparepart_id === id);
return sparepart ? (
<Tag key={id} color="green">
{sparepart.sparepart_name} (ID: {id})
</Tag>
) : (
<Tag key={id} color="green">
Sparepart ID: {id}
</Tag>
);
})}
</Space>
</div>
)}
</div>
);
};
export default SparepartCardSelect;

View File

@@ -1,26 +0,0 @@
import React from 'react';
import { Card, Divider, Typography } from 'antd';
import SparepartCardSelect from './SparepartCardSelect';
const { Text } = Typography;
const SparepartForm = ({
sparepartForm,
selectedSparepartIds,
onSparepartChange,
isReadOnly = false
}) => {
return (
<div style={{ minHeight: '400px' }}>
<Card title="Spareparts" style={{ minHeight: '100%' }}>
<SparepartCardSelect
selectedSparepartIds={selectedSparepartIds}
onSparepartChange={onSparepartChange}
isReadOnly={isReadOnly}
/>
</Card>
</div>
);
};
export default SparepartForm;

View File

@@ -7,7 +7,7 @@ import CustomSparepartCard from './CustomSparepartCard';
const { Text, Title } = Typography;
const { Option } = Select;
const SingleSparepartSelect = ({
const SparepartSelect = ({
selectedSparepartIds = [],
onSparepartChange,
isReadOnly = false
@@ -32,45 +32,25 @@ const SingleSparepartSelect = ({
}
}, [selectedSparepartIds, spareparts]);
const fetchSpareparts = async () => {
const fetchSpareparts = async (searchQuery = '') => {
setLoading(true);
try {
const params = new URLSearchParams();
params.set('limit', '1000');
if (searchQuery && searchQuery.trim() !== '') {
params.set('criteria', searchQuery.trim());
}
const response = await getAllSparepart(params);
if (response && (response.statusCode === 200 || response.data)) {
const sparepartData = response.data?.data || response.data || [];
setSpareparts(sparepartData);
} else {
setSpareparts([
{
sparepart_id: 1,
sparepart_name: 'Compressor Oil Filter',
sparepart_description: 'Oil filter for compressor',
sparepart_foto: null,
sparepart_code: 'SP-001',
sparepart_merk: 'Brand A',
sparepart_model: 'Model X',
is_active: true,
stock_quantity: 50
}
]);
setSpareparts([]);
}
} catch (error) {
setSpareparts([
{
sparepart_id: 1,
sparepart_name: 'Compressor Oil Filter',
sparepart_description: 'Oil filter for compressor',
sparepart_foto: null,
sparepart_code: 'SP-001',
sparepart_merk: 'Brand A',
sparepart_model: 'Model X',
is_active: true,
stock_quantity: 50
}
]);
setSpareparts([]);
} finally {
setLoading(false);
}
@@ -93,6 +73,17 @@ const SingleSparepartSelect = ({
setDropdownOpen(false);
};
const handleSearch = (value) => {
fetchSpareparts(value);
};
const onDropdownOpenChange = (open) => {
setDropdownOpen(open);
if (open) {
fetchSpareparts();
}
};
const handleRemoveSparepart = (sparepartId) => {
const newSelectedSpareparts = selectedSpareparts.filter(sp => sp.sparepart_id !== sparepartId);
setSelectedSpareparts(newSelectedSpareparts);
@@ -111,7 +102,7 @@ const SingleSparepartSelect = ({
isSelected={isSelected}
isReadOnly={isReadOnly}
showPreview={true}
showDelete={isAlreadySelected && !isReadOnly} // Show delete only for already selected items
showDelete={isAlreadySelected && !isReadOnly}
onCardClick={!isAlreadySelected && !isReadOnly ? () => handleSparepartSelect(sparepart.sparepart_id) : undefined}
onDelete={() => handleRemoveSparepart(sparepart.sparepart_id)}
style={{
@@ -124,26 +115,34 @@ const SingleSparepartSelect = ({
return (
<>
<div>
{!isReadOnly && (
<div style={{ marginBottom: 16 }}>
<Select
placeholder="Search and select sparepart..."
style={{ width: '100%' }}
loading={loading}
onSelect={handleSparepartSelect}
value={null}
showSearch
filterOption={(input, option) =>
option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
open={dropdownOpen}
onDropdownVisibleChange={setDropdownOpen}
suffixIcon={<PlusOutlined />}
>
{spareparts
.filter(sparepart => !selectedSpareparts.some(sp => sp.sparepart_id === sparepart.sparepart_id))
.map((sparepart) => (
{/* Fixed Search Section */}
{!isReadOnly && (
<div style={{
marginBottom: 16,
position: 'sticky',
top: 0,
zIndex: 10,
backgroundColor: 'white',
padding: '8px 0',
borderBottom: '1px solid #f0f0f0'
}}>
<Select
placeholder="search and select sparepart"
style={{ width: '100%' }}
loading={loading}
onSelect={handleSparepartSelect}
value={null}
showSearch
onSearch={handleSearch}
filterOption={false}
open={dropdownOpen}
onOpenChange={onDropdownOpenChange}
suffixIcon={<PlusOutlined />}
>
{spareparts
.filter(sparepart => !selectedSpareparts.some(sp => sp.sparepart_id === sparepart.sparepart_id))
.slice(0, 5)
.map((sparepart) => (
<Option key={sparepart.sparepart_id} value={sparepart.sparepart_id}>
<div>
<Text strong>{sparepart.sparepart_name || sparepart.name || 'Unnamed'}</Text>
@@ -153,31 +152,31 @@ const SingleSparepartSelect = ({
</div>
</Option>
))}
</Select>
</div>
)}
<div>
{selectedSpareparts.length > 0 ? (
<div>
<Title level={5} style={{ marginBottom: 16 }}>
Selected Spareparts ({selectedSpareparts.length})
</Title>
<Row gutter={[16, 16]}>
{selectedSpareparts.map(sparepart => renderSparepartCard(sparepart, true))}
</Row>
</div>
) : (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description="No spareparts selected"
style={{ margin: '20px 0' }}
/>
)}
</Select>
</div>
)}
{/* Scrollable Selected Items Section */}
<div>
{selectedSpareparts.length > 0 ? (
<div>
<Title level={5} style={{ marginBottom: 16 }}>
Selected Spareparts ({selectedSpareparts.length})
</Title>
<Row gutter={[16, 16]}>
{selectedSpareparts.map(sparepart => renderSparepartCard(sparepart, true))}
</Row>
</div>
) : (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description="No spareparts selected"
style={{ margin: '20px 0' }}
/>
)}
</div>
</>
);
};
export default SingleSparepartSelect;
export default SparepartSelect;

View File

@@ -194,7 +194,6 @@ export const useErrorCodeLogic = (errorCodeForm, fileList) => {
};
const handleSolutionStatusChange = (fieldId, status) => {
// Only update local state - form is already updated by Form.Item
setSolutionStatuses(prev => ({
...prev,
[fieldId]: status
@@ -213,8 +212,7 @@ export const useErrorCodeLogic = (errorCodeForm, fileList) => {
newSolutionTypes[fieldId] = solution.type_solution || 'text';
newSolutionStatuses[fieldId] = solution.is_active !== false;
newSolutionData[fieldId] = {
...solution,
brand_code_solution_id: solution.brand_code_solution_id
...solution
};
setTimeout(() => {

View File

@@ -15,7 +15,7 @@ export const useSolutionLogic = (solutionForm) => {
name: 'Solution 1',
status: true,
type: 'text',
text: 'Deskripsi untuk Solution 1',
text: 'Solution description',
file: null,
fileUpload: null
}
@@ -63,7 +63,7 @@ export const useSolutionLogic = (solutionForm) => {
solutionForm.setFieldValue(['solution_items', newKey, 'name'], defaultName);
solutionForm.setFieldValue(['solution_items', newKey, 'type'], 'text');
solutionForm.setFieldValue(['solution_items', newKey, 'text'], `Deskripsi untuk ${defaultName}`);
solutionForm.setFieldValue(['solution_items', newKey, 'text'], 'Solution description');
solutionForm.setFieldValue(['solution_items', newKey, 'status'], true);
solutionForm.setFieldValue(['solution_items', newKey, 'file'], null);
solutionForm.setFieldValue(['solution_items', newKey, 'fileUpload'], null);
@@ -112,22 +112,30 @@ export const useSolutionLogic = (solutionForm) => {
...solutionData,
fileUpload: null,
file: null,
text: solutionData.text || `Deskripsi untuk ${solutionData.name || 'Solution'}`
path_solution: null,
fileName: null,
text: solutionData.text || 'Solution description'
};
solutionForm.setFieldValue([...fieldName, 'fileUpload'], null);
solutionForm.setFieldValue([...fieldName, 'file'], null);
solutionForm.setFieldValue([...fieldName, 'path_solution'], null);
solutionForm.setFieldValue([...fieldName, 'fileName'], null);
solutionForm.setFieldValue([...fieldName, 'text'], updatedSolutionData.text);
} else if (value === 'file') {
const updatedSolutionData = {
...solutionData,
text: '',
fileUpload: null,
file: null
file: null,
path_solution: null,
fileName: null
};
solutionForm.setFieldValue([...fieldName, 'text'], '');
solutionForm.setFieldValue([...fieldName, 'fileUpload'], null);
solutionForm.setFieldValue([...fieldName, 'file'], null);
solutionForm.setFieldValue([...fieldName, 'path_solution'], null);
solutionForm.setFieldValue([...fieldName, 'fileName'], null);
}
}, 0);
};
@@ -141,6 +149,10 @@ export const useSolutionLogic = (solutionForm) => {
setSolutionTypes({ 0: 'text' });
setSolutionStatuses({ 0: true });
if (!solutionForm || !solutionForm.resetFields) {
return;
}
solutionForm.resetFields();
setTimeout(() => {
solutionForm.setFieldsValue({
@@ -149,7 +161,7 @@ export const useSolutionLogic = (solutionForm) => {
name: 'Solution 1',
status: true,
type: 'text',
text: '',
text: 'Solution description',
file: null,
fileUpload: null
}
@@ -158,17 +170,18 @@ export const useSolutionLogic = (solutionForm) => {
solutionForm.setFieldValue(['solution_items', 0, 'name'], 'Solution 1');
solutionForm.setFieldValue(['solution_items', 0, 'type'], 'text');
solutionForm.setFieldValue(['solution_items', 0, 'text'], 'Deskripsi untuk Solution 1');
solutionForm.setFieldValue(['solution_items', 0, 'text'], 'Solution description');
solutionForm.setFieldValue(['solution_items', 0, 'status'], true);
solutionForm.setFieldValue(['solution_items', 0, 'file'], null);
solutionForm.setFieldValue(['solution_items', 0, 'fileUpload'], null);
console.log('✅ Reset solution fields with proper structure');
console.log('Form values after reset:', solutionForm.getFieldsValue(true));
}, 100);
};
const checkFirstSolutionValid = () => {
if (!solutionForm || !solutionForm.getFieldsValue) {
return false;
}
const values = solutionForm.getFieldsValue();
const firstField = solutionFields[0];
@@ -177,7 +190,6 @@ export const useSolutionLogic = (solutionForm) => {
}
const solutionKey = firstField.key || firstField;
// Try both notations for compatibility
const commaPath = `solution_items,${solutionKey}`;
const dotPath = `solution_items.${solutionKey}`;
const firstSolution = values[commaPath] || values[dotPath];
@@ -204,7 +216,6 @@ export const useSolutionLogic = (solutionForm) => {
try {
solution = solutionForm.getFieldValue(['solution_items', key]);
} catch (error) {
// Silently handle errors
}
if (!solution && values.solution_items && values.solution_items[key]) {
@@ -233,7 +244,6 @@ export const useSolutionLogic = (solutionForm) => {
}
if (!solution) {
// Try to find the solution in the raw form structure
const rawValues = solutionForm.getFieldsValue();
if (rawValues.solution_items && rawValues.solution_items[key]) {
@@ -242,14 +252,14 @@ export const useSolutionLogic = (solutionForm) => {
}
if (!solution) {
return;
return;
}
const hasName = solution.name && solution.name.trim() !== '';
if (!hasName) {
return;
return;
}
const solutionType = solutionTypes[key] || solution.type || 'text';
@@ -273,35 +283,46 @@ export const useSolutionLogic = (solutionForm) => {
let pathSolution = '';
let fileObject = null;
if (solution.fileUpload && typeof solution.fileUpload === 'object' && Object.keys(solution.fileUpload).length > 0) {
pathSolution = solution.fileUpload.path_solution || solution.fileUpload.uploadPath || '';
fileObject = solution.fileUpload;
} else if (solution.file && typeof solution.file === 'object' && Object.keys(solution.file).length > 0) {
pathSolution = solution.file.path_solution || solution.file.uploadPath || '';
fileObject = solution.file;
} else if (solution.file && typeof solution.file === 'string' && solution.file.trim() !== '') {
pathSolution = solution.file;
}
let typeSolution = solutionTypes[key] || solution.type || 'text';
const typeSolution = solutionTypes[key] || solution.type || 'text';
if (typeSolution === 'file') {
if (fileObject && fileObject.type_solution) {
typeSolution = fileObject.type_solution;
if (solution.fileUpload && typeof solution.fileUpload === 'object' && Object.keys(solution.fileUpload).length > 0) {
pathSolution = solution.fileUpload.path_solution || solution.fileUpload.uploadPath || '';
fileObject = solution.fileUpload;
} else if (solution.file && typeof solution.file === 'object' && Object.keys(solution.file).length > 0) {
pathSolution = solution.file.path_solution || solution.file.uploadPath || '';
fileObject = solution.file;
} else if (solution.file && typeof solution.file === 'string' && solution.file.trim() !== '') {
pathSolution = solution.file;
} else if (solution.path_solution && solution.path_solution.trim() !== '') {
pathSolution = solution.path_solution;
} else {
typeSolution = 'image';
}
}
let finalTypeSolution = typeSolution;
if (typeSolution === 'file') {
if (fileObject && fileObject.type_solution) {
finalTypeSolution = fileObject.type_solution;
} else {
finalTypeSolution = 'image';
}
}
const finalSolution = {
solution_name: solution.name,
type_solution: typeSolution,
text_solution: solution.text || '',
path_solution: pathSolution,
type_solution: finalTypeSolution,
is_active: solution.status !== false && solution.status !== undefined ? solution.status : (solutionStatuses[key] !== false),
};
if (typeSolution === 'text') {
finalSolution.text_solution = solution.text || '';
finalSolution.path_solution = '';
} else {
finalSolution.text_solution = '';
finalSolution.path_solution = pathSolution;
}
result.push(finalSolution);
});
@@ -323,7 +344,7 @@ export const useSolutionLogic = (solutionForm) => {
const newStatuses = {};
solutions.forEach((solution, index) => {
const key = solution.id || index;
const key = solution.brand_code_solution_id || solution.id || index;
let fileObject = null;
if (solution.path_solution && solution.path_solution.trim() !== '') {
@@ -349,7 +370,8 @@ export const useSolutionLogic = (solutionForm) => {
text: solution.text_solution || '',
file: fileObject,
fileUpload: fileObject,
status: solution.is_active !== false
status: solution.is_active !== false,
path_solution: solution.path_solution || ''
};
newTypes[key] = isFileType ? 'file' : 'text';
newStatuses[key] = solution.is_active !== false;
@@ -367,7 +389,8 @@ export const useSolutionLogic = (solutionForm) => {
text: solution.text,
file: solution.file,
fileUpload: solution.fileUpload,
status: solution.status
status: solution.status,
path_solution: solution.path_solution
};
});
@@ -382,7 +405,8 @@ export const useSolutionLogic = (solutionForm) => {
text: solution.text,
file: solution.file,
fileUpload: solution.fileUpload,
status: solution.status
status: solution.status,
path_solution: solution.path_solution
};
});
@@ -396,6 +420,7 @@ export const useSolutionLogic = (solutionForm) => {
form.setFieldValue([`solution_items,${key}`, 'file'], solution.file);
form.setFieldValue([`solution_items,${key}`, 'fileUpload'], solution.fileUpload);
form.setFieldValue([`solution_items,${key}`, 'status'], solution.status);
form.setFieldValue([`solution_items,${key}`, 'path_solution'], solution.path_solution);
form.setFieldValue(['solution_items', key, 'name'], solution.name);
form.setFieldValue(['solution_items', key, 'type'], solution.type);
@@ -403,6 +428,7 @@ export const useSolutionLogic = (solutionForm) => {
form.setFieldValue(['solution_items', key, 'file'], solution.file);
form.setFieldValue(['solution_items', key, 'fileUpload'], solution.fileUpload);
form.setFieldValue(['solution_items', key, 'status'], solution.status);
form.setFieldValue(['solution_items', key, 'path_solution'], solution.path_solution);
});
setSolutionTypes(newTypes);