Merge pull request 'lavoce' (#22) from lavoce into main

Reviewed-on: #22
This commit is contained in:
2025-11-25 03:50:54 +00:00
27 changed files with 2178 additions and 1611 deletions

View File

@@ -10,11 +10,13 @@ import Home from './pages/home/Home';
import Blank from './pages/blank/Blank'; import Blank from './pages/blank/Blank';
// Master // Master
import IndexDevice from './pages/master/device/IndexDevice'; import IndexPlantSubSection from './pages/master/plantSubSection/IndexPlantSubSection';
import IndexTag from './pages/master/tag/IndexTag';
import IndexUnit from './pages/master/unit/IndexUnit';
import IndexBrandDevice from './pages/master/brandDevice/IndexBrandDevice'; import IndexBrandDevice from './pages/master/brandDevice/IndexBrandDevice';
import IndexDevice from './pages/master/device/IndexDevice';
import IndexUnit from './pages/master/unit/IndexUnit';
import IndexTag from './pages/master/tag/IndexTag';
import IndexStatus from './pages/master/status/IndexStatus'; import IndexStatus from './pages/master/status/IndexStatus';
import IndexSparepart from './pages/master/sparepart/IndexSparepart';
import IndexShift from './pages/master/shift/IndexShift'; import IndexShift from './pages/master/shift/IndexShift';
// Brand device // Brand device
import AddBrandDevice from './pages/master/brandDevice/AddBrandDevice'; import AddBrandDevice from './pages/master/brandDevice/AddBrandDevice';
@@ -34,6 +36,8 @@ import IndexNotification from './pages/notification/IndexNotification';
import IndexRole from './pages/role/IndexRole'; import IndexRole from './pages/role/IndexRole';
import IndexUser from './pages/user/IndexUser'; import IndexUser from './pages/user/IndexUser';
import IndexContact from './pages/contact/IndexContact'; import IndexContact from './pages/contact/IndexContact';
import DetailNotificationTab from './pages/detailNotification/IndexDetailNotification';
import IndexVerificationSparepart from './pages/verificationSparepart/IndexVerificationSparepart';
import SvgTest from './pages/home/SvgTest'; import SvgTest from './pages/home/SvgTest';
import SvgOverviewCompressor from './pages/home/SvgOverviewCompressor'; import SvgOverviewCompressor from './pages/home/SvgOverviewCompressor';
@@ -46,7 +50,6 @@ import SvgAirDryerB from './pages/home/SvgAirDryerB';
import SvgAirDryerC from './pages/home/SvgAirDryerC'; import SvgAirDryerC from './pages/home/SvgAirDryerC';
import IndexHistoryAlarm from './pages/history/alarm/IndexHistoryAlarm'; import IndexHistoryAlarm from './pages/history/alarm/IndexHistoryAlarm';
import IndexHistoryEvent from './pages/history/event/IndexHistoryEvent'; import IndexHistoryEvent from './pages/history/event/IndexHistoryEvent';
import IndexPlantSubSection from './pages/master/plantSubSection/IndexPlantSubSection';
const App = () => { const App = () => {
return ( return (
@@ -57,6 +60,14 @@ const App = () => {
<Route path="/signin" element={<SignIn />} /> <Route path="/signin" element={<SignIn />} />
<Route path="/signup" element={<SignUp />} /> <Route path="/signup" element={<SignUp />} />
<Route path="/svg" element={<SvgTest />} /> <Route path="/svg" element={<SvgTest />} />
<Route
path="/detail-notification/:notificationId"
element={<DetailNotificationTab />}
/>
<Route
path="/verification-sparepart/:notificationId"
element={<IndexVerificationSparepart />}
/>
{/* Protected Routes */} {/* Protected Routes */}
<Route path="/dashboard" element={<ProtectedRoute />}> <Route path="/dashboard" element={<ProtectedRoute />}>
@@ -79,13 +90,23 @@ const App = () => {
<Route path="device" element={<IndexDevice />} /> <Route path="device" element={<IndexDevice />} />
<Route path="tag" element={<IndexTag />} /> <Route path="tag" element={<IndexTag />} />
<Route path="unit" element={<IndexUnit />} /> <Route path="unit" element={<IndexUnit />} />
<Route path="sparepart" element={<IndexSparepart />} />
<Route path="brand-device" element={<IndexBrandDevice />} /> <Route path="brand-device" element={<IndexBrandDevice />} />
<Route path="brand-device/add" element={<AddBrandDevice />} /> <Route path="brand-device/add" element={<AddBrandDevice />} />
<Route path="brand-device/edit/:id" element={<EditBrandDevice />} /> <Route path="brand-device/edit/:id" element={<EditBrandDevice />} />
<Route path="brand-device/view/:id" element={<ViewBrandDevice />} /> <Route path="brand-device/view/:id" element={<ViewBrandDevice />} />
<Route path="brand-device/edit/:id/files/:fileType/:fileName" element={<ViewFilePage />} /> <Route
<Route path="brand-device/view/:id/files/:fileType/:fileName" element={<ViewFilePage />} /> path="brand-device/edit/:id/files/:fileType/:fileName"
<Route path="brand-device/view/temp/files/:fileName" element={<ViewFilePage />} /> element={<ViewFilePage />}
/>
<Route
path="brand-device/view/:id/files/:fileType/:fileName"
element={<ViewFilePage />}
/>
<Route
path="brand-device/view/temp/files/:fileName"
element={<ViewFilePage />}
/>
<Route path="plant-sub-section" element={<IndexPlantSubSection />} /> <Route path="plant-sub-section" element={<IndexPlantSubSection />} />
<Route path="shift" element={<IndexShift />} /> <Route path="shift" element={<IndexShift />} />
<Route path="status" element={<IndexStatus />} /> <Route path="status" element={<IndexStatus />} />

50
src/api/sparepart.jsx Normal file
View File

@@ -0,0 +1,50 @@
import { SendRequest } from '../components/Global/ApiRequest';
const getAllSparepart = async (queryParams) => {
const response = await SendRequest({
method: 'get',
prefix: `sparepart?${queryParams.toString()}`,
});
return response.data;
};
const getSparepartById = async (id) => {
const response = await SendRequest({
method: 'get',
prefix: `sparepart/${id}`,
});
return response.data;
};
const createSparepart = async (queryParams) => {
const response = await SendRequest({
method: 'post',
prefix: `sparepart`,
params: queryParams,
});
return response.data;
};
const updateSparepart = async (id, queryParams) => {
const response = await SendRequest({
method: 'put',
prefix: `sparepart/${id}`,
params: queryParams,
});
return response.data;
};
const deleteSparepart = async (id) => {
const response = await SendRequest({
method: 'delete',
prefix: `sparepart/${id}`,
});
return response.data;
};
export { getAllSparepart, getSparepartById, createSparepart, updateSparepart, deleteSparepart };

View File

@@ -58,34 +58,34 @@ const CardList = ({
style={getCardStyle(fieldColor ? item[fieldColor] : cardColor)} style={getCardStyle(fieldColor ? item[fieldColor] : cardColor)}
actions={[ actions={[
showPreviewModal && ( showPreviewModal && (
<EyeOutlined <EyeOutlined
style={{ color: '#1890ff' }} style={{ color: '#1890ff' }}
key="preview" key="preview"
onClick={() => showPreviewModal(item)} onClick={() => showPreviewModal(item)}
/> />
), ),
showEditModal && ( showEditModal && (
<EditOutlined <EditOutlined
style={{ color: '#faad14' }} style={{ color: '#faad14' }}
key="edit" key="edit"
onClick={() => showEditModal(item)} onClick={() => showEditModal(item)}
/> />
), ),
showDeleteDialog && ( showDeleteDialog && (
<DeleteOutlined <DeleteOutlined
style={{ color: '#ff1818' }} style={{ color: '#ff1818' }}
key="delete" key="delete"
onClick={() => showDeleteDialog(item)} onClick={() => showDeleteDialog(item)}
/> />
), ),
].filter(Boolean)} // <== Hapus elemen yang undefined ].filter(Boolean)} // <== Hapus elemen yang undefined
> >
<div style={{ textAlign: 'left' }}> <div style={{ textAlign: 'left' }}>
{column.map((itemCard, index) => ( {column.map((itemCard, index) => (
<React.Fragment key={index}> <React.Fragment key={index}>
{!itemCard.hidden && {!itemCard.hidden &&
itemCard.title !== 'No' && itemCard.title !== 'No' &&
itemCard.title !== 'Aksi' && ( itemCard.title !== 'Action' && (
<p style={{ margin: '8px 0' }}> <p style={{ margin: '8px 0' }}>
<Text strong>{itemCard.title}:</Text>{' '} <Text strong>{itemCard.title}:</Text>{' '}
{itemCard.render {itemCard.render

View File

@@ -32,6 +32,7 @@ import {
SlidersOutlined, SlidersOutlined,
SnippetsOutlined, SnippetsOutlined,
ContactsOutlined, ContactsOutlined,
ToolOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
const { Text } = Typography; const { Text } = Typography;
@@ -142,6 +143,11 @@ const allItems = [
icon: <SafetyOutlined style={{ fontSize: '19px' }} />, icon: <SafetyOutlined style={{ fontSize: '19px' }} />,
label: <Link to="/master/status">Status</Link>, label: <Link to="/master/status">Status</Link>,
}, },
{
key: 'master-sparepart',
icon: <ToolOutlined style={{ fontSize: '19px' }} />,
label: <Link to="/master/sparepart">sparepart</Link>,
},
// { // {
// key: 'master-shift', // key: 'master-shift',
// icon: <ClockCircleOutlined style={{ fontSize: '19px' }} />, // icon: <ClockCircleOutlined style={{ fontSize: '19px' }} />,
@@ -259,6 +265,7 @@ const LayoutMenu = () => {
unit: 'master-unit', unit: 'master-unit',
tag: 'master-tag', tag: 'master-tag',
status: 'master-status', status: 'master-status',
sparepart: 'master-sparepart',
shift: 'master-shift', shift: 'master-shift',
}; };
return masterKeyMap[subPath] || `master-${subPath}`; return masterKeyMap[subPath] || `master-${subPath}`;

View File

@@ -14,34 +14,22 @@ const DetailContact = memo(function DetailContact(props) {
name: '', name: '',
phone: '', phone: '',
is_active: true, is_active: true,
contact_type: 'operator', contact_type: '',
}; };
const [formData, setFormData] = useState(defaultData); const [formData, setFormData] = useState(defaultData);
const handleInputChange = (e) => { const handleInputChange = (e) => {
let name, value; const { name, value } = e.target;
if (e && e.target) {
name = e.target.name;
value = e.target.value;
} else if (e && e.type === 'change') {
name = e.name || e.target?.name;
value = e.value !== undefined ? e.value : e.checked;
} else if (typeof e === 'string' || typeof e === 'number') {
// Handle Select onChange
value = e;
name = 'contact_type';
} else {
return;
}
// Validasi untuk field phone - hanya angka yang diperbolehkan // Validasi untuk field phone - hanya angka yang diperbolehkan
if (name === 'phone') { if (name === 'phone') {
value = value.replace(/[^0-9+\-\s()]/g, ''); const cleanedValue = value.replace(/[^0-9+\-\s()]/g, '');
} setFormData((prev) => ({
...prev,
if (name) { [name]: cleanedValue,
}));
} else {
setFormData((prev) => ({ setFormData((prev) => ({
...prev, ...prev,
[name]: value, [name]: value,
@@ -49,6 +37,13 @@ const DetailContact = memo(function DetailContact(props) {
} }
}; };
const handleContactTypeChange = (value) => {
setFormData((prev) => ({
...prev,
contact_type: value,
}));
};
const handleStatusToggle = (checked) => { const handleStatusToggle = (checked) => {
setFormData({ setFormData({
...formData, ...formData,
@@ -59,6 +54,21 @@ const DetailContact = memo(function DetailContact(props) {
const handleSave = async () => { const handleSave = async () => {
setConfirmLoading(true); setConfirmLoading(true);
// Validation rules
const validationRules = [
{ field: 'name', label: 'Contact Name', required: true },
{ field: 'phone', label: 'Phone', required: true },
{ field: 'contact_type', label: 'Contact Type', required: true },
];
if (
validateRun(formData, validationRules, (errorMessages) => {
NotifOk({ icon: 'warning', title: 'Peringatan', message: errorMessages });
setConfirmLoading(false);
})
)
return;
// Custom validation untuk name - minimal 3 karakter // Custom validation untuk name - minimal 3 karakter
if (formData.name && formData.name.length < 3) { if (formData.name && formData.name.length < 3) {
NotifOk({ NotifOk({
@@ -82,21 +92,6 @@ const DetailContact = memo(function DetailContact(props) {
return; return;
} }
// Validation rules
const validationRules = [
{ field: 'name', label: 'Contact Name', required: true },
{ field: 'phone', label: 'Phone', required: true },
{ field: 'contact_type', label: 'Contact Type', required: true },
];
if (
validateRun(formData, validationRules, (errorMessages) => {
NotifOk({ icon: 'warning', title: 'Peringatan', message: errorMessages });
setConfirmLoading(false);
})
)
return;
try { try {
const contactData = { const contactData = {
contact_name: formData.name, contact_name: formData.name,
@@ -107,7 +102,10 @@ const DetailContact = memo(function DetailContact(props) {
let response; let response;
if (props.actionMode === 'edit') { if (props.actionMode === 'edit') {
response = await updateContact(props.selectedData.contact_id || props.selectedData.id, contactData); response = await updateContact(
props.selectedData.contact_id || props.selectedData.id,
contactData
);
} else { } else {
response = await createContact(contactData); response = await createContact(contactData);
} }
@@ -115,7 +113,7 @@ const DetailContact = memo(function DetailContact(props) {
NotifAlert({ NotifAlert({
icon: 'success', icon: 'success',
title: 'Berhasil', title: 'Berhasil',
message: `Data Contact berhasil ${ message: `Data Contact "${formData.name}" berhasil ${
props.actionMode === 'add' ? 'ditambahkan' : 'diperbarui' props.actionMode === 'add' ? 'ditambahkan' : 'diperbarui'
}.`, }.`,
}); });
@@ -145,15 +143,16 @@ const DetailContact = memo(function DetailContact(props) {
setFormData({ setFormData({
name: props.selectedData.contact_name || props.selectedData.name, name: props.selectedData.contact_name || props.selectedData.name,
phone: props.selectedData.contact_phone || props.selectedData.phone, phone: props.selectedData.contact_phone || props.selectedData.phone,
is_active: props.selectedData.is_active || props.selectedData.status === 'active', is_active:
contact_type: props.selectedData.contact_type || props.contactType || 'operator', props.selectedData.is_active || props.selectedData.status === 'active',
contact_type: props.selectedData.contact_type || props.contactType || '',
}); });
} else if (props.actionMode === 'add') { } else if (props.actionMode === 'add') {
setFormData({ setFormData({
name: '', name: '',
phone: '', phone: '',
is_active: true, is_active: true,
contact_type: props.contactType === 'all' ? 'operator' : props.contactType || 'operator', contact_type: props.contactType === 'all' ? '' : props.contactType || '',
}); });
} }
} }
@@ -256,8 +255,8 @@ const DetailContact = memo(function DetailContact(props) {
<Text strong>Contact Type</Text> <Text strong>Contact Type</Text>
<Text style={{ color: 'red' }}> *</Text> <Text style={{ color: 'red' }}> *</Text>
<Select <Select
value={formData.contact_type} value={formData.contact_type || undefined}
onChange={handleInputChange} onChange={handleContactTypeChange}
placeholder="Select Contact Type" placeholder="Select Contact Type"
disabled={props.readOnly} disabled={props.readOnly}
style={{ width: '100%' }} style={{ width: '100%' }}

View File

@@ -0,0 +1,357 @@
import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
Layout,
Card,
Row,
Col,
Typography,
Space,
Button,
Spin,
Result,
Input,
} from 'antd';
import {
ArrowLeftOutlined,
CloseCircleFilled,
WarningFilled,
CheckCircleFilled,
InfoCircleFilled,
CloseOutlined,
BookOutlined,
ToolOutlined,
HistoryOutlined,
FilePdfOutlined,
PlusOutlined,
UserOutlined,
} from '@ant-design/icons';
// Path disesuaikan karena lokasi file berubah
// import { getNotificationById } from '../../api/notification'; // Dihapus karena belum ada di file API
import UserHistoryModal from '../notification/component/UserHistoryModal';
import LogHistoryModal from '../notification/component/LogHistoryModal';
const { Content } = Layout;
const { Text, Paragraph, Link } = Typography;
// Menggunakan kembali fungsi transform dari ListNotification untuk konsistensi data
const transformNotificationData = (item) => ({
id: `notification-${item.notification_error_id || 'dummy'}-0`,
type: item.is_read ? 'resolved' : item.is_delivered ? 'warning' : 'critical',
title: item.device_name || 'Unknown Device',
issue: item.error_code_name || 'Unknown Error',
description: `${item.error_code} - ${item.error_code_name}`,
timestamp: new Date(item.created_at || Date.now()).toLocaleString('id-ID'),
location: item.device_location || 'Location not specified',
details: item.message_error_issue || 'No details available',
link: '#',
subsection: item.solution_name || 'N/A',
isRead: item.is_read || false,
status: item.is_read ? 'Resolved' : item.is_delivered ? 'Delivered' : 'Pending',
tag: item.error_code,
plc: item.plc || 'N/A',
});
const getDummyNotificationById = (id) => {
console.log("Fetching dummy data for ID:", id);
// Data mentah dummy, seolah-olah dari API
const rawDummyData = { device_name: 'Compressor C-101', error_code_name: 'High Temperature', error_code: 'TEMP-H-303', device_location: 'Gudang Produksi A', message_error_issue: 'Suhu kompresor terdeteksi melebihi ambang batas aman.', is_delivered: true, plc: 'PLC-UTL-01' };
// Mengolah data mentah dummy menggunakan transform function
return transformNotificationData(rawDummyData);
};
const getIconAndColor = (type) => {
switch (type) {
case 'critical':
return { IconComponent: CloseCircleFilled, color: '#ff4d4f', bgColor: '#fff1f0' };
case 'warning':
return { IconComponent: WarningFilled, color: '#faad14', bgColor: '#fffbe6' };
case 'resolved':
return { IconComponent: CheckCircleFilled, color: '#52c41a', bgColor: '#f6ffed' };
default:
return { IconComponent: InfoCircleFilled, color: '#1890ff', bgColor: '#e6f7ff' };
}
};
const DetailNotificationTab = () => {
const { notificationId } = useParams(); // Mungkin perlu disesuaikan jika route berbeda
const navigate = useNavigate();
const [notification, setNotification] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [modalContent, setModalContent] = useState(null); // 'user', 'log', atau null
const [isAddingLog, setIsAddingLog] = useState(false);
const logHistoryData = [
{
id: 1,
timestamp: '04-11-2025 11:55 WIB',
addedBy: {
name: 'Budi Santoso',
phone: '081122334455',
},
description: 'Suhu sudah coba diturunkan, namun masih belum mencapai treshold aman.',
},
{
id: 2,
timestamp: '04-11-2025 11:45 WIB',
addedBy: {
name: 'John Doe',
phone: '081234567890',
},
description: 'Suhu sudah coba diturunkan, namun masih belum mencapai treshold aman.',
},
{
id: 3,
timestamp: '04-11-2025 11:40 WIB',
addedBy: {
name: 'Jane Smith',
phone: '087654321098',
},
description: 'Suhu sudah coba diturunkan, namun masih belum mencapai treshold aman.',
},
];
useEffect(() => {
const fetchDetail = async () => {
try {
setLoading(true);
// Ganti dengan fungsi API asli Anda
// const response = await getNotificationById(notificationId);
// setNotification(response.data);
// Menggunakan data dummy untuk sekarang
const dummyData = getDummyNotificationById(notificationId);
if (dummyData) {
setNotification(dummyData);
} else {
throw new Error('Notification not found');
}
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
fetchDetail();
}, [notificationId]);
if (loading) {
return (
<Layout style={{ minHeight: '100vh', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
<Spin size="large" />
</Layout>
);
}
if (error || !notification) {
return (
<Layout style={{ minHeight: '100vh', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
<Result
status="404"
title="404"
subTitle="Sorry, the notification you visited does not exist."
extra={<Button type="primary" onClick={() => navigate('/notification')}>Back to List</Button>}
/>
</Layout>
);
}
const { color } = getIconAndColor(notification.type);
return (
<Layout style={{ padding: '24px', backgroundColor: '#f0f2f5' }}>
<Content>
<Card>
<div style={{ borderBottom: '1px solid #f0f0f0', paddingBottom: '16px', marginBottom: '24px' }}>
<Row justify="space-between" align="middle">
<Col>
<Button
type="text"
icon={<ArrowLeftOutlined />}
onClick={() => navigate('/notification')}
style={{ paddingLeft: 0 }}
>
Back to notification list
</Button>
</Col>
<Col>
<Button
icon={<UserOutlined />}
onClick={() => setModalContent('user')}
>
User History
</Button>
</Col>
</Row>
<div style={{ backgroundColor: '#f6ffed', border: '1px solid #b7eb8f', borderRadius: '4px', padding: '8px 16px', textAlign: 'center', marginTop: '16px' }}>
<Typography.Title level={4} style={{ margin: 0, color: '#262626' }}>
Error Notification Detail
</Typography.Title>
</div>
</div>
<Space direction="vertical" size="large" style={{ width: '100%' }}>
<Row gutter={[24, 24]}>
{/* Kolom Kiri: Data Kompresor */}
<Col xs={24} lg={12}>
<Card size="small" style={{ height: '100%', borderColor: '#d4380d' }} bodyStyle={{ padding: '16px' }}>
<Space direction="vertical" size="large" style={{ width: '100%' }}>
<Row gutter={16} align="middle">
<Col>
<div style={{ width: '32px', height: '32px', borderRadius: '50%', backgroundColor: '#d4380d', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#ffffff', fontSize: '18px' }}><CloseOutlined /></div>
</Col>
<Col>
<Text>{notification.title}</Text>
<div style={{ marginTop: '2px' }}><Text strong style={{ fontSize: '16px' }}>{notification.issue}</Text></div>
</Col>
</Row>
<div>
<Text strong>Plant Subsection</Text>
<div>{notification.subsection}</div>
<Text strong style={{ display: 'block', marginTop: '8px' }}>Time</Text>
<div>{notification.timestamp}</div>
</div>
<div style={{ border: '1px solid #d4380d', borderRadius: '4px', padding: '8px', background: 'linear-gradient(to right, #ffe7e6, #ffffff)' }}>
<Row justify="space-around" align="middle">
<Col><Text style={{ fontSize: '12px', color: color }}>Value</Text><div style={{ fontWeight: 'bold', fontSize: '16px', color: color }}>N/A</div></Col>
<Col><Text type="secondary" style={{ fontSize: '12px' }}>Treshold</Text><div style={{ fontWeight: 500 }}>N/A</div></Col>
</Row>
</div>
</Space>
</Card>
</Col>
{/* Kolom Kanan: Informasi Teknis */}
<Col xs={24} lg={12}>
<Card title="Informasi Teknis" size="small" style={{ height: '100%' }}>
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
<div><Text strong>PLC</Text><div>{notification.plc || 'N/A'}</div></div>
<div><Text strong>Status</Text><div style={{ color: '#faad14', fontWeight: 500 }}>{notification.status}</div></div>
<div><Text strong>Tag</Text><div style={{ fontFamily: 'monospace', backgroundColor: '#f0f0f0', padding: '2px 6px', borderRadius: '4px', display: 'inline-block' }}>{notification.tag}</div></div>
</Space>
</Card>
</Col>
</Row>
<Row gutter={[16, 16]}>
<Col xs={24} md={8}><Card hoverable bodyStyle={{ padding: '12px', textAlign: 'center' }}><Space><BookOutlined style={{ fontSize: '16px', color: '#1890ff' }} /><Text strong style={{ fontSize: '16px', color: '#262626' }}>Handling Guideline</Text></Space></Card></Col>
<Col xs={24} md={8}><Card hoverable bodyStyle={{ padding: '12px', textAlign: 'center' }}><Space><ToolOutlined style={{ fontSize: '16px', color: '#1890ff' }} /><Text strong style={{ fontSize: '16px', color: '#262626' }}>Spare Part</Text></Space></Card></Col>
<Col xs={24} md={8} onClick={() => setModalContent('log')} style={{ cursor: 'pointer' }}><Card hoverable bodyStyle={{ padding: '12px', textAlign: 'center' }}><Space><HistoryOutlined style={{ fontSize: '16px', color: '#1890ff' }} /><Text strong style={{ fontSize: '16px', color: '#262626' }}>Log Activity</Text></Space></Card></Col>
</Row>
<Row gutter={[16, 16]}>
<Col xs={24} md={8}>
<Card size="small" title="Guideline Documents" style={{ height: '100%' }}>
<Space direction="vertical" size="small" style={{ width: '100%' }}>
<Card size="small" hoverable>
<Text><FilePdfOutlined style={{ marginRight: '8px' }} /> Error 303.pdf</Text>
<Link href="#" target="_blank" style={{ fontSize: '12px', display: 'block', marginLeft: '24px' }}>lihat disini</Link>
</Card>
<Card size="small" hoverable>
<Text><FilePdfOutlined style={{ marginRight: '8px' }} /> SOP Kompresor.pdf</Text>
<Link href="#" target="_blank" style={{ fontSize: '12px', display: 'block', marginLeft: '24px' }}>lihat disini</Link>
</Card>
</Space>
</Card>
</Col>
<Col xs={24} md={8}>
<Card size="small" title="Required Spare Parts" style={{ height: '100%' }}>
<Space direction="vertical" size="small" style={{ width: '100%' }}>
<Card size="small">
<Row gutter={16} align="top">
<Col span={7} style={{ textAlign: 'center' }}>
<div style={{ width: '100%', height: '60px', backgroundColor: '#f0f0f0', display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: '4px', marginBottom: '8px' }}>
<ToolOutlined style={{ fontSize: '24px', color: '#bfbfbf' }} />
</div>
<Text style={{ fontSize: '12px', color: '#52c41a', fontWeight: 500 }}>Available</Text>
</Col>
<Col span={17}>
<Text strong>Air Filter</Text>
<Paragraph style={{ fontSize: '12px', margin: 0, color: '#595959' }}>Filters incoming air to remove dust.</Paragraph>
</Col>
</Row>
</Card>
</Space>
</Card>
</Col>
<Col span={8}>
<Card size="small" style={{ height: '100%' }}>
<Space direction="vertical" size="small" style={{ width: '100%' }}>
<Card
size="small"
bodyStyle={{
padding: '8px 12px',
backgroundColor: isAddingLog ? '#fafafa' : '#fff',
}}
>
<Space
direction="vertical"
style={{ width: '100%' }}
size="small"
>
{isAddingLog && (
<>
<Text strong style={{ fontSize: '12px' }}>
Add New Log / Update Progress
</Text>
<Input.TextArea
rows={2}
placeholder="Tuliskan update penanganan di sini..."
/>
</>
)}
<Button
type={isAddingLog ? 'primary' : 'dashed'}
size="small"
block
icon={!isAddingLog && <PlusOutlined />}
onClick={() => setIsAddingLog(!isAddingLog)}
>
{isAddingLog ? 'Submit Log' : 'Add Log'}
</Button>
</Space>
</Card>
{logHistoryData.map((log) => (
<Card
key={log.id}
size="small"
bodyStyle={{ padding: '8px 12px' }}
>
<Paragraph
style={{ fontSize: '12px', margin: 0 }}
ellipsis={{ rows: 2 }}
>
<Text strong>{log.addedBy.name}:</Text>{' '}
{log.description}
</Paragraph>
<Text type="secondary" style={{ fontSize: '11px' }}>
{log.timestamp}
</Text>
</Card>
))}
</Space>
</Card>
</Col>
</Row>
</Space>
</Card>
</Content>
<UserHistoryModal
visible={modalContent === 'user'}
onCancel={() => setModalContent(null)}
notificationData={notification}
/>
<LogHistoryModal
visible={modalContent === 'log'}
onCancel={() => setModalContent(null)}
notificationData={notification}
/>
</Layout>
);
};
export default DetailNotificationTab;

View File

@@ -1,20 +1,32 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { Divider, Typography, Button, Steps, Form, Row, Col, Card, ConfigProvider } from 'antd'; import {
Divider,
Typography,
Button,
Steps,
Form,
Row,
Col,
Card,
ConfigProvider,
Table,
Tag,
Space,
} from 'antd';
import { NotifAlert, NotifOk } from '../../../components/Global/ToastNotif'; import { NotifAlert, NotifOk } from '../../../components/Global/ToastNotif';
import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb'; import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb';
import { createBrand } from '../../../api/master-brand'; import { createBrand } from '../../../api/master-brand';
import BrandForm from './component/BrandForm'; import BrandForm from './component/BrandForm';
import ErrorCodeForm from './component/ErrorCodeForm';
import ErrorCodeSimpleForm from './component/ErrorCodeSimpleForm'; import ErrorCodeSimpleForm from './component/ErrorCodeSimpleForm';
import ErrorCodeTable from './component/ListErrorCode';
import ErrorCodeListModal from './component/ErrorCodeListModal'; import ErrorCodeListModal from './component/ErrorCodeListModal';
import FormActions from './component/FormActions'; import FormActions from './component/FormActions';
import SparepartForm from './component/SparepartForm';
import SolutionForm from './component/SolutionForm'; import SolutionForm from './component/SolutionForm';
import SparepartForm from './component/SparepartForm';
import { useSolutionLogic } from './hooks/solution'; import { useSolutionLogic } from './hooks/solution';
import { useSparepartLogic } from './hooks/sparepart'; import { useSparepartLogic } from './hooks/sparepart';
import { uploadFile, getFolderFromFileType } from '../../../api/file-uploads'; import { uploadFile, getFolderFromFileType } from '../../../api/file-uploads';
import { EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
const { Title } = Typography; const { Title } = Typography;
const { Step } = Steps; const { Step } = Steps;
@@ -44,8 +56,6 @@ const AddBrandDevice = () => {
const [formData, setFormData] = useState(defaultData); const [formData, setFormData] = useState(defaultData);
const [errorCodes, setErrorCodes] = useState([]); const [errorCodes, setErrorCodes] = useState([]);
const [errorCodeIcon, setErrorCodeIcon] = useState(null); const [errorCodeIcon, setErrorCodeIcon] = useState(null);
const [showErrorCodeModal, setShowErrorCodeModal] = useState(false);
const [sparepartImages, setSparepartImages] = useState({});
const { const {
solutionFields, solutionFields,
@@ -67,31 +77,16 @@ const AddBrandDevice = () => {
sparepartFields, sparepartFields,
sparepartTypes, sparepartTypes,
sparepartStatuses, sparepartStatuses,
sparepartsToDelete,
handleAddSparepartField, handleAddSparepartField,
handleRemoveSparepartField, handleRemoveSparepartField,
handleSparepartTypeChange, handleSparepartTypeChange,
handleSparepartStatusChange, handleSparepartStatusChange,
resetSparepartFields, resetSparepartFields,
getSparepartData, getSparepartData,
setSparepartForExistingRecord, setSparepartsForExistingRecord,
} = useSparepartLogic(sparepartForm); } = useSparepartLogic(sparepartForm);
// Handlers for sparepart image upload
const handleSparepartImageUpload = (fieldKey, imageData) => {
setSparepartImages(prev => ({
...prev,
[fieldKey]: imageData
}));
};
const handleSparepartImageRemove = (fieldKey) => {
setSparepartImages(prev => {
const newImages = { ...prev };
delete newImages[fieldKey];
return newImages;
});
};
useEffect(() => { useEffect(() => {
setBreadcrumbItems([ setBreadcrumbItems([
{ title: <span style={{ fontSize: '14px', fontWeight: 'bold' }}> Master</span> }, { title: <span style={{ fontSize: '14px', fontWeight: 'bold' }}> Master</span> },
@@ -160,13 +155,14 @@ const AddBrandDevice = () => {
path_solution: sol.path_solution || '', path_solution: sol.path_solution || '',
is_active: sol.is_active !== false, is_active: sol.is_active !== false,
})), })),
// Note: Sparepart data is collected but not sent to backend yet ...(ec.sparepart && ec.sparepart.length > 0 && {
// sparepart: (ec.sparepart || []).map((sp) => ({ sparepart: ec.sparepart.map((sp) => ({
// type: sp.type || 'required', sparepart_name: sp.sparepart_name || sp.name || sp.label || '',
// name: sp.name || '', brand_sparepart_description: sp.brand_sparepart_description || sp.description || sp.sparepart_description || '',
// quantity: sp.quantity || 1, is_active: sp.is_active !== false,
// is_active: sp.is_active !== false, path_foto: sp.path_foto || '',
// })), })),
}),
})); }));
const finalFormData = { const finalFormData = {
@@ -226,7 +222,7 @@ const AddBrandDevice = () => {
} }
if (record.sparepart && record.sparepart.length > 0) { if (record.sparepart && record.sparepart.length > 0) {
setSparepartForExistingRecord(record.sparepart, sparepartForm); setSparepartsForExistingRecord(record.sparepart, sparepartForm);
} }
}; };
@@ -258,17 +254,6 @@ const AddBrandDevice = () => {
} else { } else {
resetSolutionFields(); resetSolutionFields();
} }
if (record.sparepart && record.sparepart.length > 0) {
// Reset sparepart fields first
resetSparepartFields();
// Then load new spareparts
setTimeout(() => {
setSparepartForExistingRecord(record.sparepart, sparepartForm);
}, 0);
} else {
resetSparepartFields();
}
}; };
const handleAddErrorCode = async () => { const handleAddErrorCode = async () => {
@@ -297,9 +282,7 @@ const AddBrandDevice = () => {
return; return;
} }
// Get sparepart data (optional, no backend yet) const sparepartData = getSparepartData();
const spareparts = getSparepartData() || [];
const newErrorCode = { const newErrorCode = {
key: Date.now(), key: Date.now(),
error_code: formValues.error_code, error_code: formValues.error_code,
@@ -310,7 +293,7 @@ const AddBrandDevice = () => {
status: formValues.status !== false, status: formValues.status !== false,
errorCodeIcon: errorCodeIcon, errorCodeIcon: errorCodeIcon,
solution: solutions, solution: solutions,
sparepart: spareparts, ...(sparepartData && sparepartData.length > 0 && { sparepart: sparepartData }), // Only add sparepart if there are spareparts
}; };
if (editingErrorCodeKey) { if (editingErrorCodeKey) {
@@ -336,7 +319,6 @@ const AddBrandDevice = () => {
// Reset all forms // Reset all forms
resetErrorCodeForm(); resetErrorCodeForm();
resetSolutionFields(); resetSolutionFields();
resetSparepartFields();
} catch (error) { } catch (error) {
console.error('Error adding error code:', error); console.error('Error adding error code:', error);
NotifAlert({ NotifAlert({
@@ -357,6 +339,7 @@ const AddBrandDevice = () => {
setFileList([]); setFileList([]);
setErrorCodeIcon(null); setErrorCodeIcon(null);
resetSolutionFields(); resetSolutionFields();
resetSparepartFields();
setIsErrorCodeFormReadOnly(false); setIsErrorCodeFormReadOnly(false);
setEditingErrorCodeKey(null); setEditingErrorCodeKey(null);
}; };
@@ -542,7 +525,6 @@ const AddBrandDevice = () => {
layout="vertical" layout="vertical"
initialValues={{ initialValues={{
sparepart_status_0: true, sparepart_status_0: true,
sparepart_type_0: 'required',
}} }}
> >
<SparepartForm <SparepartForm
@@ -550,59 +532,111 @@ const AddBrandDevice = () => {
sparepartFields={sparepartFields} sparepartFields={sparepartFields}
onAddSparepartField={handleAddSparepartField} onAddSparepartField={handleAddSparepartField}
onRemoveSparepartField={handleRemoveSparepartField} onRemoveSparepartField={handleRemoveSparepartField}
onSparepartTypeChange={handleSparepartTypeChange} isReadOnly={isErrorCodeFormReadOnly}
onSparepartStatusChange={handleSparepartStatusChange}
onSparepartImageUpload={handleSparepartImageUpload}
onSparepartImageRemove={handleSparepartImageRemove}
sparepartImages={sparepartImages}
isReadOnly={false}
/> />
</Form> </Form>
</Card> </Card>
</Col> </Col>
</Row>
{/* Error Codes List Button */} {/* Error Codes Table Column */}
<Row justify="center"> <Col span={24} style={{ marginTop: 16 }}>
<Col> <Card size="small" title={`Error Codes (${errorCodes.length})`}>
<ConfigProvider <Table
theme={{ dataSource={errorCodes}
token: { colorBgContainer: '#23a55ade' }, columns={[
components: { {
Button: { title: 'Error Code',
defaultBg: '#23a55a', dataIndex: 'error_code',
defaultColor: '#FFFFFF', key: 'error_code',
defaultBorderColor: '#23a55a', width: '25%',
defaultHoverBg: '#209652',
defaultHoverColor: '#FFFFFF',
defaultHoverBorderColor: '#23a55a',
}, },
}, {
}} title: 'Sol',
> key: 'Sol',
<Button width: '10%',
type="primary" align: 'center',
size="large" render: (_, record) => {
onClick={() => setShowErrorCodeModal(true)} const solutionCount = record.solution
style={{ minWidth: '200px' }} ? record.solution.length
> : 0;
View All Error Codes ({errorCodes.length}) return (
</Button> <Tag
</ConfigProvider> color={solutionCount > 0 ? 'green' : 'red'}
>
{solutionCount} Sol
</Tag>
);
},
},
{
title: 'Status',
dataIndex: 'status',
key: 'status',
width: '20%',
align: 'center',
render: (_, { status }) => (
<Tag color={status ? 'green' : 'red'}>
{status ? 'Active' : 'Inactive'}
</Tag>
),
},
{
title: 'Action',
key: 'action',
align: 'center',
width: '15%',
render: (_, record) => (
<Space>
<Button
type="text"
style={{ borderColor: '#1890ff' }}
size="small"
icon={
<EyeOutlined
style={{ color: '#1890ff' }}
/>
}
onClick={() =>
handlePreviewErrorCode(record)
}
/>
<Button
type="text"
style={{ borderColor: '#faad14' }}
size="small"
icon={
<EditOutlined
style={{ color: '#faad14' }}
/>
}
onClick={() => handleEditErrorCode(record)}
/>
<Button
type="text"
danger
style={{ borderColor: 'red' }}
size="small"
icon={<DeleteOutlined />}
onClick={() =>
handleDeleteErrorCode(record.key)
}
/>
</Space>
),
},
]}
rowKey="key"
pagination={{
pageSize: 10,
showSizeChanger: false,
hideOnSinglePage: true,
}}
size="small"
scroll={{ y: 300 }}
/>
</Card>
</Col> </Col>
</Row> </Row>
{/* Error Codes List Modal */}
<ErrorCodeListModal
visible={showErrorCodeModal}
onClose={() => setShowErrorCodeModal(false)}
errorCodes={errorCodes}
loading={loading}
onPreview={handlePreviewErrorCode}
onEdit={handleEditErrorCode}
onDelete={handleDeleteErrorCode}
onAddNew={handleCreateNewErrorCode}
/>
</> </>
); );
} }
@@ -616,7 +650,7 @@ const AddBrandDevice = () => {
</Title> </Title>
<Steps current={currentStep} style={{ marginBottom: 24 }}> <Steps current={currentStep} style={{ marginBottom: 24 }}>
<Step title="Brand Device Details" /> <Step title="Brand Device Details" />
<Step title="Error Codes, Solutions & Spareparts" /> <Step title="Error Codes & Solutions" />
</Steps> </Steps>
<div style={{ marginTop: 24 }}>{renderStepContent()}</div> <div style={{ marginTop: 24 }}>{renderStepContent()}</div>
<Divider /> <Divider />

View File

@@ -12,6 +12,9 @@ import {
Spin, Spin,
Modal, Modal,
ConfigProvider, ConfigProvider,
Table,
Tag,
Space,
} from 'antd'; } from 'antd';
import { NotifAlert, NotifOk } from '../../../components/Global/ToastNotif'; import { NotifAlert, NotifOk } from '../../../components/Global/ToastNotif';
import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb'; import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb';
@@ -26,6 +29,7 @@ import FormActions from './component/FormActions';
import { useErrorCodeLogic } from './hooks/errorCode'; import { useErrorCodeLogic } from './hooks/errorCode';
import { useSolutionLogic } from './hooks/solution'; import { useSolutionLogic } from './hooks/solution';
import { useSparepartLogic } from './hooks/sparepart'; import { useSparepartLogic } from './hooks/sparepart';
import { EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
const { Title } = Typography; const { Title } = Typography;
const { Step } = Steps; const { Step } = Steps;
@@ -55,8 +59,6 @@ const EditBrandDevice = () => {
const [formData, setFormData] = useState(defaultData); const [formData, setFormData] = useState(defaultData);
const [errorCodes, setErrorCodes] = useState([]); const [errorCodes, setErrorCodes] = useState([]);
const [errorCodeIcon, setErrorCodeIcon] = useState(null); const [errorCodeIcon, setErrorCodeIcon] = useState(null);
const [showErrorCodeModal, setShowErrorCodeModal] = useState(false);
const [sparepartImages, setSparepartImages] = useState({});
const [solutionForm] = Form.useForm(); const [solutionForm] = Form.useForm();
const [sparepartForm] = Form.useForm(); const [sparepartForm] = Form.useForm();
@@ -82,31 +84,16 @@ const EditBrandDevice = () => {
sparepartFields, sparepartFields,
sparepartTypes, sparepartTypes,
sparepartStatuses, sparepartStatuses,
sparepartsToDelete,
handleAddSparepartField, handleAddSparepartField,
handleRemoveSparepartField, handleRemoveSparepartField,
handleSparepartTypeChange, handleSparepartTypeChange,
handleSparepartStatusChange, handleSparepartStatusChange,
resetSparepartFields, resetSparepartFields,
getSparepartData, getSparepartData,
setSparepartForExistingRecord, setSparepartsForExistingRecord,
} = useSparepartLogic(sparepartForm); } = useSparepartLogic(sparepartForm);
// Handlers for sparepart image upload
const handleSparepartImageUpload = (fieldKey, imageData) => {
setSparepartImages((prev) => ({
...prev,
[fieldKey]: imageData,
}));
};
const handleSparepartImageRemove = (fieldKey) => {
setSparepartImages((prev) => {
const newImages = { ...prev };
delete newImages[fieldKey];
return newImages;
});
};
useEffect(() => { useEffect(() => {
const fetchBrandData = async () => { const fetchBrandData = async () => {
const token = localStorage.getItem('token'); const token = localStorage.getItem('token');
@@ -169,6 +156,7 @@ const EditBrandDevice = () => {
path_icon: ec.path_icon || '', path_icon: ec.path_icon || '',
status: ec.is_active, status: ec.is_active,
solution: ec.solution || [], solution: ec.solution || [],
sparepart: ec.sparepart || [],
errorCodeIcon: ec.path_icon errorCodeIcon: ec.path_icon
? { ? {
name: 'icon', name: 'icon',
@@ -230,9 +218,8 @@ const EditBrandDevice = () => {
const handleFinish = async () => { const handleFinish = async () => {
setConfirmLoading(true); setConfirmLoading(true);
try { try {
// Get current solution and sparepart data from forms // Get current solution data from forms
const currentSolutionData = getSolutionData(); const currentSolutionData = getSolutionData();
const currentSparepartData = getSparepartData();
const finalFormData = { const finalFormData = {
brand_name: formData.brand_name, brand_name: formData.brand_name,
@@ -257,11 +244,11 @@ const EditBrandDevice = () => {
path_solution: sol.path_solution || '', path_solution: sol.path_solution || '',
is_active: sol.is_active !== false, is_active: sol.is_active !== false,
})), })),
sparepart: currentSparepartData.map((sp) => ({ sparepart: (ec.sparepart || []).map((sp) => ({
name: sp.name, sparepart_name: sp.sparepart_name || sp.name || sp.label || '',
description: sp.description || '', brand_sparepart_description: sp.brand_sparepart_description || sp.description || sp.brand_sparepart_description || '',
is_active: sp.is_active !== false, is_active: sp.is_active !== false,
sparepart_image: sparepartImages[sp.key || sp.id] || null, path_foto: sp.path_foto || '',
})), })),
}; };
} }
@@ -281,12 +268,14 @@ const EditBrandDevice = () => {
path_solution: sol.path_solution || '', path_solution: sol.path_solution || '',
is_active: sol.is_active !== false, is_active: sol.is_active !== false,
})), })),
sparepart: (ec.sparepart || []).map((sp) => ({ ...(ec.sparepart && ec.sparepart.length > 0 && {
name: sp.name, sparepart: ec.sparepart.map((sp) => ({
description: sp.description || '', sparepart_name: sp.sparepart_name || sp.name || sp.label || '',
is_active: sp.is_active !== false, brand_sparepart_description: sp.brand_sparepart_description || sp.description || sp.brand_sparepart_description || '',
sparepart_image: sp.sparepart_image || null, is_active: sp.is_active !== false,
})), path_foto: sp.path_foto || '',
})),
}),
}; };
}), }),
}; };
@@ -340,19 +329,9 @@ const EditBrandDevice = () => {
// Load spareparts to sparepart form // Load spareparts to sparepart form
if (record.sparepart && record.sparepart.length > 0) { if (record.sparepart && record.sparepart.length > 0) {
setSparepartForExistingRecord(record.sparepart, sparepartForm); setSparepartsForExistingRecord(record.sparepart, sparepartForm);
// Load sparepart images
const newSparepartImages = {};
record.sparepart.forEach((sparepart) => {
if (sparepart.sparepart_image) {
newSparepartImages[sparepart.id || sparepart.key] = sparepart.sparepart_image;
}
});
setSparepartImages(newSparepartImages);
} else { } else {
resetSparepartFields(); resetSparepartFields();
setSparepartImages({});
} }
}; };
@@ -375,16 +354,7 @@ const EditBrandDevice = () => {
// Load spareparts to sparepart form // Load spareparts to sparepart form
if (record.sparepart && record.sparepart.length > 0) { if (record.sparepart && record.sparepart.length > 0) {
setSparepartForExistingRecord(record.sparepart, sparepartForm); setSparepartsForExistingRecord(record.sparepart, sparepartForm);
// Load sparepart images
const newSparepartImages = {};
record.sparepart.forEach((sparepart) => {
if (sparepart.sparepart_image) {
newSparepartImages[sparepart.id || sparepart.key] = sparepart.sparepart_image;
}
});
setSparepartImages(newSparepartImages);
} }
const formElement = document.querySelector('.ant-form'); const formElement = document.querySelector('.ant-form');
@@ -401,9 +371,6 @@ const EditBrandDevice = () => {
// Get solution data from solution form // Get solution data from solution form
const solutionData = getSolutionData(); const solutionData = getSolutionData();
// Get sparepart data from sparepart form
const sparepartData = getSparepartData();
if (solutionData.length === 0) { if (solutionData.length === 0) {
NotifAlert({ NotifAlert({
icon: 'warning', icon: 'warning',
@@ -413,6 +380,9 @@ const EditBrandDevice = () => {
return; return;
} }
// Get sparepart data from sparepart form
const sparepartData = getSparepartData();
// Create complete error code object // Create complete error code object
const newErrorCode = { const newErrorCode = {
error_code: errorCodeValues.error_code, error_code: errorCodeValues.error_code,
@@ -422,7 +392,7 @@ const EditBrandDevice = () => {
path_icon: errorCodeIcon?.uploadPath || '', path_icon: errorCodeIcon?.uploadPath || '',
status: errorCodeValues.status === undefined ? true : errorCodeValues.status, status: errorCodeValues.status === undefined ? true : errorCodeValues.status,
solution: solutionData, solution: solutionData,
sparepart: sparepartData, ...(sparepartData && sparepartData.length > 0 && { sparepart: sparepartData }),
errorCodeIcon: errorCodeIcon, errorCodeIcon: errorCodeIcon,
key: editingErrorCodeKey || `temp-${Date.now()}`, key: editingErrorCodeKey || `temp-${Date.now()}`,
}; };
@@ -480,6 +450,7 @@ const EditBrandDevice = () => {
setFileList([]); setFileList([]);
setErrorCodeIcon(null); setErrorCodeIcon(null);
resetSolutionFields(); resetSolutionFields();
resetSparepartFields();
setIsErrorCodeFormReadOnly(false); setIsErrorCodeFormReadOnly(false);
setEditingErrorCodeKey(null); setEditingErrorCodeKey(null);
}; };
@@ -508,7 +479,6 @@ const EditBrandDevice = () => {
resetSolutionFields(); resetSolutionFields();
resetSparepartFields(); resetSparepartFields();
setErrorCodeIcon(null); setErrorCodeIcon(null);
setSparepartImages({});
setIsErrorCodeFormReadOnly(false); setIsErrorCodeFormReadOnly(false);
setEditingErrorCodeKey(null); setEditingErrorCodeKey(null);
}; };
@@ -586,7 +556,7 @@ const EditBrandDevice = () => {
: 'Error Code Form' : 'Error Code Form'
: editingErrorCodeKey : editingErrorCodeKey
? 'Edit Error Code' ? 'Edit Error Code'
: 'Tambah Error Code'} : 'Error Code'}
</Title> </Title>
} }
size="small" size="small"
@@ -656,7 +626,6 @@ const EditBrandDevice = () => {
layout="vertical" layout="vertical"
initialValues={{ initialValues={{
sparepart_status_0: true, sparepart_status_0: true,
sparepart_type_0: 'required',
}} }}
> >
<SparepartForm <SparepartForm
@@ -664,59 +633,109 @@ const EditBrandDevice = () => {
sparepartFields={sparepartFields} sparepartFields={sparepartFields}
onAddSparepartField={handleAddSparepartField} onAddSparepartField={handleAddSparepartField}
onRemoveSparepartField={handleRemoveSparepartField} onRemoveSparepartField={handleRemoveSparepartField}
onSparepartTypeChange={handleSparepartTypeChange}
onSparepartStatusChange={handleSparepartStatusChange}
onSparepartImageUpload={handleSparepartImageUpload}
onSparepartImageRemove={handleSparepartImageRemove}
sparepartImages={sparepartImages}
isReadOnly={isErrorCodeFormReadOnly} isReadOnly={isErrorCodeFormReadOnly}
/> />
</Form> </Form>
</Card> </Card>
</Col> </Col>
</Row> <Col span={24} style={{ marginTop: 16 }}>
<Card size="small" title={`Error Codes (${errorCodes.length})`}>
{/* Error Codes List Button */} <Table
<Row justify="center"> dataSource={errorCodes}
<Col> columns={[
<ConfigProvider {
theme={{ title: 'Error Code',
token: { colorBgContainer: '#23a55ade' }, dataIndex: 'error_code',
components: { key: 'error_code',
Button: { width: '25%',
defaultBg: '#23a55a',
defaultColor: '#FFFFFF',
defaultBorderColor: '#23a55a',
defaultHoverBg: '#209652',
defaultHoverColor: '#FFFFFF',
defaultHoverBorderColor: '#23a55a',
}, },
}, {
}} title: 'Sol',
> key: 'Sol',
<Button width: '10%',
type="primary" align: 'center',
size="large" render: (_, record) => {
onClick={() => setShowErrorCodeModal(true)} const solutionCount = record.solution
style={{ minWidth: '200px' }} ? record.solution.length
> : 0;
View All Error Codes ({errorCodes.length}) return (
</Button> <Tag
</ConfigProvider> color={solutionCount > 0 ? 'green' : 'red'}
>
{solutionCount} Sol
</Tag>
);
},
},
{
title: 'Status',
dataIndex: 'status',
key: 'status',
width: '20%',
align: 'center',
render: (_, { status }) => (
<Tag color={status ? 'green' : 'red'}>
{status ? 'Active' : 'Inactive'}
</Tag>
),
},
{
title: 'Action',
key: 'action',
align: 'center',
width: '15%',
render: (_, record) => (
<Space>
<Button
type="text"
style={{ borderColor: '#1890ff' }}
size="small"
icon={
<EyeOutlined
style={{ color: '#1890ff' }}
/>
}
onClick={() =>
handlePreviewErrorCode(record)
}
/>
<Button
type="text"
style={{ borderColor: '#faad14' }}
size="small"
icon={
<EditOutlined
style={{ color: '#faad14' }}
/>
}
onClick={() => handleEditErrorCode(record)}
/>
<Button
type="text"
danger
style={{ borderColor: 'red' }}
size="small"
icon={<DeleteOutlined />}
onClick={() =>
handleDeleteErrorCode(record.key)
}
/>
</Space>
),
},
]}
rowKey="key"
pagination={{
pageSize: 10,
showSizeChanger: false,
hideOnSinglePage: true,
}}
size="small"
scroll={{ y: 300 }}
/>
</Card>
</Col> </Col>
</Row> </Row>
{/* Error Codes List Modal */}
<ErrorCodeListModal
visible={showErrorCodeModal}
onClose={() => setShowErrorCodeModal(false)}
errorCodes={errorCodes}
loading={loading}
onPreview={handlePreviewErrorCode}
onEdit={handleEditErrorCode}
onDelete={handleDeleteErrorCode}
onAddNew={handleCreateNewErrorCode}
/>
</> </>
); );
} }
@@ -730,7 +749,7 @@ const EditBrandDevice = () => {
</Title> </Title>
<Steps current={currentStep} style={{ marginBottom: 24 }}> <Steps current={currentStep} style={{ marginBottom: 24 }}>
<Step title="Brand Device Details" /> <Step title="Brand Device Details" />
<Step title="Error Codes" /> <Step title="Error Codes & Solutions" />
</Steps> </Steps>
<div style={{ position: 'relative' }}> <div style={{ position: 'relative' }}>
{loading && ( {loading && (

View File

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

View File

@@ -33,14 +33,14 @@ const ErrorCodeListModal = ({
title: 'Error Name', title: 'Error Name',
dataIndex: 'error_code_name', dataIndex: 'error_code_name',
key: 'error_code_name', key: 'error_code_name',
width: '25%', width: '30%',
render: (text) => text || '-', render: (text) => text || '-',
}, },
{ {
title: 'Description', title: 'Description',
dataIndex: 'error_code_description', dataIndex: 'error_code_description',
key: 'error_code_description', key: 'error_code_description',
width: '30%', width: '25%',
render: (text) => text || '-', render: (text) => text || '-',
ellipsis: true, ellipsis: true,
}, },
@@ -54,18 +54,6 @@ const ErrorCodeListModal = ({
return <Tag color={solutionCount > 0 ? 'green' : 'red'}>{solutionCount} Sol</Tag>; return <Tag color={solutionCount > 0 ? 'green' : 'red'}>{solutionCount} Sol</Tag>;
}, },
}, },
{
title: 'Spareparts',
key: 'spareparts',
width: '10%',
align: 'center',
render: (_, record) => {
const sparepartCount = record.sparepart ? record.sparepart.length : 0;
return (
<Tag color={sparepartCount > 0 ? 'blue' : 'default'}>{sparepartCount} SP</Tag>
);
},
},
{ {
title: 'Status', title: 'Status',
dataIndex: 'status', dataIndex: 'status',

View File

@@ -1,13 +1,4 @@
import { import { Form, Input, Switch, Upload, Button, Typography, message, ConfigProvider } from 'antd';
Form,
Input,
Switch,
Upload,
Button,
Typography,
message,
ConfigProvider,
} from 'antd';
import { UploadOutlined } from '@ant-design/icons'; import { UploadOutlined } from '@ant-design/icons';
import { uploadFile } from '../../../../api/file-uploads'; import { uploadFile } from '../../../../api/file-uploads';
@@ -47,7 +38,8 @@ const ErrorCodeSimpleForm = ({
const folder = 'images'; const folder = 'images';
const uploadResponse = await uploadFile(file, folder); const uploadResponse = await uploadFile(file, folder);
const iconPath = uploadResponse.data?.path_icon || uploadResponse.data?.path_solution || ''; const iconPath =
uploadResponse.data?.path_icon || uploadResponse.data?.path_solution || '';
if (iconPath) { if (iconPath) {
onErrorCodeIconUpload({ onErrorCodeIconUpload({
@@ -82,9 +74,7 @@ const ErrorCodeSimpleForm = ({
style={{ backgroundColor: statusValue ? '#23A55A' : '#bfbfbf' }} style={{ backgroundColor: statusValue ? '#23A55A' : '#bfbfbf' }}
/> />
</Form.Item> </Form.Item>
<Text style={{ marginLeft: 8 }}> <Text style={{ marginLeft: 8 }}>{statusValue ? 'Active' : 'Inactive'}</Text>
{statusValue ? 'Active' : 'Inactive'}
</Text>
</div> </div>
</Form.Item> </Form.Item>
@@ -94,10 +84,7 @@ const ErrorCodeSimpleForm = ({
name="error_code" name="error_code"
rules={[{ required: true, message: 'Error code wajib diisi!' }]} rules={[{ required: true, message: 'Error code wajib diisi!' }]}
> >
<Input <Input placeholder="Enter error code" disabled={isErrorCodeFormReadOnly} />
placeholder="Enter error code"
disabled={isErrorCodeFormReadOnly}
/>
</Form.Item> </Form.Item>
{/* Error Name */} {/* Error Name */}
@@ -106,17 +93,11 @@ const ErrorCodeSimpleForm = ({
name="error_code_name" name="error_code_name"
rules={[{ required: true, message: 'Error name wajib diisi!' }]} rules={[{ required: true, message: 'Error name wajib diisi!' }]}
> >
<Input <Input placeholder="Enter error name" disabled={isErrorCodeFormReadOnly} />
placeholder="Enter error name"
disabled={isErrorCodeFormReadOnly}
/>
</Form.Item> </Form.Item>
{/* Error Description */} {/* Error Description */}
<Form.Item <Form.Item label="Description" name="error_code_description">
label="Description"
name="error_code_description"
>
<Input.TextArea <Input.TextArea
placeholder="Enter error description" placeholder="Enter error description"
rows={3} rows={3}
@@ -127,14 +108,16 @@ const ErrorCodeSimpleForm = ({
{/* Color and Icon in same row */} {/* Color and Icon in same row */}
<Form.Item label="Color & Icon"> <Form.Item label="Color & Icon">
<Input.Group compact> <Input.Group compact>
<Form.Item <Form.Item name="error_code_color" noStyle>
name="error_code_color"
noStyle
>
<input <input
type="color" type="color"
disabled={isErrorCodeFormReadOnly} disabled={isErrorCodeFormReadOnly}
style={{ width: '30%', height: '40px', border: '1px solid #d9d9d9', borderRadius: 4 }} style={{
width: '30%',
height: '40px',
border: '1px solid #d9d9d9',
borderRadius: 4,
}}
defaultValue="#000000" defaultValue="#000000"
/> />
</Form.Item> </Form.Item>
@@ -152,7 +135,13 @@ const ErrorCodeSimpleForm = ({
</Button> </Button>
</Upload> </Upload>
) : ( ) : (
<div style={{ padding: '8px 12px', border: '1px solid #d9d9d9', borderRadius: 4 }}> <div
style={{
padding: '8px 12px',
border: '1px solid #d9d9d9',
borderRadius: 4,
}}
>
<Text type="secondary">No upload allowed</Text> <Text type="secondary">No upload allowed</Text>
</div> </div>
)} )}
@@ -181,12 +170,7 @@ const ErrorCodeSimpleForm = ({
</Text> </Text>
</div> </div>
{!isErrorCodeFormReadOnly && ( {!isErrorCodeFormReadOnly && (
<Button <Button type="text" danger size="small" onClick={handleIconRemove}>
type="text"
danger
size="small"
onClick={handleIconRemove}
>
Remove Remove
</Button> </Button>
)} )}
@@ -221,7 +205,7 @@ const ErrorCodeSimpleForm = ({
}} }}
style={{ width: '100%' }} style={{ width: '100%' }}
> >
+ Add Error Code Simpan Error Code
</Button> </Button>
</ConfigProvider> </ConfigProvider>
</Form.Item> </Form.Item>

View File

@@ -262,7 +262,7 @@ const ListBrandDevice = memo(function ListBrandDevice(props) {
<TableList <TableList
mobile mobile
cardColor={'#42AAFF'} cardColor={'#42AAFF'}
header={'tag_name'} header={'brand_name'}
showPreviewModal={showPreviewModal} showPreviewModal={showPreviewModal}
showEditModal={showEditModal} showEditModal={showEditModal}
showDeleteDialog={showDeleteDialog} showDeleteDialog={showDeleteDialog}

View File

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

View File

@@ -1,243 +0,0 @@
import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Switch, Radio, Upload, Typography, Space } from 'antd';
import { DeleteOutlined, UploadOutlined, EyeOutlined } from '@ant-design/icons';
import { uploadFile, getFolderFromFileType } from '../../../../api/file-uploads';
import { NotifAlert } from '../../../../components/Global/ToastNotif';
const { Text } = Typography;
const { TextArea } = Input;
const SolutionFieldNew = ({
fieldKey,
fieldName,
index,
solutionType,
solutionStatus,
isReadOnly = false,
canRemove = true,
onTypeChange,
onStatusChange,
onRemove,
onFileUpload,
onFileView,
fileList = []
}) => {
const [currentStatus, setCurrentStatus] = useState(solutionStatus ?? true);
// Watch form values
const getFieldValue = () => {
try {
const form = document.querySelector(`[data-field="${fieldName}"]`)?.form;
if (form) {
const formData = new FormData(form);
return formData.get(`${fieldName}.status`) === 'on';
}
return currentStatus;
} catch {
return currentStatus;
}
};
useEffect(() => {
setCurrentStatus(solutionStatus ?? true);
}, [solutionStatus]);
const handleFileUpload = async (file) => {
try {
const isAllowedType = [
'application/pdf',
'image/jpeg',
'image/png',
'image/gif',
].includes(file.type);
if (!isAllowedType) {
NotifAlert({
icon: 'error',
title: 'Error',
message: `${file.name} bukan file PDF atau gambar yang diizinkan.`,
});
return;
}
const fileExtension = file.name.split('.').pop().toLowerCase();
const isImage = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(fileExtension);
const fileType = isImage ? 'image' : 'pdf';
const folder = getFolderFromFileType(fileType);
const uploadResponse = await uploadFile(file, folder);
const actualPath = uploadResponse.data?.path_solution || '';
if (actualPath) {
// Store the file info with the solution field
file.uploadPath = actualPath;
file.solutionId = fieldKey;
file.type_solution = fileType;
onFileUpload(file);
NotifAlert({
icon: 'success',
title: 'Berhasil',
message: `${file.name} berhasil diupload!`,
});
} else {
NotifAlert({
icon: 'error',
title: 'Gagal',
message: `Gagal mengupload ${file.name}`,
});
}
} catch (error) {
console.error('Error uploading file:', error);
NotifAlert({
icon: 'error',
title: 'Error',
message: `Gagal mengupload ${file.name}. Silakan coba lagi.`,
});
}
};
const renderSolutionContent = () => {
if (solutionType === 'text') {
return (
<Form.Item
name={[fieldName, 'text']}
rules={[{ required: true, message: 'Text solution wajib diisi!' }]}
>
<TextArea
placeholder="Enter solution text"
rows={3}
disabled={isReadOnly}
/>
</Form.Item>
);
}
if (solutionType === 'file') {
const currentFiles = fileList.filter(file => file.solutionId === fieldKey);
return (
<div>
<Form.Item
name={[fieldName, 'file']}
rules={[{ required: true, message: 'File solution wajib diupload!' }]}
>
<Upload
beforeUpload={handleFileUpload}
showUploadList={false}
accept=".pdf,.jpg,.jpeg,.png,.gif"
disabled={isReadOnly}
>
<Button
icon={<UploadOutlined />}
disabled={isReadOnly}
style={{ width: '100%' }}
>
Upload File (PDF/Image)
</Button>
</Upload>
</Form.Item>
{currentFiles.length > 0 && (
<div style={{ marginTop: 8 }}>
{currentFiles.map((file, index) => (
<div key={index} style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
padding: '4px 8px',
border: '1px solid #d9d9d9',
borderRadius: 4,
marginBottom: 4
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<Text style={{ fontSize: 12 }}>{file.name}</Text>
<Text type="secondary" style={{ fontSize: 10 }}>
({(file.size / 1024).toFixed(1)} KB)
</Text>
</div>
<Button
type="text"
size="small"
icon={<EyeOutlined />}
onClick={() => onFileView(file.uploadPath, file.type_solution)}
/>
</div>
))}
</div>
)}
</div>
);
}
return null;
};
return (
<div style={{
border: '1px solid #d9d9d9',
borderRadius: 8,
padding: 16,
marginBottom: 16,
backgroundColor: isReadOnly ? '#f5f5f5' : 'white'
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
<Text strong>Solution #{index + 1}</Text>
<Space>
<Form.Item
name={[fieldName, 'name']}
rules={[{ required: true, message: 'Solution name wajib diisi!' }]}
style={{ margin: 0, width: 200 }}
>
<Input
placeholder="Solution name"
disabled={isReadOnly}
/>
</Form.Item>
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<Form.Item name={[fieldName, 'status']} valuePropName="checked" noStyle>
<Switch
disabled={isReadOnly}
onChange={(checked) => {
onStatusChange(fieldKey, checked);
setCurrentStatus(checked);
}}
style={{
backgroundColor: currentStatus ? '#23A55A' : '#bfbfbf'
}}
/>
</Form.Item>
<Text style={{ fontSize: 12, color: '#666' }}>
{currentStatus ? 'Active' : 'Inactive'}
</Text>
</div>
{canRemove && !isReadOnly && (
<Button
type="text"
danger
icon={<DeleteOutlined />}
onClick={onRemove}
/>
)}
</Space>
</div>
<Form.Item
name={[fieldName, 'type']}
rules={[{ required: true, message: 'Solution type wajib diisi!' }]}
>
<Radio.Group
onChange={(e) => onTypeChange(fieldKey, e.target.value)}
disabled={isReadOnly}
>
<Radio value="text">Text Solution</Radio>
<Radio value="file">File Solution</Radio>
</Radio.Group>
</Form.Item>
{renderSolutionContent()}
</div>
);
};
export default SolutionFieldNew;

View File

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

View File

@@ -0,0 +1,152 @@
import React, { useState, useEffect } from 'react';
import { Form, Select, Button, Switch, Typography, Space, Input, message } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import { getAllSparepart } from '../../../../api/sparepart';
const { Text } = Typography;
const SparepartField = ({
fieldKey,
fieldName,
index,
sparepartType,
sparepartStatus,
isReadOnly = false,
canRemove = true,
onRemove,
spareparts = [],
onSparepartChange
}) => {
const [currentStatus, setCurrentStatus] = useState(sparepartStatus ?? true);
const [sparepartList, setSparepartList] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
setCurrentStatus(sparepartStatus ?? true);
loadSpareparts();
}, [sparepartStatus]);
const loadSpareparts = async () => {
setLoading(true);
try {
// Get all spareparts from the API
const params = new URLSearchParams();
params.set('limit', '100'); // Get all spareparts
const response = await getAllSparepart(params);
// Response structure should have { data: [...], statusCode: 200 }
if (response && (response.statusCode === 200 || response.data)) {
// If response has data array directly
const sparepartData = response.data?.data || response.data || [];
setSparepartList(sparepartData);
if (onSparepartChange) {
onSparepartChange(sparepartData);
}
} else {
// For demo purposes, use mock data if API fails
setSparepartList([
{ brand_sparepart_id: 1, sparepart_name: 'Compressor Oil Filter', brand_sparepart_description: 'Oil filter for compressor' },
{ brand_sparepart_id: 2, sparepart_name: 'Air Intake Filter', brand_sparepart_description: 'Air intake filter' },
{ brand_sparepart_id: 3, sparepart_name: 'Cooling Fan Motor', brand_sparepart_description: 'Motor for cooling fan' },
]);
if (onSparepartChange) {
onSparepartChange([
{ brand_sparepart_id: 1, sparepart_name: 'Compressor Oil Filter', brand_sparepart_description: 'Oil filter for compressor' },
{ brand_sparepart_id: 2, sparepart_name: 'Air Intake Filter', brand_sparepart_description: 'Air intake filter' },
{ brand_sparepart_id: 3, sparepart_name: 'Cooling Fan Motor', brand_sparepart_description: 'Motor for cooling fan' },
]);
}
}
} catch (error) {
console.error('Error loading spareparts:', error);
// Default mock data
const mockSpareparts = [
{ brand_sparepart_id: 1, sparepart_name: 'Compressor Oil Filter', brand_sparepart_description: 'Oil filter for compressor' },
{ brand_sparepart_id: 2, sparepart_name: 'Air Intake Filter', brand_sparepart_description: 'Air intake filter' },
{ brand_sparepart_id: 3, sparepart_name: 'Cooling Fan Motor', brand_sparepart_description: 'Motor for cooling fan' },
];
setSparepartList(mockSpareparts);
if (onSparepartChange) {
onSparepartChange(mockSpareparts);
}
} finally {
setLoading(false);
}
};
const sparepartOptions = sparepartList.map(sparepart => ({
label: sparepart.sparepart_name || sparepart.sparepart_name || `Sparepart ${sparepart.sparepart_id || sparepart.brand_sparepart_id}`,
value: sparepart.sparepart_id || sparepart.brand_sparepart_id,
description: sparepart.sparepart_description
}));
return (
<div style={{
border: '1px solid #d9d9d9',
borderRadius: 8,
padding: 16,
marginBottom: 16,
backgroundColor: isReadOnly ? '#f5f5f5' : 'white'
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
<Text strong>Sparepart #{index + 1}</Text>
<Space>
<Form.Item
name={[fieldName, 'sparepart_id']}
rules={[{ required: false, message: 'Sparepart wajib dipilih!' }]} /* Making it optional since sparepart is optional */
style={{ margin: 0, width: 200 }}
>
<Select
placeholder="Pilih sparepart"
loading={loading}
disabled={isReadOnly}
options={sparepartOptions}
showSearch
optionFilterProp="label"
/>
</Form.Item>
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<Form.Item name={[fieldName, 'status']} valuePropName="checked" noStyle>
<Switch
disabled={isReadOnly}
onChange={(checked) => {
setCurrentStatus(checked);
}}
style={{
backgroundColor: currentStatus ? '#23A55A' : '#bfbfbf'
}}
/>
</Form.Item>
<Text style={{ fontSize: 12, color: '#666' }}>
{currentStatus ? 'Active' : 'Inactive'}
</Text>
</div>
{canRemove && !isReadOnly && (
<Button
type="text"
danger
icon={<DeleteOutlined />}
onClick={onRemove}
/>
)}
</Space>
</div>
{/* Sparepart Description */}
<Form.Item
name={[fieldName, 'description']}
label="Deskripsi"
>
<Input.TextArea
placeholder="Deskripsi sparepart"
rows={2}
disabled={isReadOnly}
/>
</Form.Item>
</div>
);
};
export default SparepartField;

View File

@@ -1,18 +1,7 @@
import React, { useState, useEffect } from 'react'; import React, { useState } from 'react';
import { import { Form, Card, Typography, Divider, Button } from 'antd';
Form, import { PlusOutlined } from '@ant-design/icons';
Input, import SparepartField from './SparepartField';
Button,
Divider,
Typography,
Switch,
Space,
Card,
Upload,
message,
} from 'antd';
import { PlusOutlined, DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import { uploadFile } from '../../../../api/file-uploads';
const { Text } = Typography; const { Text } = Typography;
@@ -21,234 +10,63 @@ const SparepartForm = ({
sparepartFields, sparepartFields,
onAddSparepartField, onAddSparepartField,
onRemoveSparepartField, onRemoveSparepartField,
onSparepartTypeChange,
onSparepartStatusChange,
onSparepartImageUpload,
onSparepartImageRemove,
sparepartImages = {},
isReadOnly = false, isReadOnly = false,
spareparts = [],
onSparepartChange
}) => { }) => {
const [fieldStatuses, setFieldStatuses] = useState({}); const [sparepartList, setSparepartList] = useState([]);
// Watch form values for each field const handleSparepartChange = (list) => {
const getFieldValue = (fieldName) => { setSparepartList(list);
try { if (onSparepartChange) {
const values = sparepartForm?.getFieldsValue(); onSparepartChange(list);
return values?.sparepart_items?.[fieldName]?.status ?? true;
} catch {
return true;
} }
}; };
useEffect(() => {
// Update field statuses when form changes
const newStatuses = {};
sparepartFields.forEach((field) => {
newStatuses[field.key] = getFieldValue(field.key);
});
setFieldStatuses(newStatuses);
}, [sparepartFields, sparepartForm]);
const handleImageUpload = async (fieldKey, file) => {
// Check if file is an image
const isImage = file.type.startsWith('image/');
if (!isImage) {
message.error('You can only upload image files!');
return Upload.LIST_IGNORE;
}
// Check file size (max 2MB)
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('Image must be smaller than 2MB!');
return Upload.LIST_IGNORE;
}
try {
const fileExtension = file.name.split('.').pop().toLowerCase();
const isImageFile = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(
fileExtension
);
const fileType = isImageFile ? 'image' : 'pdf';
const folder = 'images';
const uploadResponse = await uploadFile(file, folder);
const imagePath =
uploadResponse.data?.path_icon || uploadResponse.data?.path_solution || '';
if (imagePath) {
onSparepartImageUpload &&
onSparepartImageUpload(fieldKey, {
name: file.name,
uploadPath: imagePath,
fileExtension,
isImage: isImageFile,
size: file.size,
});
message.success(`${file.name} uploaded successfully!`);
} else {
message.error(`Failed to upload ${file.name}`);
}
} catch (error) {
console.error('Error uploading image:', error);
message.error(`Failed to upload ${file.name}`);
}
};
const handleImageRemove = (fieldKey) => {
onSparepartImageRemove && onSparepartImageRemove(fieldKey);
};
return ( return (
<div> <div>
<Text strong style={{ marginBottom: 16, display: 'block' }}>
{isReadOnly ? 'Sparepart Details' : 'Tambah Sparepart'}
</Text>
<Form <Form
form={sparepartForm} form={sparepartForm}
layout="vertical" layout="vertical"
initialValues={{ initialValues={{
sparepart_status_0: true, sparepart_status_0: true,
sparepart_type_0: 'required',
}} }}
> >
{/* Dynamic Sparepart Fields */}
<Divider orientation="left">Sparepart Items</Divider> <Divider orientation="left">Sparepart Items</Divider>
{sparepartFields.map((field, index) => ( {sparepartFields.map((field, index) => (
<Card <SparepartField
key={field.key} key={field.key}
size="small" fieldKey={field.key}
style={{ marginBottom: 16 }} fieldName={field.name}
title={ index={index}
<div sparepartStatus={field.status}
style={{ onRemove={() => onRemoveSparepartField(field.key)}
display: 'flex', isReadOnly={isReadOnly}
justifyContent: 'space-between', canRemove={sparepartFields.length > 1}
alignItems: 'center', spareparts={sparepartList}
}} onSparepartChange={handleSparepartChange}
> />
<Text strong>Sparepart {index + 1}</Text>
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
{!isReadOnly && sparepartFields.length > 1 && (
<div style={{ textAlign: 'right' }}>
<Button
type="text"
danger
icon={<DeleteOutlined />}
onClick={() => onRemoveSparepartField(field.key)}
/>
</div>
)}
</div>
</div>
}
>
<Form layout="vertical" style={{ border: 'none' }}>
{/* Sparepart Name */}
<Form.Item
name={[field.name, 'name']}
rules={[{ required: true, message: 'Sparepart name wajib diisi!' }]}
>
<Input placeholder="Enter sparepart name" disabled={isReadOnly} />
</Form.Item>
{/* Description */}
<Form.Item name={[field.name, 'description']}>
<Input.TextArea
placeholder="Enter sparepart description (optional)"
rows={2}
disabled={isReadOnly}
/>
</Form.Item>
{/* Image Upload */}
<Form.Item label="Sparepart Image">
{!isReadOnly ? (
<Upload
beforeUpload={(file) => handleImageUpload(field.key, file)}
showUploadList={false}
accept="image/*"
style={{ width: '100%' }}
>
<Button icon={<UploadOutlined />} style={{ width: '100%' }}>
Upload Sparepart Image
</Button>
</Upload>
) : (
<div
style={{
padding: '8px 12px',
border: '1px solid #d9d9d9',
borderRadius: 4,
}}
>
<Text type="secondary">No upload allowed</Text>
</div>
)}
{sparepartImages[field.key] && (
<div style={{ marginTop: 8 }}>
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 8,
}}
>
<img
src={sparepartImages[field.key].uploadPath}
alt="Sparepart Image"
style={{
width: 50,
height: 50,
objectFit: 'cover',
border: '1px solid #d9d9d9',
borderRadius: 4,
}}
/>
<div>
<Text style={{ fontSize: 12 }}>
{sparepartImages[field.key].name}
</Text>
<br />
<Text type="secondary" style={{ fontSize: 10 }}>
Size:{' '}
{(
sparepartImages[field.key].size / 1024
).toFixed(1)}{' '}
KB
</Text>
</div>
{!isReadOnly && (
<Button
type="text"
danger
size="small"
onClick={() => handleImageRemove(field.key)}
>
Remove
</Button>
)}
</div>
</div>
)}
</Form.Item>
</Form>
</Card>
))} ))}
{!isReadOnly && ( {!isReadOnly && (
<Form.Item> <>
<Button <Form.Item>
type="dashed" <Button
onClick={() => onAddSparepartField()} type="dashed"
icon={<PlusOutlined />} onClick={onAddSparepartField}
style={{ width: '100%' }} icon={<PlusOutlined />}
> style={{ width: '100%' }}
+ Add Sparepart >
</Button> + Add Sparepart
</Form.Item> </Button>
</Form.Item>
<div style={{ marginTop: 16 }}>
<Text type="secondary">
* Sparepart is optional and can be added for each error code if needed.
</Text>
</div>
</>
)} )}
</Form> </Form>
</div> </div>

View File

@@ -1,115 +1,141 @@
import { useState } from 'react'; import { useState, useCallback } from 'react';
export const useSparepartLogic = (sparepartForm) => { export const useSparepartLogic = (sparepartForm) => {
const [sparepartFields, setSparepartFields] = useState([ const [sparepartFields, setSparepartFields] = useState([]);
{ name: ['sparepart_items', 0], key: 0 } const [sparepartTypes, setSparepartTypes] = useState({});
]); const [sparepartStatuses, setSparepartStatuses] = useState({});
const [sparepartTypes, setSparepartTypes] = useState({ 0: 'required' }); const [sparepartsToDelete, setSparepartsToDelete] = useState(new Set());
const [sparepartStatuses, setSparepartStatuses] = useState({ 0: true });
const handleAddSparepartField = () => {
const newKey = Date.now(); // Use timestamp for unique key
const newField = { name: ['sparepart_items', newKey], key: newKey };
const handleAddSparepartField = useCallback(() => {
const newKey = Date.now();
const newField = {
key: newKey,
name: sparepartFields.length,
isCreated: true,
};
setSparepartFields(prev => [...prev, newField]); setSparepartFields(prev => [...prev, newField]);
setSparepartTypes(prev => ({ ...prev, [newKey]: 'required' })); setSparepartTypes(prev => ({
setSparepartStatuses(prev => ({ ...prev, [newKey]: true })); ...prev,
[newKey]: 'required'
}));
setSparepartStatuses(prev => ({
...prev,
[newKey]: true
}));
}, [sparepartFields.length]);
// Set default values for the new field const handleRemoveSparepartField = useCallback((key) => {
setTimeout(() => { setSparepartFields(prev => prev.filter(field => field.key !== key));
sparepartForm.setFieldValue(['sparepart_items', newKey, 'type'], 'required'); setSparepartTypes(prev => {
sparepartForm.setFieldValue(['sparepart_items', newKey, 'quantity'], 1); const newTypes = { ...prev };
}, 0); delete newTypes[key];
}; return newTypes;
});
setSparepartStatuses(prev => {
const newStatuses = { ...prev };
delete newStatuses[key];
return newStatuses;
});
const handleRemoveSparepartField = (key) => { // Add to delete list if it's not a new field
if (sparepartFields.length <= 1) { setSparepartsToDelete(prev => new Set([...prev, key]));
return; // Keep at least one sparepart field }, []);
const handleSparepartTypeChange = useCallback((key, type) => {
setSparepartTypes(prev => ({
...prev,
[key]: type
}));
}, []);
const handleSparepartStatusChange = useCallback((key, status) => {
setSparepartStatuses(prev => ({
...prev,
[key]: status
}));
}, []);
const resetSparepartFields = useCallback(() => {
setSparepartFields([]);
setSparepartTypes({});
setSparepartStatuses({});
setSparepartsToDelete(new Set());
}, []);
const getSparepartData = useCallback(() => {
if (!sparepartForm) return [];
const values = sparepartForm.getFieldsValue();
const data = [];
sparepartFields.forEach((field, index) => {
const fieldData = {
sparepart_id: values[`sparepart_id_${field.name}`],
sparepart_name: values[`sparepart_name_${field.name}`],
sparepart_description: values[`sparepart_description_${field.name}`],
status: values[`sparepart_status_${field.name}`],
type: sparepartTypes[field.key] || 'required',
};
// Only add if required fields are filled
if (fieldData.sparepart_id) {
data.push(fieldData);
}
});
return data;
}, [sparepartForm, sparepartFields, sparepartTypes]);
const setSparepartsForExistingRecord = useCallback((sparepartData, form) => {
resetSparepartFields();
if (!sparepartData || !Array.isArray(sparepartData)) {
return;
} }
setSparepartFields(prev => prev.filter(field => field.key !== key)); const newFields = sparepartData.map((sp, index) => ({
key: sp.brand_sparepart_id || sp.sparepart_id || `existing-${index}`,
// Clean up type and status name: index,
const newTypes = { ...sparepartTypes }; isCreated: false,
const newStatuses = { ...sparepartStatuses };
delete newTypes[key];
delete newStatuses[key];
setSparepartTypes(newTypes);
setSparepartStatuses(newStatuses);
};
const handleSparepartTypeChange = (key, value) => {
setSparepartTypes(prev => ({ ...prev, [key]: value }));
};
const handleSparepartStatusChange = (key, value) => {
setSparepartStatuses(prev => ({ ...prev, [key]: value }));
};
const resetSparepartFields = () => {
setSparepartFields([{ name: ['sparepart_items', 0], key: 0 }]);
setSparepartTypes({ 0: 'required' });
setSparepartStatuses({ 0: true });
// Reset form values
sparepartForm.resetFields();
sparepartForm.setFieldsValue({
sparepart_status_0: true,
sparepart_type_0: 'required',
});
};
const getSparepartData = () => {
const values = sparepartForm.getFieldsValue();
return sparepartFields.map(field => {
const key = field.key;
const sparepartPath = field.name.join(',');
const sparepart = values[sparepartPath];
return sparepart && sparepart.name && sparepart.name.trim() !== '' ? {
name: sparepart.name || '',
description: sparepart.description || '',
is_active: sparepart.status !== false,
} : null;
}).filter(Boolean);
};
const setSparepartForExistingRecord = (spareparts, form) => {
if (!spareparts || spareparts.length === 0) return;
const newFields = spareparts.map((sparepart, index) => ({
name: ['sparepart_items', sparepart.id || index],
key: sparepart.id || index
})); }));
setSparepartFields(newFields); setSparepartFields(newFields);
// Set sparepart values // Set form values for existing spareparts
const formValues = {}; setTimeout(() => {
Object.keys(spareparts).forEach(index => { const formValues = {};
const key = spareparts[index].id || index; sparepartData.forEach((sp, index) => {
const sparepart = spareparts[index]; const sparepartId = sp.brand_sparepart_id || sp.sparepart_id || sp.sparepart_name;
formValues[`sparepart_items,${key}`] = { formValues[`sparepart_id_${index}`] = sparepartId;
name: sparepart.name || '', formValues[`sparepart_status_${index}`] = sp.is_active ?? sp.status ?? true;
description: sparepart.description || '', formValues[`sparepart_description_${index}`] = sp.brand_sparepart_description || sp.description || sp.sparepart_name;
status: sparepart.is_active !== false,
};
});
form.setFieldsValue(formValues); setSparepartTypes(prev => ({
}; ...prev,
[sp.brand_sparepart_id || sp.sparepart_id || `existing-${index}`]: sp.type || sp.sparepart_type || 'required'
}));
setSparepartStatuses(prev => ({
...prev,
[sp.brand_sparepart_id || sp.sparepart_id || `existing-${index}`]: sp.is_active ?? sp.status ?? true
}));
});
form.setFieldsValue(formValues);
}, 0);
}, [resetSparepartFields]);
return { return {
sparepartFields, sparepartFields,
sparepartTypes, sparepartTypes,
sparepartStatuses, sparepartStatuses,
sparepartsToDelete,
handleAddSparepartField, handleAddSparepartField,
handleRemoveSparepartField, handleRemoveSparepartField,
handleSparepartTypeChange, handleSparepartTypeChange,
handleSparepartStatusChange, handleSparepartStatusChange,
resetSparepartFields, resetSparepartFields,
getSparepartData, getSparepartData,
setSparepartForExistingRecord, setSparepartsForExistingRecord,
}; };
}; };

View File

@@ -237,7 +237,7 @@ const ListPlantSubSection = memo(function ListPlantSubSection(props) {
<TableList <TableList
mobile mobile
cardColor={'#42AAFF'} cardColor={'#42AAFF'}
header={'sub_section_name'} header={'plant_sub_section_name'}
showPreviewModal={showPreviewModal} showPreviewModal={showPreviewModal}
showEditModal={showEditModal} showEditModal={showEditModal}
showDeleteDialog={showDeleteDialog} showDeleteDialog={showDeleteDialog}

View File

@@ -0,0 +1,75 @@
import React, { memo, useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb';
import { Typography } from 'antd';
import ListSparepart from './component/ListSparepart';
import DetailSparepart from './component/DetailSparepart';
const { Text } = Typography;
const IndexSparepart = memo(function IndexSparepart() {
const navigate = useNavigate();
const { setBreadcrumbItems } = useBreadcrumb();
const [actionMode, setActionMode] = useState('list');
const [selectedData, setSelectedData] = useState(null);
const [readOnly, setReadOnly] = useState(false);
const [showModal, setShowmodal] = useState(false);
const setMode = (param) => {
setShowmodal(true);
switch (param) {
case 'add':
setReadOnly(false);
break;
case 'edit':
setReadOnly(false);
break;
case 'preview':
setReadOnly(true);
break;
default:
setShowmodal(false);
break;
}
setActionMode(param);
};
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
setBreadcrumbItems([
{ title: <Text strong style={{ fontSize: '14px' }}> Master</Text> },
{ title: <Text strong style={{ fontSize: '14px' }}>Sparepart</Text> }
]);
} else {
navigate('/signin');
}
}, []);
return (
<React.Fragment>
<ListSparepart
actionMode={actionMode}
setActionMode={setMode}
selectedData={selectedData}
setSelectedData={setSelectedData}
readOnly={readOnly}
/>
<DetailSparepart
setActionMode={setMode}
selectedData={selectedData}
setSelectedData={setSelectedData}
readOnly={readOnly}
showModal={showModal}
permitDefault={false}
actionMode={actionMode}
/>
</React.Fragment>
);
});
export default IndexSparepart;

View File

@@ -0,0 +1,289 @@
import React, { useState, useEffect } from 'react';
import { Modal, Input, Divider, Typography, Switch, Button, ConfigProvider, message } from 'antd';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
import { createSparepart, updateSparepart } from '../../../../api/sparepart';
import { validateRun } from '../../../../Utils/validate';
const { Text } = Typography;
const { TextArea } = Input;
const DetailSparepart = (props) => {
const [confirmLoading, setConfirmLoading] = useState(false);
const defaultData = {
sparepart_id: '',
sparepart_name: '',
sparepart_description: '',
sparepart_model: '',
sparepart_item_type: '',
sparepart_unit: '',
sparepart_merk: '',
sparepart_stok: '',
};
const [formData, setFormData] = useState(defaultData);
const handleCancel = () => {
props.setSelectedData(null);
props.setActionMode('list');
};
const handleSave = async () => {
setConfirmLoading(true);
// Daftar aturan validasi
const validationRules = [
{ field: 'sparepart_name', label: 'Sparepart Name', required: true },
{ field: 'sparepart_model', label: 'Sparepart Model', required: true },
{ field: 'sparepart_unit', label: 'Sparepart Unit', required: true },
{ field: 'sparepart_merk', label: 'Sparepart Merk', required: true },
{ field: 'sparepart_stok', label: 'Sparepart Stok', required: true },
];
if (
validateRun(formData, validationRules, (errorMessages) => {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: errorMessages,
});
setConfirmLoading(false);
})
)
return;
try {
const payload = {
sparepart_name: formData.sparepart_name,
sparepart_description: formData.sparepart_description,
sparepart_model: formData.sparepart_model,
sparepart_item_type: formData.sparepart_item_type,
sparepart_unit: formData.sparepart_unit,
sparepart_merk: formData.sparepart_merk,
sparepart_stok: formData.sparepart_stok,
};
const response = formData.sparepart_id
? await updateSparepart(formData.sparepart_id, payload)
: await createSparepart(payload);
// Check if response is successful
if (response && (response.statusCode === 200 || response.statusCode === 201)) {
const sparepartName = response.data?.sparepart_name || formData.sparepart_name;
NotifOk({
icon: 'success',
title: 'Berhasil',
message: `Data Sparepart "${sparepartName}" berhasil ${
formData.sparepart_id ? 'diubah' : 'ditambahkan'
}.`,
});
props.setActionMode('list');
} else {
NotifAlert({
icon: 'error',
title: 'Gagal',
message: response?.message || 'Terjadi kesalahan saat menyimpan data.',
});
}
} catch (error) {
console.error('Save Sparepart Error:', error);
NotifAlert({
icon: 'error',
title: 'Error',
message: error.message || 'Terjadi kesalahan pada server. Coba lagi nanti.',
});
}
setConfirmLoading(false);
};
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value,
});
};
const handleFieldChange = (name, value) => {
setFormData({
...formData,
[name]: value,
});
};
const handleStatusToggle = (event) => {
const isChecked = event;
setFormData({
...formData,
is_active: isChecked ? true : false,
});
};
useEffect(() => {
if (props.selectedData) {
setFormData(props.selectedData);
} else {
setFormData(defaultData);
}
}, [props.showModal, props.selectedData, props.actionMode]);
return (
<Modal
title={`${
props.actionMode === 'add'
? 'Tambah'
: props.actionMode === 'preview'
? 'Preview'
: 'Edit'
} Sparepart`}
open={props.showModal}
onCancel={handleCancel}
footer={[
<React.Fragment key="modal-footer">
<ConfigProvider
theme={{
token: { colorBgContainer: '#E9F6EF' },
components: {
Button: {
defaultBg: 'white',
defaultColor: '#23A55A',
defaultBorderColor: '#23A55A',
defaultHoverColor: '#23A55A',
defaultHoverBorderColor: '#23A55A',
defaultHoverColor: '#23A55A',
},
},
}}
>
<Button onClick={handleCancel}>Batal</Button>
</ConfigProvider>
<ConfigProvider
theme={{
token: {
colorBgContainer: '#209652',
},
components: {
Button: {
defaultBg: '#23a55a',
defaultColor: '#FFFFFF',
defaultBorderColor: '#23a55a',
defaultHoverColor: '#FFFFFF',
defaultHoverBorderColor: '#23a55a',
},
},
}}
>
{!props.readOnly && (
<Button loading={confirmLoading} onClick={handleSave}>
Simpan
</Button>
)}
</ConfigProvider>
</React.Fragment>,
]}
>
{formData && (
<div>
<div hidden>
<Text strong>Sparepart ID</Text>
<Input
name="sparepart_id"
value={formData.sparepart_id}
onChange={handleInputChange}
disabled
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Sparepart Name</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="sparepart_name"
value={formData.sparepart_name}
onChange={handleInputChange}
placeholder="Enter Sparepart Name"
readOnly={props.readOnly}
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Sparepart Description</Text>
<TextArea
name="sparepart_description"
value={formData.sparepart_description}
onChange={handleInputChange}
placeholder="Enter Sparepart Description (Optional)"
readOnly={props.readOnly}
rows={4}
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Sparepart Model</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="sparepart_model"
value={formData.sparepart_model}
onChange={handleInputChange}
placeholder="Enter Sparepart Model"
readOnly={props.readOnly}
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Sparepart Item Type</Text>
<Input
name="sparepart_item_type"
value={formData.sparepart_item_type}
onChange={handleInputChange}
placeholder="Enter Sparepart Item Type"
readOnly={props.readOnly}
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Sparepart Unit</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="sparepart_unit"
value={formData.sparepart_unit}
onChange={handleInputChange}
placeholder="Enter Sparepart Unit"
readOnly={props.readOnly}
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Sparepart Merk</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="sparepart_merk"
value={formData.sparepart_merk}
onChange={handleInputChange}
placeholder="Enter Sparepart Merk"
readOnly={props.readOnly}
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Sparepart Stok</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="sparepart_stok"
value={formData.sparepart_stok}
onChange={handleInputChange}
placeholder="Enter Sparepart Stok"
readOnly={props.readOnly}
type="number"
/>
</div>
</div>
)}
</Modal>
);
};
export default DetailSparepart;

View File

@@ -0,0 +1,276 @@
import React, { memo, useState, useEffect } from 'react';
import { Space, Tag, ConfigProvider, Button, Row, Col, Card, Input, Segmented } from 'antd';
import {
PlusOutlined,
EditOutlined,
DeleteOutlined,
EyeOutlined,
SearchOutlined,
AppstoreOutlined,
TableOutlined,
} from '@ant-design/icons';
import { NotifAlert, NotifOk, NotifConfirmDialog } from '../../../../components/Global/ToastNotif';
import { useNavigate } from 'react-router-dom';
import { deleteSparepart, getAllSparepart } from '../../../../api/sparepart';
import TableList from '../../../../components/Global/TableList';
const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [
{
title: 'No',
key: 'no',
width: '5%',
align: 'center',
render: (_, __, index) => index + 1,
},
{
title: 'ID',
dataIndex: 'sparepart_id',
key: 'sparepart_id',
width: '5%',
hidden: 'true',
},
{
title: 'Sparepart Name',
dataIndex: 'sparepart_name',
key: 'sparepart_name',
width: '20%',
},
{
title: 'Description',
dataIndex: 'sparepart_description',
key: 'sparepart_description',
width: '20%',
render: (sparepart_description) => sparepart_description || '-'
},
{
title: 'Model',
dataIndex: 'sparepart_model',
key: 'sparepart_model',
width: '10%',
render: (sparepart_model) => sparepart_model || '-'
},
{
title: 'Item Type',
dataIndex: 'sparepart_item_type',
key: 'sparepart_item_type',
width: '10%',
render: (sparepart_item_type) => sparepart_item_type || '-'
},
{
title: 'Unit',
dataIndex: 'sparepart_unit',
key: 'sparepart_unit',
width: '8%',
render: (sparepart_unit) => sparepart_unit || '-'
},
{
title: 'Merk',
dataIndex: 'sparepart_merk',
key: 'sparepart_merk',
width: '12%',
render: (sparepart_merk) => sparepart_merk || '-'
},
{
title: 'Stock',
dataIndex: 'sparepart_stok',
key: 'sparepart_stok',
width: '8%',
render: (sparepart_stok) => sparepart_stok || '0'
},
{
title: 'Action',
key: 'aksi',
align: 'center',
width: '12%',
render: (_, record) => (
<Space>
<Button
type="text"
style={{ borderColor: '#1890ff' }}
icon={<EyeOutlined style={{ color: '#1890ff' }} />}
onClick={() => showPreviewModal(record)}
/>
<Button
type="text"
style={{ borderColor: '#faad14' }}
icon={<EditOutlined style={{ color: '#faad14' }} />}
onClick={() => showEditModal(record)}
/>
<Button
type="text"
danger
style={{ borderColor: 'red' }}
icon={<DeleteOutlined />}
onClick={() => showDeleteDialog(record)}
/>
</Space>
),
},
];
const ListSparepart = memo(function ListSparepart(props) {
const [trigerFilter, setTrigerFilter] = useState(false);
const defaultFilter = { criteria: '' };
const [formDataFilter, setFormDataFilter] = useState(defaultFilter);
const [searchValue, setSearchValue] = useState('');
const navigate = useNavigate();
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
if (props.actionMode === 'list') {
setFormDataFilter(defaultFilter);
doFilter();
}
} else {
navigate('/signin');
}
}, [props.actionMode]);
const doFilter = () => {
setTrigerFilter((prev) => !prev);
};
const handleSearch = () => {
setFormDataFilter({ criteria: searchValue });
setTrigerFilter((prev) => !prev);
};
const handleSearchClear = () => {
setSearchValue('');
setFormDataFilter({ criteria: '' });
setTrigerFilter((prev) => !prev);
};
const showPreviewModal = (param) => {
props.setSelectedData(param);
props.setActionMode('preview');
};
const showEditModal = (param = null) => {
props.setSelectedData(param);
props.setActionMode('edit');
};
const showAddModal = (param = null) => {
props.setSelectedData(param);
props.setActionMode('add');
};
const showDeleteDialog = (param) => {
NotifConfirmDialog({
icon: 'question',
title: 'Konfirmasi Hapus',
message: 'Sparepart "' + param.sparepart_name + '" akan dihapus?',
onConfirm: () => handleDelete(param.sparepart_id),
onCancel: () => props.setSelectedData(null),
});
};
const handleDelete = async (sparepart_id) => {
const response = await deleteSparepart(sparepart_id);
if (response.statusCode === 200 && response.data === true) {
NotifAlert({
icon: 'success',
title: 'Berhasil',
message: response.message || 'Data Sparepart berhasil dihapus.',
});
doFilter();
} else {
NotifOk({
icon: 'error',
title: 'Gagal',
message: response?.message || 'Gagal Menghapus Data Sparepart',
});
}
};
return (
<React.Fragment>
<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 sparepart by name, model, or merk..."
value={searchValue}
onChange={(e) => {
const value = e.target.value;
setSearchValue(value);
if (value === '') {
setFormDataFilter({ criteria: '' });
setTrigerFilter((prev) => !prev);
}
}}
onSearch={handleSearch}
allowClear={{
clearIcon: <span onClick={handleSearchClear}></span>,
}}
enterButton={
<Button
type="primary"
icon={<SearchOutlined />}
style={{
backgroundColor: '#23A55A',
borderColor: '#23A55A',
}}
>
Search
</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={() => showAddModal()}
size="large"
>
Add data
</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={'sparepart_name'}
showPreviewModal={showPreviewModal}
showEditModal={showEditModal}
showDeleteDialog={showDeleteDialog}
getData={getAllSparepart}
queryParams={formDataFilter}
columns={columns(showPreviewModal, showEditModal, showDeleteDialog)}
triger={trigerFilter}
/>
</Col>
</Row>
</Card>
</React.Fragment>
);
});
export default ListSparepart;

View File

@@ -84,12 +84,32 @@ const DetailTag = (props) => {
const params = new URLSearchParams({ limit: 10000 }); const params = new URLSearchParams({ limit: 10000 });
const response = await getAllTag(params); const response = await getAllTag(params);
if (response && response.data && response.data.data) { // Handle different response structures
const existingTags = response.data.data; let existingTags = [];
if (response) {
if (Array.isArray(response)) {
existingTags = response;
} else if (response.data && Array.isArray(response.data)) {
existingTags = response.data;
} else if (response.data && response.data.data && Array.isArray(response.data.data)) {
existingTags = response.data.data;
}
}
if (existingTags.length > 0) {
const isDuplicate = existingTags.some((tag) => { const isDuplicate = existingTags.some((tag) => {
const isSameNumber = Number(tag.tag_number) === tagNumberInt; // Handle both string and number tag_number
const isDifferentTag = formData.tag_id ? tag.tag_id !== formData.tag_id : true; const existingTagNumber = Number(tag.tag_number);
const currentTagNumber = Number(formData.tag_number);
// Check if numbers are valid and equal
const isSameNumber = !isNaN(existingTagNumber) && !isNaN(currentTagNumber) &&
existingTagNumber === currentTagNumber;
// For edit mode, exclude the current tag from duplicate check
const isDifferentTag = formData.tag_id ?
String(tag.tag_id) !== String(formData.tag_id) : true;
return isSameNumber && isDifferentTag; return isSameNumber && isDifferentTag;
}); });
@@ -97,7 +117,7 @@ const DetailTag = (props) => {
NotifOk({ NotifOk({
icon: 'warning', icon: 'warning',
title: 'Peringatan', title: 'Peringatan',
message: `Tag Number ${tagNumberInt} sudah digunakan. Silakan gunakan nomor yang berbeda.`, message: `Tag Number ${formData.tag_number} sudah digunakan. Silakan gunakan nomor yang berbeda.`,
}); });
setConfirmLoading(false); setConfirmLoading(false);
return; return;

View File

@@ -63,7 +63,7 @@ const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [
render: (text) => text || '-', render: (text) => text || '-',
}, },
{ {
title: 'Sub Section', title: 'Plant Sub Section',
dataIndex: 'plant_sub_section_name', dataIndex: 'plant_sub_section_name',
key: 'plant_sub_section_name', key: 'plant_sub_section_name',
width: '10%', width: '10%',

View File

@@ -12,6 +12,8 @@ import {
Modal, Modal,
Tag, Tag,
message, message,
Spin,
Pagination,
} from 'antd'; } from 'antd';
import { import {
CloseCircleFilled, CloseCircleFilled,
@@ -33,11 +35,12 @@ import {
FilePdfOutlined, FilePdfOutlined,
PlusOutlined, PlusOutlined,
ExclamationCircleOutlined, ExclamationCircleOutlined,
SearchOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom'; import { useNavigate, Link as RouterLink } from 'react-router-dom';
import { getAllNotification } from '../../../api/notification'; import { getAllNotification } from '../../../api/notification';
const { Text, Paragraph, Link } = Typography; const { Text, Paragraph, Link: AntdLink } = Typography;
// Transform API response to component format // Transform API response to component format
const transformNotificationData = (apiData) => { const transformNotificationData = (apiData) => {
@@ -57,7 +60,7 @@ const transformNotificationData = (apiData) => {
}) + ' WIB', }) + ' WIB',
location: item.device_location || 'Location not specified', location: item.device_location || 'Location not specified',
details: item.message_error_issue || 'No details available', details: item.message_error_issue || 'No details available',
link: '#', // Will be updated when API provides link link: `/verification-sparepart/${item.notification_error_id}`, // Dummy URL untuk verifikasi spare part
subsection: item.solution_name || 'N/A', subsection: item.solution_name || 'N/A',
isRead: item.is_read, isRead: item.is_read,
status: item.is_read ? 'Resolved' : item.is_delivered ? 'Delivered' : 'Pending', status: item.is_read ? 'Resolved' : item.is_delivered ? 'Delivered' : 'Pending',
@@ -129,25 +132,61 @@ const ListNotification = memo(function ListNotification(props) {
const [notifications, setNotifications] = useState([]); const [notifications, setNotifications] = useState([]);
const [activeTab, setActiveTab] = useState('all'); const [activeTab, setActiveTab] = useState('all');
const [searchTerm, setSearchTerm] = useState(''); const [searchTerm, setSearchTerm] = useState('');
const [searchValue, setSearchValue] = useState('');
const [loading, setLoading] = useState(false);
const [modalContent, setModalContent] = useState(null); // 'user', 'log', 'details', or null const [modalContent, setModalContent] = useState(null); // 'user', 'log', 'details', or null
const [isAddingLog, setIsAddingLog] = useState(false); const [isAddingLog, setIsAddingLog] = useState(false);
const [selectedNotification, setSelectedNotification] = useState(null); const [selectedNotification, setSelectedNotification] = useState(null);
const [pagination, setPagination] = useState({
current_page: 1,
current_limit: 10,
total_limit: 0,
total_page: 1,
});
const navigate = useNavigate(); const navigate = useNavigate();
// Fetch notifications from API // Fetch notifications from API
const fetchNotifications = async () => { const fetchNotifications = async () => {
setLoading(true);
try { try {
const response = await getAllNotification(); const response = await getAllNotification();
if (response && response.data) { if (response && response.data) {
const transformedData = transformNotificationData(response.data); const transformedData = transformNotificationData(response.data);
setNotifications(transformedData); setNotifications(transformedData);
// Update pagination with mock data (since API doesn't provide pagination info)
const totalItems = transformedData.length;
setPagination((prev) => ({
...prev,
total_limit: totalItems,
total_page: Math.ceil(totalItems / prev.current_limit),
}));
} }
} catch (error) { } catch (error) {
console.error('Error fetching notifications:', error); console.error('Error fetching notifications:', error);
setNotifications([]); setNotifications([]);
} finally {
setTimeout(() => {
setLoading(false);
}, 500);
} }
}; };
const handlePaginationChange = (page, pageSize) => {
setPagination((prev) => ({
...prev,
current_page: page,
current_limit: pageSize,
}));
};
// Get paginated notifications
const getPaginatedNotifications = () => {
const startIndex = (pagination.current_page - 1) * pagination.current_limit;
const endIndex = startIndex + pagination.current_limit;
return filteredNotifications.slice(startIndex, endIndex);
};
useEffect(() => { useEffect(() => {
const token = localStorage.getItem('token'); const token = localStorage.getItem('token');
if (!token) { if (!token) {
@@ -200,6 +239,15 @@ const ListNotification = memo(function ListNotification(props) {
); );
}; };
const handleSearch = () => {
setSearchTerm(searchValue);
};
const handleSearchClear = () => {
setSearchValue('');
setSearchTerm('');
};
const filteredNotifications = notifications const filteredNotifications = notifications
.filter((n) => { .filter((n) => {
const matchesTab = const matchesTab =
@@ -210,8 +258,8 @@ const ListNotification = memo(function ListNotification(props) {
}) })
.filter((n) => { .filter((n) => {
if (!searchTerm) return true; if (!searchTerm) return true;
const searchableText = // Search by title and error code name
`${n.title} ${n.issue} ${n.description} ${n.location} ${n.details}`.toLowerCase(); const searchableText = `${n.title} ${n.issue}`.toLowerCase();
return searchableText.includes(searchTerm.toLowerCase()); return searchableText.includes(searchTerm.toLowerCase());
}); });
@@ -230,14 +278,17 @@ const ListNotification = memo(function ListNotification(props) {
transition: 'all 0.3s', transition: 'all 0.3s',
}); });
const renderDeviceNotifications = () => ( const renderDeviceNotifications = () => {
<Space direction="vertical" size="middle" style={{ display: 'flex' }}> const paginatedNotifications = getPaginatedNotifications();
{filteredNotifications.length === 0 ? (
<div style={{ textAlign: 'center', padding: '40px 0', color: '#8c8c8c' }}> return (
Tidak ada notifikasi <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
</div> {filteredNotifications.length === 0 ? (
) : ( <div style={{ textAlign: 'center', padding: '40px 0', color: '#8c8c8c' }}>
filteredNotifications.map((notification) => { Tidak ada notifikasi
</div>
) : (
paginatedNotifications.map((notification) => {
const { IconComponent, color, bgColor } = getIconAndColor(notification.type); const { IconComponent, color, bgColor } = getIconAndColor(notification.type);
return ( return (
<Card <Card
@@ -333,9 +384,12 @@ const ListNotification = memo(function ListNotification(props) {
</Space> </Space>
<Space> <Space>
<LinkOutlined /> <LinkOutlined />
<Link href={notification.link} target="_blank"> <AntdLink
href={notification.link}
target="_blank"
>
{notification.link} {notification.link}
</Link> </AntdLink>
<Button <Button
type="link" type="link"
icon={<SendOutlined />} icon={<SendOutlined />}
@@ -380,22 +434,28 @@ const ListNotification = memo(function ListNotification(props) {
setModalContent('user'); setModalContent('user');
}} }}
/> />
<Button <RouterLink
type="text" to={`/detail-notification/${
icon={ notification.id.split('-')[1]
<EyeOutlined style={{ color: '#1890ff' }} /> }`}
} target="_blank"
title="Details" rel="noopener noreferrer"
style={{ onClick={(e) => e.stopPropagation()}
border: '1px solid #1890ff', >
borderRadius: '4px', <Button
}} type="text"
onClick={(e) => { icon={
e.stopPropagation(); <EyeOutlined
setModalContent('details'); style={{ color: '#1890ff' }}
setSelectedNotification(notification); />
}} }
/> title="Details"
style={{
border: '1px solid #1890ff',
borderRadius: '4px',
}}
/>
</RouterLink>
<Button <Button
type="text" type="text"
icon={ icon={
@@ -422,8 +482,9 @@ const ListNotification = memo(function ListNotification(props) {
); );
}) })
)} )}
</Space> </Space>
); );
};
const renderUserHistory = () => ( const renderUserHistory = () => (
<> <>
@@ -635,9 +696,7 @@ const ListNotification = memo(function ListNotification(props) {
<Text type="secondary" style={{ fontSize: '12px' }}> <Text type="secondary" style={{ fontSize: '12px' }}>
Treshold Treshold
</Text> </Text>
<div style={{ fontWeight: 500 }}> <div style={{ fontWeight: 500 }}>N/A</div>
N/A
</div>
</Col> </Col>
</Row> </Row>
</div> </div>
@@ -1041,37 +1100,24 @@ const ListNotification = memo(function ListNotification(props) {
</Button> </Button>
</Space> </Space>
</Card> </Card>
{logHistoryData.slice(0, 2).map( {logHistoryData.map((log) => (
( <Card
log // Menampilkan 2 log terbaru sebagai pratinjau key={log.id}
) => ( size="small"
<Card bodyStyle={{ padding: '8px 12px' }}
key={log.id}
size="small"
bodyStyle={{ padding: '8px 12px' }}
>
<Paragraph
style={{ fontSize: '12px', margin: 0 }}
ellipsis={{ rows: 2 }}
>
<Text strong>{log.addedBy.name}:</Text>{' '}
{log.description}
</Paragraph>
<Text type="secondary" style={{ fontSize: '11px' }}>
{log.timestamp}
</Text>
</Card>
)
)}
<div style={{ textAlign: 'center', paddingTop: '8px' }}>
<Button
type="link"
style={{ padding: 0 }}
onClick={() => setModalContent('log')}
> >
View All Log History <Paragraph
</Button> style={{ fontSize: '12px', margin: 0 }}
</div> ellipsis={{ rows: 2 }}
>
<Text strong>{log.addedBy.name}:</Text>{' '}
{log.description}
</Paragraph>
<Text type="secondary" style={{ fontSize: '11px' }}>
{log.timestamp}
</Text>
</Card>
))}
</Space> </Space>
</Card> </Card>
</Col> </Col>
@@ -1100,17 +1146,35 @@ const ListNotification = memo(function ListNotification(props) {
Riwayat notifikasi yang dikirim ke engineer Riwayat notifikasi yang dikirim ke engineer
</p> </p>
<Row <Row justify="space-between" align="middle" gutter={[8, 8]}>
justify="space-between" <Col xs={24} sm={24} md={12} lg={12}>
align="middle"
style={{ marginBottom: '24px' }}
>
<Col>
<Input.Search <Input.Search
placeholder="Search notifications..." placeholder="Search by notification name or error code name..."
onSearch={setSearchTerm} value={searchValue}
onChange={(e) => setSearchTerm(e.target.value)} onChange={(e) => {
style={{ width: 300 }} const value = e.target.value;
setSearchValue(value);
if (value === '') {
handleSearchClear();
}
}}
onSearch={handleSearch}
allowClear={{
clearIcon: <span onClick={handleSearchClear}></span>,
}}
enterButton={
<Button
type="primary"
icon={<SearchOutlined />}
style={{
backgroundColor: '#23A55A',
borderColor: '#23A55A',
}}
>
Search
</Button>
}
size="large"
/> />
</Col> </Col>
</Row> </Row>
@@ -1148,7 +1212,29 @@ const ListNotification = memo(function ListNotification(props) {
</div> </div>
</div> </div>
{renderDeviceNotifications()} <Spin spinning={loading}>
{renderDeviceNotifications()}
</Spin>
{/* PAGINATION */}
<Row justify="space-between" align="middle" style={{ marginTop: '16px' }}>
<Col>
<div>
Menampilkan {pagination.current_limit} data halaman{' '}
{pagination.current_page} dari total {pagination.total_limit} data
</div>
</Col>
<Col>
<Pagination
showSizeChanger
onChange={handlePaginationChange}
onShowSizeChange={handlePaginationChange}
current={pagination.current_page}
pageSize={pagination.current_limit}
total={pagination.total_limit}
/>
</Col>
</Row>
</Col> </Col>
</Row> </Row>
</Card> </Card>

View File

@@ -229,7 +229,7 @@ const ListRole = memo(function ListRole(props) {
onClick={() => showAddModal()} onClick={() => showAddModal()}
size="large" size="large"
> >
Add Data Add Role
</Button> </Button>
</ConfigProvider> </ConfigProvider>
</Space> </Space>

View File

@@ -0,0 +1,75 @@
import React from 'react';
import { Layout, Card, Row, Col, Typography, Button, Input } from 'antd';
import { ArrowLeftOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
const { Content } = Layout;
const { Title, Paragraph } = Typography;
const { Search } = Input;
const IndexVerificationSparepart = () => {
const navigate = useNavigate();
const { notification_error_id } = useParams();
return (
<Layout style={{ padding: '24px', backgroundColor: '#f0f2f5' }}>
<Content>
<Card>
<div style={{ borderBottom: '1px solid #f0f0f0', paddingBottom: '16px', marginBottom: '24px' }}>
<Row justify="space-between" align="middle">
<Col>
<Button
type="text"
icon={<ArrowLeftOutlined />}
onClick={() => navigate('/notification')}
style={{ paddingLeft: 0 }}
>
Kembali ke daftar notifikasi
</Button>
</Col>
</Row>
<div style={{ backgroundColor: '#f6ffed', border: '1px solid #b7eb8f', borderRadius: '4px 4px 0 0', padding: '8px 16px', marginTop: '16px' }}>
<Row justify="center" align="middle">
<Col>
<Title level={4} style={{ margin: 0, color: '#262626' }}>
List Available Sparepart
</Title>
</Col>
</Row>
<Paragraph style={{ margin: '4px 0 0', color: '#595959', textAlign: 'center' }}>
Select items from inventory to save changes
</Paragraph>
</div>
<div style={{ border: '1px solid #91d5ff', borderTop: 'none', backgroundColor: '#e6f7ff', padding: '12px 16px', borderRadius: '0 0 4px 4px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<ExclamationCircleOutlined style={{ color: '#1890ff', fontSize: '20px', marginRight: '12px' }} />
<Paragraph style={{ margin: 0 }}>
<strong>Important Notice:</strong> All items listed are currently in stock and available for immediate use. Please verify part numbers before installation. Selected items will be marked for inventory tracking.
</Paragraph>
</div>
</div>
<Row justify="space-between" align="middle" style={{ marginBottom: '24px' }}>
<Col>
<Title level={5} style={{ margin: 0 }}> Inventory</Title>
</Col>
<Col>
<Search
placeholder="Search in inventory"
onSearch={value => console.log(value)}
style={{ width: 200 }}
/>
</Col>
</Row>
{/* Konten untuk verifikasi spare part akan ditambahkan di sini */}
<div style={{ textAlign: 'center', padding: '40px 0' }}>
<Title level={5}>ID Notifikasi: {notification_error_id}</Title>
<p>Halaman ini dalam pengembangan. Di sini akan ditampilkan detail spare part yang perlu diverifikasi.</p>
</div>
</Card>
</Content>
</Layout>
);
};
export default IndexVerificationSparepart;