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

Reviewed-on: #18
This commit is contained in:
2025-11-17 08:27:39 +00:00
17 changed files with 2883 additions and 450 deletions

View File

@@ -33,6 +33,7 @@ import IndexReport from './pages/report/report/IndexReport';
import IndexNotification from './pages/notification/IndexNotification';
import IndexRole from './pages/role/IndexRole';
import IndexUser from './pages/user/IndexUser';
import IndexContact from './pages/contact/IndexContact';
import SvgTest from './pages/home/SvgTest';
import SvgOverviewCompressor from './pages/home/SvgOverviewCompressor';
@@ -112,6 +113,10 @@ const App = () => {
<Route index element={<IndexUser />} />
</Route>
<Route path="/contact" element={<ProtectedRoute />}>
<Route index element={<IndexContact />} />
</Route>
<Route path="/jadwal-shift" element={<ProtectedRoute />}>
<Route index element={<IndexJadwalShift />} />
</Route>

56
src/api/contact.jsx Normal file
View File

@@ -0,0 +1,56 @@
import { SendRequest } from '../components/Global/ApiRequest';
const getAllContact = async (queryParams) => {
const response = await SendRequest({
method: 'get',
prefix: `contact?${queryParams.toString()}`,
});
return response.data;
};
const getContactById = async (id) => {
const response = await SendRequest({
method: 'get',
prefix: `contact/${id}`,
});
return response.data;
};
const createContact = async (queryParams) => {
const response = await SendRequest({
method: 'post',
prefix: `contact`,
params: queryParams,
});
return response.data;
};
const updateContact = async (id, queryParams) => {
const response = await SendRequest({
method: 'put',
prefix: `contact/${id}`,
params: queryParams,
});
return response.data;
};
const deleteContact = async (id) => {
const response = await SendRequest({
method: 'delete',
prefix: `contact/${id}`,
});
return response.data;
};
export {
getAllContact,
getContactById,
createContact,
updateContact,
deleteContact,
};

View File

@@ -31,6 +31,7 @@ import {
GroupOutlined,
SlidersOutlined,
SnippetsOutlined,
ContactsOutlined,
} from '@ant-design/icons';
const { Text } = Typography;
@@ -75,7 +76,7 @@ const allItems = [
icon: <NodeExpandOutlined style={{ fontSize: '19px' }} />,
label: <Link to="/dashboard-svg/compressor-c">Compressor C</Link>,
},
]
],
},
{
key: 'dashboard-svg-airdryer',
@@ -102,7 +103,7 @@ const allItems = [
icon: <NodeExpandOutlined style={{ fontSize: '19px' }} />,
label: <Link to="/dashboard-svg/airdryer-c">Air Dryer C</Link>,
},
]
],
},
],
},
@@ -141,11 +142,11 @@ const allItems = [
icon: <SafetyOutlined style={{ fontSize: '19px' }} />,
label: <Link to="/master/status">Status</Link>,
},
{
key: 'master-shift',
icon: <ClockCircleOutlined style={{ fontSize: '19px' }} />,
label: <Link to="/master/shift">Shift</Link>,
},
// {
// key: 'master-shift',
// icon: <ClockCircleOutlined style={{ fontSize: '19px' }} />,
// label: <Link to="/master/shift">Shift</Link>,
// },
],
},
{
@@ -182,6 +183,15 @@ const allItems = [
},
],
},
{
key: 'contact',
icon: <ContactsOutlined style={{ fontSize: '19px' }} />,
label: (
<Link to="/contact" className="fontMenus">
Contact
</Link>
),
},
{
key: 'notification',
icon: <BellOutlined style={{ fontSize: '19px' }} />,
@@ -209,15 +219,15 @@ const allItems = [
</Link>
),
},
{
key: 'jadwal-shift',
icon: <CalendarOutlined style={{ fontSize: '19px' }} />,
label: (
<Link to="/jadwal-shift" className="fontMenus">
Jadwal Shift
</Link>
),
},
// {
// key: 'jadwal-shift',
// icon: <CalendarOutlined style={{ fontSize: '19px' }} />,
// label: (
// <Link to="/jadwal-shift" className="fontMenus">
// Jadwal Shift
// </Link>
// ),
// },
];
const LayoutMenu = () => {
@@ -236,6 +246,7 @@ const LayoutMenu = () => {
if (pathname === '/role') return 'role';
if (pathname === '/notification') return 'notification';
if (pathname === '/jadwal-shift') return 'jadwal-shift';
if (pathname === '/contact') return 'contact';
// Handle master routes
if (pathname.startsWith('/master/')) {
@@ -244,11 +255,11 @@ const LayoutMenu = () => {
const masterKeyMap = {
'plant-sub-section': 'master-plant-sub-section',
'brand-device': 'master-brand-device',
'device': 'master-device',
'unit': 'master-unit',
'tag': 'master-tag',
'status': 'master-status',
'shift': 'master-shift'
device: 'master-device',
unit: 'master-unit',
tag: 'master-tag',
status: 'master-status',
shift: 'master-shift',
};
return masterKeyMap[subPath] || `master-${subPath}`;
}
@@ -265,7 +276,7 @@ const LayoutMenu = () => {
if (subPath === 'airdryer-a') return 'dashboard-svg-airdryer-airdryer-a';
if (subPath === 'airdryer-b') return 'dashboard-svg-airdryer-airdryer-b';
if (subPath === 'airdryer-c') return 'dashboard-svg-airdryer-airdryer-c';
return `dashboard-svg-${subPath}`;
}
@@ -273,8 +284,8 @@ const LayoutMenu = () => {
if (pathname.startsWith('/report/')) {
const subPath = pathParts[1];
const reportKeyMap = {
'trending': 'report-trending',
'report': 'report-report'
trending: 'report-trending',
report: 'report-report',
};
return reportKeyMap[subPath] || `report-${subPath}`;
}
@@ -283,8 +294,8 @@ const LayoutMenu = () => {
if (pathname.startsWith('/history/')) {
const subPath = pathParts[1];
const historyKeyMap = {
'alarm': 'history-alarm',
'event': 'history-event'
alarm: 'history-alarm',
event: 'history-event',
};
return historyKeyMap[subPath] || `history-${subPath}`;
}
@@ -295,7 +306,7 @@ const LayoutMenu = () => {
// Function to get parent keys from menu key
const getParentKeys = (key) => {
const parentKeys = [];
if (key.startsWith('dashboard-svg-compressor-')) {
parentKeys.push('dashboard-svg', 'dashboard-svg-compressor');
} else if (key.startsWith('dashboard-svg-airdryer-')) {
@@ -309,7 +320,7 @@ const LayoutMenu = () => {
} else if (key.startsWith('history-')) {
parentKeys.push('history');
}
return parentKeys;
};
@@ -319,7 +330,7 @@ const LayoutMenu = () => {
setSelectedKeys([currentKey]);
const parentKeys = getParentKeys(currentKey);
// Always keep the parent menus open when a child is selected
if (parentKeys.length > 0) {
setStateOpenKeys(parentKeys);
@@ -348,13 +359,13 @@ const LayoutMenu = () => {
const onOpenChange = (openKeys) => {
const currentOpenKey = openKeys.find((key) => stateOpenKeys.indexOf(key) === -1);
// If clicking on a menu that was previously closed
if (currentOpenKey !== undefined) {
const repeatIndex = openKeys
.filter((key) => key !== currentOpenKey)
.findIndex((key) => levelKeys[key] === levelKeys[currentOpenKey]);
setStateOpenKeys(
openKeys
.filter((_, index) => index !== repeatIndex)
@@ -365,12 +376,10 @@ const LayoutMenu = () => {
// but keep other parent menus open if they have active children
const currentKey = getMenuKeyFromPath(location.pathname);
const necessaryParentKeys = getParentKeys(currentKey);
// Filter out only the menus that are necessary to keep open
const filteredOpenKeys = openKeys.filter(key =>
necessaryParentKeys.includes(key)
);
const filteredOpenKeys = openKeys.filter((key) => necessaryParentKeys.includes(key));
setStateOpenKeys(filteredOpenKeys);
}
};
@@ -380,9 +389,7 @@ const LayoutMenu = () => {
const karyawan = () => {
return allItems
.filter(
(item) => item.key !== 'setting'
)
.filter((item) => item.key !== 'setting')
.map((item) => {
if (item.key === 'master') {
return {
@@ -392,7 +399,7 @@ const LayoutMenu = () => {
return item;
});
};
const items = isAdmin === 1 ? allItems : karyawan();
return (
@@ -412,4 +419,4 @@ const LayoutMenu = () => {
/>
);
};
export default LayoutMenu;
export default LayoutMenu;

View File

@@ -0,0 +1,72 @@
import React, { memo, useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import ListContact from './component/ListContact';
import DetailContact from './component/DetailContact';
import { useBreadcrumb } from '../../layout/LayoutBreadcrumb';
import { Typography } from 'antd';
const { Text } = Typography;
const IndexContact = memo(function IndexContact() {
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 [contactType, setContactType] = useState('operator');
const setMode = (param) => {
setShowModal(param !== 'list');
setReadOnly(param === 'preview');
setActionMode(param);
};
const handleContactSaved = (contactData, actionMode) => {
setLastSavedContact({ contactData, actionMode });
// Clear after processing
setTimeout(() => setLastSavedContact(null), 100);
};
const [lastSavedContact, setLastSavedContact] = useState(null);
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
setBreadcrumbItems([
{ title: <Text strong style={{ fontSize: '14px' }}> Contact</Text> },
]);
} else {
navigate('/signin');
}
}, [navigate, setBreadcrumbItems]);
return (
<React.Fragment>
<ListContact
actionMode={actionMode}
setActionMode={setMode}
selectedData={selectedData}
setSelectedData={setSelectedData}
readOnly={readOnly}
lastSavedContact={lastSavedContact}
setContactType={setContactType}
/>
<DetailContact
setActionMode={setMode}
selectedData={selectedData}
setSelectedData={setSelectedData}
readOnly={readOnly}
showModal={showModal}
actionMode={actionMode}
onContactSaved={handleContactSaved}
contactType={contactType}
/>
</React.Fragment>
);
});
export default IndexContact;

View File

@@ -0,0 +1,274 @@
import React, { memo, useEffect, useState } from 'react';
import { Modal, Input, Button, Switch, ConfigProvider, Typography, Divider, Select } from 'antd';
import { NotifAlert, NotifOk } from '../../../components/Global/ToastNotif';
import { validateRun } from '../../../Utils/validate';
import { createContact, updateContact } from '../../../api/contact';
const { Text } = Typography;
const DetailContact = memo(function DetailContact(props) {
const [confirmLoading, setConfirmLoading] = useState(false);
const defaultData = {
id: '',
name: '',
phone: '',
is_active: true,
contact_type: 'operator',
};
const [formData, setFormData] = useState(defaultData);
const handleInputChange = (e) => {
let name, value;
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
if (name === 'phone') {
value = value.replace(/[^0-9+\-\s()]/g, '');
}
if (name) {
setFormData((prev) => ({
...prev,
[name]: value,
}));
}
};
const handleStatusToggle = (checked) => {
setFormData({
...formData,
is_active: checked,
});
};
const handleSave = async () => {
setConfirmLoading(true);
// Custom validation untuk name - minimal 3 karakter
if (formData.name && formData.name.length < 3) {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Nama contact minimal 3 karakter',
});
setConfirmLoading(false);
return;
}
// Custom validation untuk phone - Indonesian phone format
const phoneRegex = /^(?:\+62|0)8\d{7,10}$/;
if (formData.phone && !phoneRegex.test(formData.phone.replace(/[\s\-\(\)]/g, ''))) {
NotifOk({
icon: 'warning',
title: 'Peringatan',
message: 'Nomor telepon harus format Indonesia (+628XXXXXXXXX atau 08XXXXXXXXX)',
});
setConfirmLoading(false);
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 {
const contactData = {
contact_name: formData.name,
contact_phone: formData.phone.replace(/[\s\-\(\)]/g, ''), // Clean phone number
is_active: formData.is_active,
contact_type: formData.contact_type,
};
let response;
if (props.actionMode === 'edit') {
response = await updateContact(props.selectedData.contact_id || props.selectedData.id, contactData);
} else {
response = await createContact(contactData);
}
NotifAlert({
icon: 'success',
title: 'Berhasil',
message: `Data Contact berhasil ${
props.actionMode === 'add' ? 'ditambahkan' : 'diperbarui'
}.`,
});
props.onContactSaved?.(response.data, props.actionMode);
handleCancel();
} catch (error) {
console.error('Save failed:', error);
NotifAlert({
icon: 'error',
title: 'Error',
message: error.response?.data?.message || 'Terjadi kesalahan saat menyimpan data.',
});
} finally {
setConfirmLoading(false);
}
};
const handleCancel = () => {
props.setActionMode('list');
props.setSelectedData(null);
};
useEffect(() => {
if (props.showModal) {
if (props.actionMode === 'edit' && props.selectedData) {
setFormData({
name: props.selectedData.contact_name || props.selectedData.name,
phone: props.selectedData.contact_phone || props.selectedData.phone,
is_active: props.selectedData.is_active || props.selectedData.status === 'active',
contact_type: props.selectedData.contact_type || props.contactType || 'operator',
});
} else if (props.actionMode === 'add') {
setFormData({
name: '',
phone: '',
is_active: true,
contact_type: props.contactType === 'all' ? 'operator' : props.contactType || 'operator',
});
}
}
}, [props.showModal, props.actionMode, props.selectedData, props.contactType]);
return (
<Modal
title={`${
props.actionMode === 'add'
? 'Tambah'
: props.actionMode === 'edit'
? 'Edit'
: 'Detail'
} Kontak`}
open={props.showModal}
onCancel={handleCancel}
footer={[
<React.Fragment key="modal-footer">
<ConfigProvider
theme={{
components: {
Button: {
defaultBg: 'white',
defaultColor: '#23A55A',
defaultBorderColor: '#23A55A',
},
},
}}
>
<Button onClick={handleCancel}>{props.readOnly ? 'Tutup' : 'Batal'}</Button>
</ConfigProvider>
<ConfigProvider
theme={{
components: {
Button: {
defaultBg: '#23a55a',
defaultColor: '#FFFFFF',
defaultBorderColor: '#23a55a',
},
},
}}
>
{!props.readOnly && (
<Button loading={confirmLoading} onClick={handleSave}>
Simpan
</Button>
)}
</ConfigProvider>
</React.Fragment>,
]}
>
<div style={{ padding: '8px 0' }}>
<div>
<div>
<Text strong>Status</Text>
</div>
<div style={{ display: 'flex', alignItems: 'center', marginTop: '8px' }}>
<div style={{ marginRight: '8px' }}>
<Switch
disabled={props.readOnly}
style={{
backgroundColor: formData.is_active ? '#23A55A' : '#bfbfbf',
}}
checked={formData.is_active}
onChange={handleStatusToggle}
/>
</div>
<div>
<Text>{formData.is_active ? 'Active' : 'Inactive'}</Text>
</div>
</div>
</div>
<Divider style={{ margin: '12px 0' }} />
<div style={{ marginBottom: 12 }}>
<Text strong>Name</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="name"
value={formData.name}
onChange={handleInputChange}
placeholder="Enter Name"
readOnly={props.readOnly}
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Phone</Text>
<Text style={{ color: 'red' }}> *</Text>
<Input
name="phone"
value={formData.phone}
onChange={handleInputChange}
placeholder="Enter Phone Number"
readOnly={props.readOnly}
maxLength={15}
style={{ color: formData.is_active ? '#000000' : '#ff4d4f' }}
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text strong>Contact Type</Text>
<Text style={{ color: 'red' }}> *</Text>
<Select
value={formData.contact_type}
onChange={handleInputChange}
placeholder="Select Contact Type"
disabled={props.readOnly}
style={{ width: '100%' }}
>
<Select.Option value="operator">Operator</Select.Option>
<Select.Option value="gudang">Gudang</Select.Option>
</Select>
</div>
</div>
</Modal>
);
});
export default DetailContact;

View File

@@ -0,0 +1,434 @@
import React, { memo, useState, useEffect } from 'react';
import { Button, Row, Col, Input, Tabs, Space, ConfigProvider, Card, Tag } from 'antd';
import {
PlusOutlined,
EditOutlined,
DeleteOutlined,
SearchOutlined,
UserOutlined,
PhoneOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { NotifAlert, NotifConfirmDialog } from '../../../components/Global/ToastNotif';
import { getAllContact, deleteContact } from '../../../api/contact';
const ContactCard = memo(function ContactCard({ contact, showEditModal, showDeleteModal }) {
return (
<Col xs={24} sm={12} md={8} lg={6}>
<div
className="contact-card"
style={{
marginBottom: 16,
borderRadius: 8,
boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
height: '100%',
padding: '16px',
backgroundColor: '#f5f5f5',
border: '1px solid #e8e8e8',
transition: 'all 0.3s ease',
cursor: 'pointer',
}}
onMouseEnter={(e) => {
e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.1)';
}}
>
<div
style={{
height: '100%',
display: 'flex',
flexDirection: 'column',
position: 'relative',
}}
>
{/* Type Badge - Top Left */}
<div style={{ position: 'absolute', top: 0, left: 0, zIndex: 1 }}>
<Tag
color={
contact.contact_type === 'operator'
? 'blue'
: contact.contact_type === 'gudang'
? 'orange'
: 'default'
}
style={{ fontSize: '11px' }}
>
{contact.contact_type === 'operator' ? 'Operator' : contact.contact_type === 'gudang' ? 'Gudang' : 'Unknown'}
</Tag>
</div>
{/* Status Badge - Top Right */}
<div style={{ position: 'absolute', top: 0, right: 0, zIndex: 1 }}>
{contact.status === 'active' ? (
<Tag color={'green'} style={{ fontSize: '11px' }}>
Active
</Tag>
) : (
<Tag color={'red'} style={{ fontSize: '11px' }}>
InActive
</Tag>
)}
</div>
{/* Main Content */}
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 12,
flex: 1,
paddingTop: '28px',
}}
>
<div
className="avatar"
style={{
width: 55,
height: 55,
borderRadius: '50%',
backgroundColor:
contact.status === 'active' ? '#52c41a' : '#ff4d4f',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
<UserOutlined style={{ color: 'white', fontSize: '25px' }} />
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div
style={{
fontWeight: 600,
fontSize: '16px',
marginBottom: '4px',
color: '#262626',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
}}
>
{contact.contact_name || contact.name}
</div>
<div
style={{
display: 'flex',
alignItems: 'center',
fontSize: '14px',
}}
>
<PhoneOutlined style={{ marginRight: 6, color: '#1890ff' }} />
<span
style={{
color: contact.status === 'active' ? '#52c41a' : '#ff4d4f',
}}
>
{contact.contact_phone || contact.phone}
</span>
</div>
</div>
</div>
{/* Edit and Delete Buttons - Bottom Right */}
<div
style={{
display: 'flex',
justifyContent: 'flex-end',
gap: '8px',
marginTop: '8px',
}}
>
<Space>
<Button
type="text"
size="small"
style={{
borderColor: '#faad14',
padding: '2px 6px',
fontSize: '11px',
height: '24px',
}}
icon={
<EditOutlined style={{ color: '#faad14', fontSize: '11px' }} />
}
onClick={(e) => {
e.stopPropagation();
showEditModal(contact);
}}
>
Edit info
</Button>
<Button
type="text"
danger
size="small"
style={{
borderColor: 'red',
padding: '2px 6px',
fontSize: '11px',
height: '24px',
}}
icon={<DeleteOutlined style={{ fontSize: '11px' }} />}
onClick={(e) => {
e.stopPropagation();
showDeleteModal(contact);
}}
>
Delete
</Button>
</Space>
</div>
</div>
</div>
</Col>
);
});
const ListContact = memo(function ListContact(props) {
const [activeTab, setActiveTab] = useState('all');
const [filteredContacts, setFilteredContacts] = useState([]);
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
// Default filter object matching plantSection pattern
const defaultFilter = { criteria: '' };
const [formDataFilter, setFormDataFilter] = useState(defaultFilter);
// Fetch contacts from API
const fetchContacts = async () => {
setLoading(true);
try {
// Build search parameters matching database pattern
const searchParams = { ...formDataFilter };
// Add specific filters if not "all"
if (activeTab !== 'all') {
if (activeTab === 'operator') {
searchParams.code = 'operator';
} else if (activeTab === 'gudang') {
searchParams.code = 'gudang';
}
}
// Backend doesn't support is_active filter or order parameter
// Contact hanya supports: criteria, name, code, limit, page
const queryParams = new URLSearchParams();
Object.entries(searchParams).forEach(([key, value]) => {
if (value !== '' && value !== null && value !== undefined) {
queryParams.append(key, value);
}
});
const response = await getAllContact(queryParams);
setFilteredContacts(response.data || []);
} catch (error) {
console.error('Error fetching contacts:', error);
NotifAlert({
icon: 'error',
title: 'Error',
message: 'Gagal memuat data kontak',
});
} finally {
setLoading(false);
}
};
// Fetch contacts on component mount
useEffect(() => {
const token = localStorage.getItem('token');
if (!token) {
navigate('/signin');
return;
}
fetchContacts();
}, []);
// Refetch when filters change
useEffect(() => {
fetchContacts();
}, [formDataFilter, activeTab]);
// Listen for saved contact data
useEffect(() => {
if (props.lastSavedContact) {
fetchContacts(); // Refetch all contacts when data is saved
}
}, [props.lastSavedContact]);
// Get contacts (already filtered by backend)
const getFilteredContacts = () => {
return filteredContacts;
};
const showEditModal = (param) => {
props.setSelectedData(param);
props.setActionMode('edit');
};
const showAddModal = () => {
props.setSelectedData(null);
props.setActionMode('add');
// Pass the current active tab to determine contact type
props.setContactType?.(activeTab);
};
const showDeleteModal = (contact) => {
NotifConfirmDialog({
icon: 'question',
title: 'Konfirmasi Hapus',
message: `Kontak "${contact.contact_name || contact.name}" akan dihapus?`,
onConfirm: () => handleDelete(contact),
onCancel: () => props.setSelectedData(null),
});
};
const handleDelete = async (contact) => {
try {
await deleteContact(contact.contact_id || contact.id);
NotifAlert({
icon: 'success',
title: 'Berhasil',
message: `Kontak "${contact.contact_name || contact.name}" berhasil dihapus.`,
});
// Refetch contacts after deletion
fetchContacts();
} catch (error) {
console.error('Error deleting contact:', error);
NotifAlert({
icon: 'error',
title: 'Error',
message: 'Gagal menghapus kontak',
});
}
};
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 by name or type..."
value={formDataFilter.criteria}
onChange={(e) => {
const value = e.target.value;
setFormDataFilter({ criteria: value });
if (value === '') {
setFormDataFilter(defaultFilter);
}
}}
onSearch={(value) => setFormDataFilter({ criteria: value })}
allowClear={{
clearIcon: (
<span onClick={() => setFormDataFilter(defaultFilter)}>
</span>
),
}}
enterButton={
<Button
type="primary"
icon={<SearchOutlined />}
style={{
backgroundColor: '#23A55A',
borderColor: '#23A55A',
}}
>
Search
</Button>
}
size="large"
/>
</Col>
<Col>
<Space wrap size="small">
<ConfigProvider
theme={{
components: {
Button: {
defaultBg: 'white',
defaultColor: '#23A55A',
defaultBorderColor: '#23A55A',
},
},
}}
>
<Button
icon={<PlusOutlined />}
onClick={() => showAddModal()}
size="large"
>
Add Contact
</Button>
</ConfigProvider>
</Space>
</Col>
</Row>
</Col>
<Col xs={24} style={{ marginTop: '16px' }}>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '16px',
}}
>
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
size="large"
items={[
{
key: 'all',
label: 'All',
},
{
key: 'operator',
label: 'Operator',
},
{
key: 'gudang',
label: 'Gudang',
},
]}
/>
</div>
{getFilteredContacts().length === 0 ? (
<div style={{ textAlign: 'center', padding: '40px' }}>
<span style={{ color: '#8c8c8c' }}>
{loading ? 'Loading contacts...' : 'No contacts found'}
</span>
</div>
) : (
<Row gutter={[16, 16]}>
{getFilteredContacts().map((contact) => (
<ContactCard
key={contact.contact_id || contact.id}
contact={{
...contact,
id: contact.contact_id || contact.id,
name: contact.contact_name || contact.name,
phone: contact.contact_phone || contact.phone,
status: contact.is_active ? 'active' : 'inactive',
}}
showEditModal={showEditModal}
showDeleteModal={showDeleteModal}
/>
))}
</Row>
)}
</Col>
</Row>
</Card>
</React.Fragment>
);
});
export default ListContact;

View File

@@ -1,14 +1,19 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Divider, Typography, Button, Steps, Form, Row, Col, Card } from 'antd';
import { Divider, Typography, Button, Steps, Form, Row, Col, Card, ConfigProvider } from 'antd';
import { NotifAlert, NotifOk } from '../../../components/Global/ToastNotif';
import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb';
import { createBrand } from '../../../api/master-brand';
import BrandForm from './component/BrandForm';
import ErrorCodeForm from './component/ErrorCodeForm';
import ErrorCodeSimpleForm from './component/ErrorCodeSimpleForm';
import ErrorCodeTable from './component/ListErrorCode';
import ErrorCodeListModal from './component/ErrorCodeListModal';
import FormActions from './component/FormActions';
import { useErrorCodeLogic } from './hooks/errorCode';
import SparepartForm from './component/SparepartForm';
import SolutionForm from './component/SolutionForm';
import { useSolutionLogic } from './hooks/solution';
import { useSparepartLogic } from './hooks/sparepart';
import { uploadFile, getFolderFromFileType } from '../../../api/file-uploads';
const { Title } = Typography;
@@ -28,6 +33,8 @@ const AddBrandDevice = () => {
const { setBreadcrumbItems } = useBreadcrumb();
const [brandForm] = Form.useForm();
const [errorCodeForm] = Form.useForm();
const [solutionForm] = Form.useForm();
const [sparepartForm] = Form.useForm();
const [confirmLoading, setConfirmLoading] = useState(false);
const [currentStep, setCurrentStep] = useState(0);
const [fileList, setFileList] = useState([]);
@@ -37,21 +44,53 @@ const AddBrandDevice = () => {
const [formData, setFormData] = useState(defaultData);
const [errorCodes, setErrorCodes] = useState([]);
const [errorCodeIcon, setErrorCodeIcon] = useState(null);
const [showErrorCodeModal, setShowErrorCodeModal] = useState(false);
const [sparepartImages, setSparepartImages] = useState({});
const {
solutionFields,
solutionTypes,
solutionStatuses,
firstSolutionValid,
solutionsToDelete,
firstSolutionValid,
handleAddSolutionField,
handleRemoveSolutionField,
handleSolutionTypeChange,
handleSolutionStatusChange,
resetSolutionFields,
checkFirstSolutionValid,
getSolutionData,
setSolutionsForExistingRecord,
} = useErrorCodeLogic(errorCodeForm, fileList);
} = useSolutionLogic(solutionForm);
const {
sparepartFields,
sparepartTypes,
sparepartStatuses,
handleAddSparepartField,
handleRemoveSparepartField,
handleSparepartTypeChange,
handleSparepartStatusChange,
resetSparepartFields,
getSparepartData,
setSparepartForExistingRecord,
} = 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(() => {
setBreadcrumbItems([
@@ -96,6 +135,17 @@ const AddBrandDevice = () => {
const handleFinish = async () => {
setConfirmLoading(true);
try {
// Validation: Ensure at least one error code
if (errorCodes.length === 0) {
NotifAlert({
icon: 'warning',
title: 'Perhatian',
message: 'Setidaknya tambahkan 1 error code!',
});
setConfirmLoading(false);
return;
}
const transformedErrorCodes = errorCodes.map((ec) => ({
error_code: ec.error_code,
error_code_name: ec.error_code_name || '',
@@ -110,6 +160,13 @@ const AddBrandDevice = () => {
path_solution: sol.path_solution || '',
is_active: sol.is_active !== false,
})),
// Note: Sparepart data is collected but not sent to backend yet
// sparepart: (ec.sparepart || []).map((sp) => ({
// type: sp.type || 'required',
// name: sp.name || '',
// quantity: sp.quantity || 1,
// is_active: sp.is_active !== false,
// })),
}));
const finalFormData = {
@@ -118,30 +175,11 @@ const AddBrandDevice = () => {
brand_model: formData.brand_model || '',
brand_manufacture: formData.brand_manufacture,
is_active: formData.is_active,
error_code:
transformedErrorCodes.length > 0
? transformedErrorCodes
: [
{
error_code: 'DEFAULT',
error_code_name: 'Default Error Code',
error_code_description: 'Default error description',
error_code_color: '#000000',
path_icon: '',
is_active: true,
solution: [
{
solution_name: 'Default Solution',
type_solution: 'text',
text_solution: 'Default solution text',
path_solution: '',
is_active: true,
},
],
},
],
error_code: transformedErrorCodes,
};
console.log('Final form data:', finalFormData); // Debug log
const response = await createBrand(finalFormData);
if (response && (response.statusCode === 200 || response.statusCode === 201)) {
@@ -159,6 +197,7 @@ const AddBrandDevice = () => {
});
}
} catch (error) {
console.error('Finish Error:', error);
NotifAlert({
icon: 'error',
title: 'Gagal',
@@ -183,17 +222,26 @@ const AddBrandDevice = () => {
setEditingErrorCodeKey(null);
if (record.solution && record.solution.length > 0) {
setSolutionsForExistingRecord(record.solution, errorCodeForm);
setSolutionsForExistingRecord(record.solution, solutionForm);
}
if (record.sparepart && record.sparepart.length > 0) {
setSparepartForExistingRecord(record.sparepart, sparepartForm);
}
};
const handleEditErrorCode = (record) => {
// Prevent infinite loop
if (editingErrorCodeKey === record.key) {
return;
}
errorCodeForm.setFieldsValue({
error_code: record.error_code,
error_code_name: record.error_code_name,
error_code_description: record.error_code_description,
error_code_color: record.error_code_color,
status: record.status,
error_code_color: record.error_code_color || '#000000',
status: record.status !== false,
});
setFileList(record.fileList || []);
setErrorCodeIcon(record.errorCodeIcon || null);
@@ -201,38 +249,102 @@ const AddBrandDevice = () => {
setEditingErrorCodeKey(record.key);
if (record.solution && record.solution.length > 0) {
setSolutionsForExistingRecord(record.solution, errorCodeForm);
// Reset solution fields first
resetSolutionFields();
// Then load new solutions
setTimeout(() => {
setSolutionsForExistingRecord(record.solution, solutionForm);
}, 0);
} else {
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 (newErrorCode) => {
// Include the current icon in the error code
const errorCodeWithIcon = {
...newErrorCode,
errorCodeIcon: errorCodeIcon
};
const handleAddErrorCode = async () => {
try {
const formValues = errorCodeForm.getFieldsValue();
if (editingErrorCodeKey) {
const updatedCodes = errorCodes.map((item) =>
item.key === editingErrorCodeKey ? errorCodeWithIcon : item
);
setErrorCodes(updatedCodes);
NotifOk({
icon: 'success',
title: 'Berhasil',
message: 'Error code berhasil diupdate!',
});
} else {
const updatedCodes = [...errorCodes, errorCodeWithIcon];
setErrorCodes(updatedCodes);
NotifOk({
icon: 'success',
title: 'Berhasil',
message: 'Error code berhasil ditambahkan!',
// Validation
if (!formValues.error_code || !formValues.error_code_name) {
NotifAlert({
icon: 'warning',
title: 'Perhatian',
message: 'Error code dan error name wajib diisi!',
});
return;
}
// Validate at least 1 solution
const solutions = getSolutionData();
if (solutions.length === 0) {
NotifAlert({
icon: 'warning',
title: 'Perhatian',
message: 'Setiap error code harus memiliki minimal 1 solution!',
});
return;
}
// Get sparepart data (optional, no backend yet)
const spareparts = getSparepartData() || [];
const newErrorCode = {
key: Date.now(),
error_code: formValues.error_code,
error_code_name: formValues.error_code_name || '',
error_code_description: formValues.error_code_description || '',
error_code_color: formValues.error_code_color || '#000000',
path_icon: errorCodeIcon?.uploadPath || '',
status: formValues.status !== false,
errorCodeIcon: errorCodeIcon,
solution: solutions,
sparepart: spareparts,
};
if (editingErrorCodeKey) {
const updatedCodes = errorCodes.map((item) =>
item.key === editingErrorCodeKey ? newErrorCode : item
);
setErrorCodes(updatedCodes);
NotifOk({
icon: 'success',
title: 'Berhasil',
message: 'Error code berhasil diupdate!',
});
} else {
const updatedCodes = [...errorCodes, newErrorCode];
setErrorCodes(updatedCodes);
NotifOk({
icon: 'success',
title: 'Berhasil',
message: 'Error code berhasil ditambahkan!',
});
}
// Reset all forms
resetErrorCodeForm();
resetSolutionFields();
resetSparepartFields();
} catch (error) {
console.error('Error adding error code:', error);
NotifAlert({
icon: 'error',
title: 'Error',
message: 'Gagal menambahkan error code',
});
}
resetErrorCodeForm();
};
const resetErrorCodeForm = () => {
@@ -366,62 +478,132 @@ const AddBrandDevice = () => {
if (currentStep === 1) {
return (
<Row gutter={24}>
<Col span={8}>
<Title level={5} style={{ marginBottom: 16 }}>
{isErrorCodeFormReadOnly
? 'View Error Code'
: editingErrorCodeKey
? 'Edit Error Code'
: 'Tambah Error Code'}
</Title>
<Form
form={errorCodeForm}
layout="vertical"
initialValues={{
status: true,
solution_status_0: true,
solution_type_0: 'text',
}}
onValuesChange={checkFirstSolutionValid}
>
<ErrorCodeForm
errorCodeForm={errorCodeForm}
isErrorCodeFormReadOnly={isErrorCodeFormReadOnly}
editingErrorCodeKey={editingErrorCodeKey}
solutionFields={solutionFields}
solutionTypes={solutionTypes}
solutionStatuses={solutionStatuses}
fileList={fileList}
solutionsToDelete={solutionsToDelete}
firstSolutionValid={firstSolutionValid}
onAddErrorCode={handleAddErrorCode}
onAddSolutionField={handleAddSolutionField}
onRemoveSolutionField={handleRemoveSolutionField}
onSolutionTypeChange={handleSolutionTypeChange}
onSolutionStatusChange={handleSolutionStatusChange}
onSolutionFileUpload={handleSolutionFileUpload}
onFileView={handleFileView}
onCreateNewErrorCode={handleCreateNewErrorCode}
onResetForm={resetErrorCodeForm}
errorCodes={errorCodes}
errorCodeIcon={errorCodeIcon}
onErrorCodeIconUpload={handleErrorCodeIconUpload}
onErrorCodeIconRemove={handleErrorCodeIconRemove}
/>
</Form>
</Col>
<Col span={16}>
<ErrorCodeTable
errorCodes={errorCodes}
loading={loading}
onPreview={handlePreviewErrorCode}
onEdit={handleEditErrorCode}
onDelete={handleDeleteErrorCode}
onFileView={handleFileView}
/>
</Col>
</Row>
<>
<Row gutter={16} style={{ marginBottom: 24 }}>
{/* Error Code Form Column */}
<Col span={8}>
<Card size="small" title="Error Code">
<Form
form={errorCodeForm}
layout="vertical"
initialValues={{
status: true,
}}
>
<ErrorCodeSimpleForm
errorCodeForm={errorCodeForm}
isErrorCodeFormReadOnly={isErrorCodeFormReadOnly}
errorCodeIcon={errorCodeIcon}
onErrorCodeIconUpload={handleErrorCodeIconUpload}
onErrorCodeIconRemove={handleErrorCodeIconRemove}
onAddErrorCode={handleAddErrorCode}
/>
</Form>
</Card>
</Col>
{/* Solution Form Column */}
<Col span={8}>
<Card size="small" title="Solutions">
<Form
form={solutionForm}
layout="vertical"
initialValues={{
solution_status_0: true,
solution_type_0: 'text',
}}
onValuesChange={checkFirstSolutionValid}
>
<SolutionForm
solutionForm={solutionForm}
solutionFields={solutionFields}
solutionTypes={solutionTypes}
solutionStatuses={solutionStatuses}
fileList={fileList}
solutionsToDelete={solutionsToDelete}
firstSolutionValid={firstSolutionValid}
onAddSolutionField={handleAddSolutionField}
onRemoveSolutionField={handleRemoveSolutionField}
onSolutionTypeChange={handleSolutionTypeChange}
onSolutionStatusChange={handleSolutionStatusChange}
onSolutionFileUpload={handleSolutionFileUpload}
onFileView={handleFileView}
isReadOnly={isErrorCodeFormReadOnly}
/>
</Form>
</Card>
</Col>
{/* Sparepart Form Column */}
<Col span={8}>
<Card size="small" title="Spareparts">
<Form
form={sparepartForm}
layout="vertical"
initialValues={{
sparepart_status_0: true,
sparepart_type_0: 'required',
}}
>
<SparepartForm
sparepartForm={sparepartForm}
sparepartFields={sparepartFields}
onAddSparepartField={handleAddSparepartField}
onRemoveSparepartField={handleRemoveSparepartField}
onSparepartTypeChange={handleSparepartTypeChange}
onSparepartStatusChange={handleSparepartStatusChange}
onSparepartImageUpload={handleSparepartImageUpload}
onSparepartImageRemove={handleSparepartImageRemove}
sparepartImages={sparepartImages}
isReadOnly={false}
/>
</Form>
</Card>
</Col>
</Row>
{/* Error Codes List Button */}
<Row justify="center">
<Col>
<ConfigProvider
theme={{
token: { colorBgContainer: '#23a55ade' },
components: {
Button: {
defaultBg: '#23a55a',
defaultColor: '#FFFFFF',
defaultBorderColor: '#23a55a',
defaultHoverBg: '#209652',
defaultHoverColor: '#FFFFFF',
defaultHoverBorderColor: '#23a55a',
},
},
}}
>
<Button
type="primary"
size="large"
onClick={() => setShowErrorCodeModal(true)}
style={{ minWidth: '200px' }}
>
View All Error Codes ({errorCodes.length})
</Button>
</ConfigProvider>
</Col>
</Row>
{/* Error Codes List Modal */}
<ErrorCodeListModal
visible={showErrorCodeModal}
onClose={() => setShowErrorCodeModal(false)}
errorCodes={errorCodes}
loading={loading}
onPreview={handlePreviewErrorCode}
onEdit={handleEditErrorCode}
onDelete={handleDeleteErrorCode}
onAddNew={handleCreateNewErrorCode}
/>
</>
);
}
return null;
@@ -434,7 +616,7 @@ const AddBrandDevice = () => {
</Title>
<Steps current={currentStep} style={{ marginBottom: 24 }}>
<Step title="Brand Device Details" />
<Step title="Error Codes" />
<Step title="Error Codes, Solutions & Spareparts" />
</Steps>
<div style={{ marginTop: 24 }}>{renderStepContent()}</div>
<Divider />

View File

@@ -1,15 +1,19 @@
import { useEffect, useState } from 'react';
import { useNavigate, useParams, useLocation } from 'react-router-dom';
import { Divider, Typography, Button, Steps, Form, Row, Col, Card, Spin, Modal } from 'antd';
import { Divider, Typography, Button, Steps, Form, Row, Col, Card, Spin, Modal, ConfigProvider } from 'antd';
import { NotifAlert, NotifOk } from '../../../components/Global/ToastNotif';
import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb';
import { getBrandById, updateBrand } from '../../../api/master-brand';
import { getFileUrl } from '../../../api/file-uploads';
import BrandForm from './component/BrandForm';
import ErrorCodeForm from './component/ErrorCodeForm';
import ErrorCodeTable from './component/ListErrorCode';
import ErrorCodeSimpleForm from './component/ErrorCodeSimpleForm';
import SolutionForm from './component/SolutionForm';
import SparepartForm from './component/SparepartForm';
import ErrorCodeListModal from './component/ErrorCodeListModal';
import FormActions from './component/FormActions';
import { useErrorCodeLogic } from './hooks/errorCode';
import { useSolutionLogic } from './hooks/solution';
import { useSparepartLogic } from './hooks/sparepart';
const { Title } = Typography;
const { Step } = Steps;
@@ -39,21 +43,59 @@ const EditBrandDevice = () => {
const [formData, setFormData] = useState(defaultData);
const [errorCodes, setErrorCodes] = useState([]);
const [errorCodeIcon, setErrorCodeIcon] = useState(null);
const [showErrorCodeModal, setShowErrorCodeModal] = useState(false);
const [sparepartImages, setSparepartImages] = useState({});
const [solutionForm] = Form.useForm();
const [sparepartForm] = Form.useForm();
const {
errorCodeFields,
addErrorCode,
removeErrorCode,
editErrorCode,
} = useErrorCodeLogic(errorCodeForm, fileList);
const {
solutionFields,
solutionTypes,
solutionStatuses,
firstSolutionValid,
solutionsToDelete,
handleAddSolutionField,
handleRemoveSolutionField,
handleSolutionTypeChange,
handleSolutionStatusChange,
resetSolutionFields,
checkFirstSolutionValid,
getSolutionData,
setSolutionsForExistingRecord,
} = useErrorCodeLogic(errorCodeForm, fileList);
} = useSolutionLogic(solutionForm);
const {
sparepartFields,
sparepartTypes,
sparepartStatuses,
handleAddSparepartField,
handleRemoveSparepartField,
handleSparepartTypeChange,
handleSparepartStatusChange,
resetSparepartFields,
getSparepartData,
setSparepartForExistingRecord,
} = 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(() => {
const fetchBrandData = async () => {
@@ -176,27 +218,65 @@ const EditBrandDevice = () => {
const handleFinish = async () => {
setConfirmLoading(true);
try {
// Get current solution and sparepart data from forms
const currentSolutionData = getSolutionData();
const currentSparepartData = getSparepartData();
const finalFormData = {
brand_name: formData.brand_name,
brand_type: formData.brand_type || '',
brand_model: formData.brand_model || '',
brand_manufacture: formData.brand_manufacture,
is_active: formData.is_active,
error_code: errorCodes.map((ec) => ({
error_code: ec.error_code,
error_code_name: ec.error_code_name || '',
error_code_description: ec.error_code_description || '',
error_code_color: ec.error_code_color || '#000000',
path_icon: ec.errorCodeIcon?.uploadPath || ec.path_icon || '',
is_active: ec.status !== undefined ? ec.status : true,
solution: (ec.solution || []).map((sol) => ({
solution_name: sol.solution_name,
type_solution: sol.type_solution,
text_solution: sol.text_solution || '',
path_solution: sol.path_solution || '',
is_active: sol.is_active !== false,
})),
})),
error_code: errorCodes.map((ec) => {
// If editing current error code, get latest data from forms
if (ec.key === editingErrorCodeKey) {
return {
error_code: ec.error_code,
error_code_name: ec.error_code_name || '',
error_code_description: ec.error_code_description || '',
error_code_color: ec.error_code_color || '#000000',
path_icon: ec.errorCodeIcon?.uploadPath || ec.path_icon || '',
is_active: ec.status !== undefined ? ec.status : true,
solution: currentSolutionData.map((sol) => ({
solution_name: sol.solution_name,
type_solution: sol.type_solution,
text_solution: sol.text_solution || '',
path_solution: sol.path_solution || '',
is_active: sol.is_active !== false,
})),
sparepart: currentSparepartData.map((sp) => ({
name: sp.name,
description: sp.description || '',
is_active: sp.is_active !== false,
sparepart_image: sparepartImages[sp.key || sp.id] || null,
})),
};
}
// Return existing data for other error codes
return {
error_code: ec.error_code,
error_code_name: ec.error_code_name || '',
error_code_description: ec.error_code_description || '',
error_code_color: ec.error_code_color || '#000000',
path_icon: ec.errorCodeIcon?.uploadPath || ec.path_icon || '',
is_active: ec.status !== undefined ? ec.status : true,
solution: (ec.solution || []).map((sol) => ({
solution_name: sol.solution_name,
type_solution: sol.type_solution,
text_solution: sol.text_solution || '',
path_solution: sol.path_solution || '',
is_active: sol.is_active !== false,
})),
sparepart: (ec.sparepart || []).map((sp) => ({
name: sp.name,
description: sp.description || '',
is_active: sp.is_active !== false,
sparepart_image: sp.sparepart_image || null,
})),
};
}),
};
const response = await updateBrand(id, finalFormData);
@@ -256,8 +336,23 @@ const EditBrandDevice = () => {
setIsErrorCodeFormReadOnly(false);
setEditingErrorCodeKey(record.key);
// Load solutions to solution form
if (record.solution && record.solution.length > 0) {
setSolutionsForExistingRecord(record.solution, errorCodeForm);
setSolutionsForExistingRecord(record.solution, solutionForm);
}
// Load spareparts to sparepart form
if (record.sparepart && record.sparepart.length > 0) {
setSparepartForExistingRecord(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');
@@ -331,6 +426,12 @@ const EditBrandDevice = () => {
const handleCreateNewErrorCode = () => {
resetErrorCodeForm();
resetSolutionFields();
resetSparepartFields();
setErrorCodeIcon(null);
setSparepartImages({});
setIsErrorCodeFormReadOnly(false);
setEditingErrorCodeKey(null);
};
const handleErrorCodeIconUpload = (iconData) => {
@@ -394,73 +495,142 @@ const EditBrandDevice = () => {
if (currentStep === 1) {
return (
<Row gutter={24}>
<Col span={8}>
<Title level={5} style={{ marginBottom: 16 }}>
{isErrorCodeFormReadOnly
? editingErrorCodeKey
? 'View Error Code'
: 'Error Code Form'
: editingErrorCodeKey
? 'Edit Error Code'
: 'Tambah Error Code'}
</Title>
<Form
form={errorCodeForm}
layout="vertical"
initialValues={{
status: true,
solution_status_0: true,
solution_type_0: 'text',
}}
onValuesChange={checkFirstSolutionValid}
>
<ErrorCodeForm
errorCodeForm={errorCodeForm}
isErrorCodeFormReadOnly={isErrorCodeFormReadOnly}
editingErrorCodeKey={editingErrorCodeKey}
solutionFields={solutionFields}
solutionTypes={solutionTypes}
solutionStatuses={solutionStatuses}
fileList={fileList}
solutionsToDelete={solutionsToDelete}
firstSolutionValid={firstSolutionValid}
onAddErrorCode={handleAddErrorCode}
onAddSolutionField={handleAddSolutionField}
onRemoveSolutionField={handleRemoveSolutionField}
onSolutionTypeChange={handleSolutionTypeChange}
onSolutionStatusChange={handleSolutionStatusChange}
onSolutionFileUpload={handleSolutionFileUpload}
onFileView={handleFileView}
onCreateNewErrorCode={handleCreateNewErrorCode}
onResetForm={resetErrorCodeForm}
errorCodes={errorCodes}
errorCodeIcon={errorCodeIcon}
onErrorCodeIconUpload={handleErrorCodeIconUpload}
onErrorCodeIconRemove={handleErrorCodeIconRemove}
/>
</Form>
</Col>
<Col span={16}>
<ErrorCodeTable
errorCodes={
loading
? Array.from({ length: 3 }, (_, index) => ({
key: `loading-${index}`,
error_code: 'Loading...',
error_code_name: 'Loading...',
solution: [],
}))
: errorCodes
}
loading={loading}
onPreview={handlePreviewErrorCode}
onEdit={handleEditErrorCode}
onDelete={handleDeleteErrorCode}
onFileView={handleFileView}
/>
</Col>
</Row>
<>
<Row gutter={24}>
<Col span={8}>
<Card
title={
<Title level={5} style={{ margin: 0 }}>
{isErrorCodeFormReadOnly
? editingErrorCodeKey
? 'View Error Code'
: 'Error Code Form'
: editingErrorCodeKey
? 'Edit Error Code'
: 'Tambah Error Code'}
</Title>
}
size="small"
>
<Form
form={errorCodeForm}
layout="vertical"
initialValues={{
status: true,
}}
>
<ErrorCodeSimpleForm
errorCodeForm={errorCodeForm}
isErrorCodeFormReadOnly={isErrorCodeFormReadOnly}
errorCodeIcon={errorCodeIcon}
onErrorCodeIconUpload={handleErrorCodeIconUpload}
onErrorCodeIconRemove={handleErrorCodeIconRemove}
onAddErrorCode={handleAddErrorCode}
/>
</Form>
</Card>
</Col>
<Col span={8}>
<Card
title={<Title level={5} style={{ margin: 0 }}>Solutions</Title>}
size="small"
>
<Form
form={solutionForm}
layout="vertical"
initialValues={{
solution_status_0: true,
solution_type_0: 'text',
}}
>
<SolutionForm
solutionForm={solutionForm}
solutionFields={solutionFields}
solutionTypes={solutionTypes}
solutionStatuses={solutionStatuses}
onAddSolutionField={handleAddSolutionField}
onRemoveSolutionField={handleRemoveSolutionField}
onSolutionTypeChange={handleSolutionTypeChange}
onSolutionStatusChange={handleSolutionStatusChange}
isReadOnly={isErrorCodeFormReadOnly}
onFileUpload={handleSolutionFileUpload}
onFileView={handleFileView}
/>
</Form>
</Card>
</Col>
<Col span={8}>
<Card
title={<Title level={5} style={{ margin: 0 }}>Spareparts</Title>}
size="small"
>
<Form
form={sparepartForm}
layout="vertical"
initialValues={{
sparepart_status_0: true,
sparepart_type_0: 'required',
}}
>
<SparepartForm
sparepartForm={sparepartForm}
sparepartFields={sparepartFields}
onAddSparepartField={handleAddSparepartField}
onRemoveSparepartField={handleRemoveSparepartField}
onSparepartTypeChange={handleSparepartTypeChange}
onSparepartStatusChange={handleSparepartStatusChange}
onSparepartImageUpload={handleSparepartImageUpload}
onSparepartImageRemove={handleSparepartImageRemove}
sparepartImages={sparepartImages}
isReadOnly={isErrorCodeFormReadOnly}
/>
</Form>
</Card>
</Col>
</Row>
{/* Error Codes List Button */}
<Row justify="center">
<Col>
<ConfigProvider
theme={{
token: { colorBgContainer: '#23a55ade' },
components: {
Button: {
defaultBg: '#23a55a',
defaultColor: '#FFFFFF',
defaultBorderColor: '#23a55a',
defaultHoverBg: '#209652',
defaultHoverColor: '#FFFFFF',
defaultHoverBorderColor: '#23a55a',
},
},
}}
>
<Button
type="primary"
size="large"
onClick={() => setShowErrorCodeModal(true)}
style={{ minWidth: '200px' }}
>
View All Error Codes ({errorCodes.length})
</Button>
</ConfigProvider>
</Col>
</Row>
{/* Error Codes List Modal */}
<ErrorCodeListModal
visible={showErrorCodeModal}
onClose={() => setShowErrorCodeModal(false)}
errorCodes={errorCodes}
loading={loading}
onPreview={handlePreviewErrorCode}
onEdit={handleEditErrorCode}
onDelete={handleDeleteErrorCode}
onAddNew={handleCreateNewErrorCode}
/>
</>
);
}
return null;

View File

@@ -0,0 +1,212 @@
import React, { useState } from 'react';
import { Modal, Table, Button, Space, message, Tag, ConfigProvider } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { NotifConfirmDialog, NotifOk, NotifAlert } from '../../../../components/Global/ToastNotif';
const ErrorCodeListModal = ({
visible,
onClose,
errorCodes,
loading,
onPreview,
onEdit,
onDelete,
onAddNew,
}) => {
const [confirmLoading, setConfirmLoading] = useState(false);
const columns = [
{
title: 'No',
key: 'no',
width: '5%',
align: 'center',
render: (_, __, index) => index + 1,
},
{
title: 'Error Code',
dataIndex: 'error_code',
key: 'error_code',
width: '15%',
},
{
title: 'Error Name',
dataIndex: 'error_code_name',
key: 'error_code_name',
width: '25%',
render: (text) => text || '-',
},
{
title: 'Description',
dataIndex: 'error_code_description',
key: 'error_code_description',
width: '30%',
render: (text) => text || '-',
ellipsis: true,
},
{
title: 'Solutions',
key: 'solutions',
width: '10%',
align: 'center',
render: (_, record) => {
const solutionCount = record.solution ? record.solution.length : 0;
return <Tag color={solutionCount > 0 ? 'green' : 'red'}>{solutionCount} Sol</Tag>;
},
},
{
title: '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',
dataIndex: 'status',
key: 'status',
width: '10%',
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"
icon={<EyeOutlined />}
onClick={() => onPreview(record)}
style={{
color: '#23A55A',
borderColor: '#23A55A',
}}
size="small"
/>
<Button
type="text"
icon={<EditOutlined />}
onClick={() => onEdit(record)}
style={{
color: '#faad14',
borderColor: '#faad14',
}}
size="small"
/>
<Button
type="text"
danger
icon={<DeleteOutlined />}
onClick={() => handleDelete(record)}
style={{
borderColor: '#ff4d4f',
color: '#ff4d4f',
}}
size="small"
/>
</Space>
),
},
];
const handleDelete = (record) => {
if (errorCodes.length <= 1) {
NotifAlert({
icon: 'warning',
title: 'Perhatian',
message: 'Setiap brand harus memiliki minimal 1 error code!',
});
return;
}
NotifConfirmDialog({
icon: 'question',
title: 'Konfirmasi',
message: `Apakah anda yakin hapus error code "${
record.error_code_name || record.error_code
}" ?`,
onConfirm: () => {
setConfirmLoading(true);
onDelete(record.key);
setConfirmLoading(false);
},
onCancel: () => {},
});
};
return (
<Modal
title={
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<span>Daftar Error Codes</span>
<ConfigProvider
theme={{
token: { colorBgContainer: '#23a55ade' },
components: {
Button: {
defaultBg: '#23a55a',
defaultColor: '#FFFFFF',
defaultBorderColor: '#23a55a',
defaultHoverBg: '#209652',
defaultHoverColor: '#FFFFFF',
defaultHoverBorderColor: '#23a55a',
},
},
}}
>
<Button
type="primary"
icon={<PlusOutlined />}
onClick={onAddNew}
>
Add New Error Code
</Button>
</ConfigProvider>
</div>
}
open={visible}
onCancel={onClose}
closable={false}
maskClosable={false}
width={1200}
footer={[
<Button key="close" onClick={onClose}>
Close
</Button>,
]}
>
<Table
columns={columns}
dataSource={errorCodes}
loading={loading || confirmLoading}
rowKey="key"
pagination={{
pageSize: 10,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} items`,
}}
scroll={{ x: 1000 }}
size="small"
/>
</Modal>
);
};
export default ErrorCodeListModal;

View File

@@ -0,0 +1,233 @@
import {
Form,
Input,
Switch,
Upload,
Button,
Typography,
message,
ConfigProvider,
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { uploadFile } from '../../../../api/file-uploads';
const { Text } = Typography;
const ErrorCodeSimpleForm = ({
errorCodeForm,
isErrorCodeFormReadOnly = false,
errorCodeIcon,
onErrorCodeIconUpload,
onErrorCodeIconRemove,
onAddErrorCode,
}) => {
const statusValue = Form.useWatch('status', errorCodeForm);
const handleIconUpload = async (file) => {
// Check if file is an image
const isImage = file.type.startsWith('image/');
if (!isImage) {
message.error('You can only upload image files!');
return Upload.LIST_IGNORE;
}
// Check file size (max 2MB)
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('Image must be smaller than 2MB!');
return Upload.LIST_IGNORE;
}
try {
const fileExtension = file.name.split('.').pop().toLowerCase();
const isImageFile = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(
fileExtension
);
const fileType = isImageFile ? 'image' : 'pdf';
const folder = 'images';
const uploadResponse = await uploadFile(file, folder);
const iconPath = uploadResponse.data?.path_icon || uploadResponse.data?.path_solution || '';
if (iconPath) {
onErrorCodeIconUpload({
name: file.name,
uploadPath: iconPath,
fileExtension,
isImage: isImageFile,
size: file.size,
});
message.success(`${file.name} uploaded successfully!`);
} else {
message.error(`Failed to upload ${file.name}`);
}
} catch (error) {
console.error('Error uploading icon:', error);
message.error(`Failed to upload ${file.name}`);
}
};
const handleIconRemove = () => {
onErrorCodeIconRemove();
};
return (
<>
{/* Status Switch */}
<Form.Item label="Status" name="status">
<div style={{ display: 'flex', alignItems: 'center' }}>
<Form.Item name="status" valuePropName="checked" noStyle>
<Switch
disabled={isErrorCodeFormReadOnly}
style={{ backgroundColor: statusValue ? '#23A55A' : '#bfbfbf' }}
/>
</Form.Item>
<Text style={{ marginLeft: 8 }}>
{statusValue ? 'Active' : 'Inactive'}
</Text>
</div>
</Form.Item>
{/* Error Code */}
<Form.Item
label="Error Code"
name="error_code"
rules={[{ required: true, message: 'Error code wajib diisi!' }]}
>
<Input
placeholder="Enter error code"
disabled={isErrorCodeFormReadOnly}
/>
</Form.Item>
{/* Error Name */}
<Form.Item
label="Error Name"
name="error_code_name"
rules={[{ required: true, message: 'Error name wajib diisi!' }]}
>
<Input
placeholder="Enter error name"
disabled={isErrorCodeFormReadOnly}
/>
</Form.Item>
{/* Error Description */}
<Form.Item
label="Description"
name="error_code_description"
>
<Input.TextArea
placeholder="Enter error description"
rows={3}
disabled={isErrorCodeFormReadOnly}
/>
</Form.Item>
{/* Color and Icon in same row */}
<Form.Item label="Color & Icon">
<Input.Group compact>
<Form.Item
name="error_code_color"
noStyle
>
<input
type="color"
disabled={isErrorCodeFormReadOnly}
style={{ width: '30%', height: '40px', border: '1px solid #d9d9d9', borderRadius: 4 }}
defaultValue="#000000"
/>
</Form.Item>
<Form.Item noStyle style={{ width: '70%', paddingLeft: 8 }}>
{!isErrorCodeFormReadOnly ? (
<Upload
beforeUpload={handleIconUpload}
showUploadList={false}
accept="image/*"
style={{ width: '100%' }}
>
<Button icon={<UploadOutlined />} style={{ width: '100%' }}>
Upload Icon
</Button>
</Upload>
) : (
<div style={{ padding: '8px 12px', border: '1px solid #d9d9d9', borderRadius: 4 }}>
<Text type="secondary">No upload allowed</Text>
</div>
)}
</Form.Item>
</Input.Group>
{errorCodeIcon && (
<div style={{ marginTop: 8 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<img
src={errorCodeIcon.uploadPath}
alt="Error Code Icon"
style={{
width: 50,
height: 50,
objectFit: 'cover',
border: '1px solid #d9d9d9',
borderRadius: 4,
}}
/>
<div>
<Text style={{ fontSize: 12 }}>{errorCodeIcon.name}</Text>
<br />
<Text type="secondary" style={{ fontSize: 10 }}>
Size: {(errorCodeIcon.size / 1024).toFixed(1)} KB
</Text>
</div>
{!isErrorCodeFormReadOnly && (
<Button
type="text"
danger
size="small"
onClick={handleIconRemove}
>
Remove
</Button>
)}
</div>
</div>
)}
</Form.Item>
{/* Add Error Code Button */}
{!isErrorCodeFormReadOnly && (
<Form.Item>
<ConfigProvider
theme={{
token: { colorBgContainer: '#23a55ade' },
components: {
Button: {
defaultBg: '#23a55a',
defaultColor: '#FFFFFF',
defaultBorderColor: '#23a55a',
defaultHoverBg: '#209652',
defaultHoverColor: '#FFFFFF',
defaultHoverBorderColor: '#23a55a',
},
},
}}
>
<Button
htmlType="button"
onClick={() => {
// Call parent function to add error code
onAddErrorCode();
}}
style={{ width: '100%' }}
>
+ Add Error Code
</Button>
</ConfigProvider>
</Form.Item>
)}
</>
);
};
export default ErrorCodeSimpleForm;

View File

@@ -139,7 +139,10 @@ const SolutionField = ({
icon={<DeleteOutlined />}
onClick={() => onRemove(fieldId)}
disabled={isReadOnly}
style={{ borderColor: '#ff4d4f' }}
style={{
borderColor: '#ff4d4f',
color: '#ff4d4f'
}}
/>
</div>
@@ -161,7 +164,7 @@ const SolutionField = ({
/>
</Form.Item>
<Text style={{ marginLeft: 8 }}>
{(watchedStatus ?? true) ? 'Active' : 'Non Active'}
{(watchedStatus ?? true) ? 'Active' : 'Inactive'}
</Text>
</div>
</Form.Item>

View File

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

View File

@@ -0,0 +1,80 @@
import React from 'react';
import { Form, Card, Typography, Divider, Button } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import SolutionFieldNew from './SolutionFieldNew';
const { Text } = Typography;
const SolutionForm = ({
solutionForm,
solutionFields,
solutionTypes,
solutionStatuses,
fileList,
solutionsToDelete,
firstSolutionValid,
onAddSolutionField,
onRemoveSolutionField,
onSolutionTypeChange,
onSolutionStatusChange,
onSolutionFileUpload,
onFileView,
isReadOnly = false,
onAddSolution
}) => {
return (
<div>
<Form
form={solutionForm}
layout="vertical"
initialValues={{
solution_status_0: true,
solution_type_0: 'text',
}}
>
<Divider orientation="left">Solution Items</Divider>
{solutionFields.map((field, index) => (
<SolutionFieldNew
key={field.key}
fieldKey={field.key}
fieldName={field.name}
index={index}
solutionType={solutionTypes[field.key]}
solutionStatus={solutionStatuses[field.key]}
onTypeChange={onSolutionTypeChange}
onStatusChange={onSolutionStatusChange}
onRemove={() => onRemoveSolutionField(field.key)}
onFileUpload={onSolutionFileUpload}
onFileView={onFileView}
fileList={fileList}
isReadOnly={isReadOnly}
canRemove={solutionFields.length > 1}
/>
))}
{!isReadOnly && (
<>
<Form.Item>
<Button
type="dashed"
onClick={onAddSolutionField}
icon={<PlusOutlined />}
style={{ width: '100%' }}
>
+ Add Solution
</Button>
</Form.Item>
<div style={{ marginTop: 16 }}>
<Text type="secondary">
* At least one solution is required for each error code.
</Text>
</div>
</>
)}
</Form>
</div>
);
};
export default SolutionForm;

View File

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

View File

@@ -0,0 +1,166 @@
import { useState } from 'react';
export const useSolutionLogic = (solutionForm) => {
const [solutionFields, setSolutionFields] = useState([
{ name: ['solution_items', 0], key: 0 }
]);
const [solutionTypes, setSolutionTypes] = useState({ 0: 'text' });
const [solutionStatuses, setSolutionStatuses] = useState({ 0: true });
const [solutionsToDelete, setSolutionsToDelete] = useState([]);
const handleAddSolutionField = () => {
const newKey = Date.now(); // Use timestamp for unique key
const newField = { name: ['solution_items', newKey], key: newKey };
setSolutionFields(prev => [...prev, newField]);
setSolutionTypes(prev => ({ ...prev, [newKey]: 'text' }));
setSolutionStatuses(prev => ({ ...prev, [newKey]: true }));
// Set default values for the new field
setTimeout(() => {
solutionForm.setFieldValue(['solution_items', newKey, 'name'], '');
solutionForm.setFieldValue(['solution_items', newKey, 'type'], 'text');
solutionForm.setFieldValue(['solution_items', newKey, 'text'], '');
}, 0);
};
const handleRemoveSolutionField = (key) => {
if (solutionFields.length <= 1) {
return; // Keep at least one solution field
}
setSolutionFields(prev => prev.filter(field => field.key !== key));
// Clean up type and status
const newTypes = { ...solutionTypes };
const newStatuses = { ...solutionStatuses };
delete newTypes[key];
delete newStatuses[key];
setSolutionTypes(newTypes);
setSolutionStatuses(newStatuses);
};
const handleSolutionTypeChange = (key, value) => {
setSolutionTypes(prev => ({ ...prev, [key]: value }));
};
const handleSolutionStatusChange = (key, value) => {
setSolutionStatuses(prev => ({ ...prev, [key]: value }));
};
const resetSolutionFields = () => {
setSolutionFields([{ name: ['solution_items', 0], key: 0 }]);
setSolutionTypes({ 0: 'text' });
setSolutionStatuses({ 0: true });
// Reset form values
solutionForm.resetFields();
solutionForm.setFieldsValue({
solution_status_0: true,
solution_type_0: 'text',
});
};
const checkFirstSolutionValid = () => {
const values = solutionForm.getFieldsValue();
const firstSolution = values.solution_items?.[0];
if (!firstSolution || !firstSolution.name || firstSolution.name.trim() === '') {
return false;
}
if (solutionTypes[0] === 'text' && (!firstSolution.text || firstSolution.text.trim() === '')) {
return false;
}
return true;
};
const getSolutionData = () => {
const values = solutionForm.getFieldsValue();
const result = solutionFields.map(field => {
const key = field.key;
// Access form values using the key from field.name (AntD stores with comma)
const solutionPath = field.name.join(',');
const solution = values[solutionPath];
const validSolution = solution && solution.name && solution.name.trim() !== '';
if (validSolution) {
return {
solution_name: solution.name || 'Default Solution',
type_solution: solutionTypes[key] || 'text',
text_solution: solution.text || '',
path_solution: solution.file || '',
is_active: solution.status !== false, // Use form value directly
};
}
return null;
}).filter(Boolean);
return result;
};
const setSolutionsForExistingRecord = (solutions, form) => {
if (!solutions || solutions.length === 0) return;
const newFields = solutions.map((solution, index) => ({
name: ['solution_items', solution.id || index],
key: solution.id || index
}));
setSolutionFields(newFields);
// Set solution values
const solutionsValues = {};
const newTypes = {};
const newStatuses = {};
solutions.forEach((solution, index) => {
const key = solution.id || index;
solutionsValues[key] = {
name: solution.solution_name || '',
type: solution.type_solution || 'text',
text: solution.text_solution || '',
file: solution.path_solution || '',
};
newTypes[key] = solution.type_solution || 'text';
newStatuses[key] = solution.is_active !== false;
});
// Set all form values at once
const formValues = {};
Object.keys(solutionsValues).forEach(key => {
const solution = solutionsValues[key];
formValues[`solution_items,${key}`] = {
name: solution.name,
type: solution.type,
text: solution.text,
file: solution.file,
status: solution.is_active !== false
};
});
form.setFieldsValue(formValues);
setSolutionTypes(newTypes);
setSolutionStatuses(newStatuses);
};
return {
solutionFields,
solutionTypes,
solutionStatuses,
solutionsToDelete,
firstSolutionValid: checkFirstSolutionValid(),
handleAddSolutionField,
handleRemoveSolutionField,
handleSolutionTypeChange,
handleSolutionStatusChange,
resetSolutionFields,
checkFirstSolutionValid,
getSolutionData,
setSolutionsForExistingRecord,
};
};

View File

@@ -0,0 +1,115 @@
import { useState } from 'react';
export const useSparepartLogic = (sparepartForm) => {
const [sparepartFields, setSparepartFields] = useState([
{ name: ['sparepart_items', 0], key: 0 }
]);
const [sparepartTypes, setSparepartTypes] = useState({ 0: 'required' });
const [sparepartStatuses, setSparepartStatuses] = useState({ 0: true });
const handleAddSparepartField = () => {
const newKey = Date.now(); // Use timestamp for unique key
const newField = { name: ['sparepart_items', newKey], key: newKey };
setSparepartFields(prev => [...prev, newField]);
setSparepartTypes(prev => ({ ...prev, [newKey]: 'required' }));
setSparepartStatuses(prev => ({ ...prev, [newKey]: true }));
// Set default values for the new field
setTimeout(() => {
sparepartForm.setFieldValue(['sparepart_items', newKey, 'type'], 'required');
sparepartForm.setFieldValue(['sparepart_items', newKey, 'quantity'], 1);
}, 0);
};
const handleRemoveSparepartField = (key) => {
if (sparepartFields.length <= 1) {
return; // Keep at least one sparepart field
}
setSparepartFields(prev => prev.filter(field => field.key !== key));
// Clean up type and status
const newTypes = { ...sparepartTypes };
const newStatuses = { ...sparepartStatuses };
delete newTypes[key];
delete newStatuses[key];
setSparepartTypes(newTypes);
setSparepartStatuses(newStatuses);
};
const handleSparepartTypeChange = (key, value) => {
setSparepartTypes(prev => ({ ...prev, [key]: value }));
};
const handleSparepartStatusChange = (key, value) => {
setSparepartStatuses(prev => ({ ...prev, [key]: value }));
};
const resetSparepartFields = () => {
setSparepartFields([{ name: ['sparepart_items', 0], key: 0 }]);
setSparepartTypes({ 0: 'required' });
setSparepartStatuses({ 0: true });
// Reset form values
sparepartForm.resetFields();
sparepartForm.setFieldsValue({
sparepart_status_0: true,
sparepart_type_0: 'required',
});
};
const getSparepartData = () => {
const values = sparepartForm.getFieldsValue();
return sparepartFields.map(field => {
const key = field.key;
const sparepartPath = field.name.join(',');
const sparepart = values[sparepartPath];
return sparepart && sparepart.name && sparepart.name.trim() !== '' ? {
name: sparepart.name || '',
description: sparepart.description || '',
is_active: sparepart.status !== false,
} : null;
}).filter(Boolean);
};
const setSparepartForExistingRecord = (spareparts, form) => {
if (!spareparts || spareparts.length === 0) return;
const newFields = spareparts.map((sparepart, index) => ({
name: ['sparepart_items', sparepart.id || index],
key: sparepart.id || index
}));
setSparepartFields(newFields);
// Set sparepart values
const formValues = {};
Object.keys(spareparts).forEach(index => {
const key = spareparts[index].id || index;
const sparepart = spareparts[index];
formValues[`sparepart_items,${key}`] = {
name: sparepart.name || '',
description: sparepart.description || '',
status: sparepart.is_active !== false,
};
});
form.setFieldsValue(formValues);
};
return {
sparepartFields,
sparepartTypes,
sparepartStatuses,
handleAddSparepartField,
handleRemoveSparepartField,
handleSparepartTypeChange,
handleSparepartStatusChange,
resetSparepartFields,
getSparepartData,
setSparepartForExistingRecord,
};
};

View File

@@ -1,79 +1,60 @@
import React, { memo, useState, useEffect } from 'react';
import { Button, Row, Col, Card, Badge } from 'antd';
import { Button, Row, Col, Card, Badge, Input, Typography, Space } from 'antd';
import {
CloseCircleFilled,
WarningFilled,
CheckCircleFilled,
InfoCircleFilled,
ClockCircleOutlined,
EnvironmentOutlined,
LinkOutlined,
SendOutlined,
MailOutlined,
UserOutlined,
FileTextOutlined,
HistoryOutlined,
EyeOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
const { Text, Paragraph, Link } = Typography;
// Dummy data untuk notifikasi
const initialNotifications = [
{
id: 1,
type: 'critical',
title: 'Compressor Unit A - Overheat detected (85°C)',
plc: 'PLC-001',
tag: 'A1-TEMP',
engineer: 'Siti Nurhaliza',
time: '2 menit lalu',
status: 'unread',
title: 'Compressor Unit A',
issue: 'Overheat detected (85°C)',
description: '⚠️ Compressor Unit A - Overheat Detected (85°C) 🚨',
timestamp: '04-11-2025 11.39 WIB',
location: 'Lantai 2, Area Produksi A, Zona 3',
details: 'Terjadi kenaikan suhu melebihi ambang batas pada Compressor Unit A. Pengecekan potensi kerusakan dibutuhkan.',
link: 'https://tinyurl.com/compA85',
isRead: false,
},
{
id: 2,
type: 'warning',
title: 'Compressor Unit C - Pressure slightly high (7.2 bar)',
plc: 'PLC-003',
tag: 'C3-PRESS',
engineer: 'Joko Widodo',
time: '15 menit lalu',
status: 'unread',
title: 'Compressor Unit C',
issue: 'Pressure slightly high (7.2 bar)',
description: '🔧 Compressor Unit C - Pressure High (7.2 bar)',
timestamp: '04-11-2025 11.30 WIB',
location: 'Lantai 1, Area Produksi C, Zona 1',
details: 'Tekanan mendekati ambang batas atas. Perlu monitoring lebih lanjut oleh engineer.',
link: 'https://tinyurl.com/compC72',
isRead: false,
},
{
id: 3,
type: 'resolved',
title: 'Compressor Unit B - Vibration issue resolved',
plc: 'PLC-002',
tag: 'B2-VIB',
engineer: 'Rudi Santoso',
time: '1 jam lalu',
status: 'read',
isRead: true,
},
{
id: 4,
type: 'critical',
title: 'Compressor Unit E - Low oil pressure (1.5 bar)',
plc: 'PLC-005',
tag: 'E1-OIL',
engineer: 'Ahmad Yani',
time: '2 jam lalu',
status: 'unread',
isRead: false,
},
{
id: 5,
type: 'warning',
title: 'Compressor Unit D - Temperature rising (78°C)',
plc: 'PLC-004',
tag: 'D2-TEMP',
engineer: 'Budi Santoso',
time: '3 jam lalu',
status: 'read',
isRead: true,
},
{
id: 6,
type: 'resolved',
title: 'Compressor Unit F - Maintenance completed',
plc: 'PLC-006',
tag: 'F1-MAIN',
engineer: 'Dewi Lestari',
time: '5 jam lalu',
status: 'read',
title: 'Compressor Unit B',
issue: 'Vibration issue resolved',
description: '✅ Compressor Unit B - Vibration Resolved',
timestamp: '04-11-2025 10.05 WIB',
location: 'Lantai 2, Area Produksi B, Zona 2',
details: 'Getaran pada Unit B telah kembali normal setelah perbaikan.',
link: 'https://tinyurl.com/compBresolved',
isRead: true,
},
];
@@ -81,6 +62,7 @@ const initialNotifications = [
const ListNotification = memo(function ListNotification(props) {
const [notifications, setNotifications] = useState(initialNotifications);
const [activeTab, setActiveTab] = useState('all');
const [searchTerm, setSearchTerm] = useState('');
const navigate = useNavigate();
useEffect(() => {
@@ -119,29 +101,29 @@ const ListNotification = memo(function ListNotification(props) {
}
};
const filterNotifications = (status) => {
if (status === 'all') return notifications;
if (status === 'unread') return notifications.filter((n) => !n.isRead);
if (status === 'read') return notifications.filter((n) => n.isRead);
return notifications;
const handleMarkAsRead = (id) => {
setNotifications((prev) =>
prev.map((n) => (n.id === id ? { ...n, isRead: true } : n))
);
};
const filteredNotifications = notifications
.filter((n) => {
if (activeTab === 'all') return true;
if (activeTab === 'unread') return !n.isRead;
if (activeTab === 'read') return n.isRead;
return true;
})
.filter((n) => {
if (!searchTerm) return true;
const searchableText = `${n.title} ${n.issue} ${n.description} ${n.location} ${n.details}`.toLowerCase();
return searchableText.includes(searchTerm.toLowerCase());
});
const getUnreadCount = () => {
return notifications.filter((n) => !n.isRead).length;
};
const handleViewDetail = (notification) => {
props.setSelectedData(notification);
props.setActionMode('preview');
// Mark as read
setNotifications((prev) =>
prev.map((n) => (n.id === notification.id ? { ...n, isRead: true, status: 'read' } : n))
);
};
const filteredNotifications = filterNotifications(activeTab);
const tabButtonStyle = (isActive) => ({
padding: '12px 16px',
border: 'none',
@@ -170,10 +152,21 @@ const ListNotification = memo(function ListNotification(props) {
>
Notification
</h2>
<p style={{ margin: '0 0 24px 0', color: '#8c8c8c', fontSize: '14px' }}>
<p style={{ margin: '0 0 16px 0', color: '#8c8c8c', fontSize: '14px' }}>
Riwayat notifikasi yang dikirim ke engineer
</p>
<Row>
<Col span={6}>
<Input.Search
placeholder="Search notifications..."
onSearch={(value) => setSearchTerm(value)}
onChange={(e) => setSearchTerm(e.target.value)}
style={{ marginBottom: '24px', width: 300 }}
/>
</Col>
</Row>
{/* Tabs */}
<div style={{ borderBottom: '1px solid #f0f0f0', marginBottom: '24px' }}>
<div style={{ display: 'flex', gap: '8px' }}>
@@ -212,7 +205,7 @@ const ListNotification = memo(function ListNotification(props) {
</div>
{/* Notification List */}
<div>
<Space direction="vertical" size="middle" style={{ display: 'flex' }}>
{filteredNotifications.length === 0 ? (
<div
style={{
@@ -230,165 +223,96 @@ const ListNotification = memo(function ListNotification(props) {
);
return (
<div
<Card
key={notification.id}
style={{
marginBottom: '12px',
backgroundColor: '#ffffff',
border: '1px solid #f0f0f0',
borderRadius: '8px',
padding: '16px',
position: 'relative',
transition: 'all 0.3s',
cursor: 'pointer',
}}
onMouseEnter={(e) => {
e.currentTarget.style.boxShadow =
'0 2px 8px rgba(0,0,0,0.06)';
e.currentTarget.style.backgroundColor = '#f6f9ff';
e.currentTarget.style.borderColor = '#d6e4ff';
}}
onMouseLeave={(e) => {
e.currentTarget.style.boxShadow = 'none';
e.currentTarget.style.backgroundColor = '#ffffff';
e.currentTarget.style.borderColor = '#f0f0f0';
backgroundColor: notification.isRead ? '#ffffff' : '#f6f9ff',
borderColor: notification.isRead ? '#f0f0f0' : '#d6e4ff',
}}
onClick={() => handleMarkAsRead(notification.id)}
>
{/* Dot for unread */}
{!notification.isRead && (
<div
style={{
position: 'absolute',
top: '16px',
right: '16px',
width: '8px',
height: '8px',
borderRadius: '50%',
backgroundColor: '#ff4d4f',
}}
/>
)}
<div
style={{
display: 'flex',
gap: '16px',
alignItems: 'flex-start',
}}
>
<div style={{ display: 'flex', gap: '16px', alignItems: 'flex-start' }}>
{/* Icon */}
<div
style={{
width: '48px',
height: '48px',
width: '40px',
height: '40px',
borderRadius: '50%',
backgroundColor: bgColor,
color: color,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: '24px',
fontSize: '22px',
flexShrink: 0,
}}
>
<IconComponent style={{ fontSize: '24px' }} />
<IconComponent style={{ fontSize: '22px' }} />
</div>
{/* Content */}
<div style={{ flex: 1 }}>
<div
style={{
fontSize: '15px',
fontWeight: 600,
marginBottom: '4px',
color: '#262626',
}}
>
{notification.title}
</div>
<Row align="top">
{/* Left: Title and Issue */}
<Col flex="220px">
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
<div>
<Text strong>{notification.title}</Text>
<div style={{ marginTop: '4px' }}>
<Text style={{ color }}>{notification.issue}</Text>
</div>
</div>
{!notification.isRead && (
<Badge color="red" status="processing" style={{ marginLeft: '8px', marginTop: '4px' }} />
)}
</div>
</Col>
<div
style={{
display: 'flex',
gap: '8px',
marginBottom: '4px',
flexWrap: 'wrap',
}}
>
<span
style={{
fontSize: '13px',
color: '#8c8c8c',
}}
>
{notification.plc}
</span>
<span
style={{
fontSize: '13px',
color: '#d9d9d9',
}}
>
</span>
<span
style={{
fontSize: '13px',
color: '#8c8c8c',
}}
>
Tag: {notification.tag}
</span>
</div>
{/* Middle: Description and Details */}
<Col flex="auto">
<div style={{ display: 'flex', gap: '8px', alignItems: 'flex-start', marginBottom: '12px' }}>
<MailOutlined style={{ marginTop: '4px', color: '#1890ff' }} />
<Paragraph style={{ color: '#595959', margin: 0, flex: 1 }}>
<Text strong>{notification.description}</Text>
<br />
{notification.details}
</Paragraph>
</div>
<Space direction="vertical" size={4} style={{ fontSize: '13px', color: '#8c8c8c' }}>
<Space>
<ClockCircleOutlined />
<Text type="secondary">{notification.timestamp}</Text>
</Space>
<Space>
<EnvironmentOutlined />
<Text type="secondary">{notification.location}</Text>
</Space>
<Space>
<LinkOutlined />
<Link href={notification.link} target="_blank">{notification.link}</Link>
<Button type="link" icon={<SendOutlined />} style={{ paddingLeft: '8px' }}>
Resend
</Button>
</Space>
</Space>
</Col>
<div
style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
flexWrap: 'wrap',
}}
>
<span
style={{
fontSize: '13px',
color: '#8c8c8c',
}}
>
Engineer:{' '}
<span style={{ color: '#595959' }}>
{notification.engineer}
</span>
</span>
<span
style={{
fontSize: '13px',
color: '#8c8c8c',
}}
>
{notification.time}
</span>
</div>
{/* Right: Action Icons */}
<Col flex="120px" style={{ textAlign: 'center' }} align="bottom">
<Space style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
<Button type="text" icon={<UserOutlined style={{ color: '#1890ff' }} />} title="User History" style={{ border: '1px solid #1890ff', borderRadius: '4px' }} />
<Button type="text" icon={<EyeOutlined style={{ color: '#1890ff' }} />} title="Details" style={{ border: '1px solid #1890ff', borderRadius: '4px' }} />
<Button type="text" icon={<HistoryOutlined style={{ color: '#1890ff' }} />} title="Log History" style={{ border: '1px solid #1890ff', borderRadius: '4px' }} />
</Space>
</Col>
</Row>
</div>
{/* Button */}
<Button
type="link"
onClick={() => handleViewDetail(notification)}
style={{
color: '#FF6B35',
fontSize: '14px',
fontWeight: 500,
}}
>
View Detail
</Button>
</div>
</div>
</Card>
);
})
)}
</div>
</Space>
</Col>
</Row>
</Card>
@@ -397,5 +321,3 @@ const ListNotification = memo(function ListNotification(props) {
});
export default ListNotification;