Compare commits

..

34 Commits

Author SHA1 Message Date
58d1f5c7ab Merge pull request 'Repair and replace svg' (#28) from lavoce into main
Reviewed-on: #28
2025-12-22 09:38:05 +00:00
c10a5bf62d Merge pull request 'lavoce' (#27) from lavoce into main
Reviewed-on: #27
2025-12-22 09:28:34 +00:00
6cc5042956 Merge pull request 'repair' (#26) from lavoce into main
Reviewed-on: #26
2025-11-28 07:17:06 +00:00
5079f8d316 Merge pull request 'lavoce' (#25) from lavoce into main
Reviewed-on: #25
2025-11-28 07:12:41 +00:00
7073390de7 Merge pull request 'lavoce' (#24) from lavoce into main
Reviewed-on: #24
2025-11-28 05:50:36 +00:00
4226a24e79 Merge pull request 'lavoce' (#23) from lavoce into main
Reviewed-on: #23
2025-11-28 05:10:26 +00:00
038009433f Merge pull request 'lavoce' (#22) from lavoce into main
Reviewed-on: #22
2025-11-25 03:50:54 +00:00
64ba51b17c Merge pull request 'lavoce' (#21) from lavoce into main
Reviewed-on: #21
2025-11-20 03:44:05 +00:00
47d0638a42 Merge pull request 'lavoce' (#20) from lavoce into main
Reviewed-on: #20
2025-11-19 01:05:19 +00:00
d8c5f3ed44 Merge pull request 'lavoce' (#19) from lavoce into main
Reviewed-on: #19
2025-11-18 00:26:36 +00:00
affd9146bb Merge pull request 'lavoce' (#18) from lavoce into main
Reviewed-on: #18
2025-11-17 08:27:39 +00:00
4022b3f8f4 Merge pull request 'lavoce' (#17) from lavoce into main
Reviewed-on: #17
2025-11-10 07:57:17 +00:00
446a4e2b95 Merge pull request 'lavoce' (#16) from lavoce into main
Reviewed-on: #16
2025-11-10 06:33:35 +00:00
83a475c708 Merge pull request 'Repair beautiful apps' (#15) from lavoce into main
Reviewed-on: #15
2025-11-04 10:01:47 +00:00
ab1c510a77 Merge pull request 'Repair bg-signin' (#14) from lavoce into main
Reviewed-on: #14
2025-11-04 08:48:59 +00:00
59859c6d18 Update public/web.config 2025-11-04 07:03:57 +00:00
2bd27937dc Update public/web.config 2025-11-04 07:02:55 +00:00
1058c660d6 Update public/web.config 2025-11-04 07:01:10 +00:00
35b2167791 Update public/web.config 2025-11-04 06:53:05 +00:00
ec676983d0 Update .gitignore 2025-11-04 06:51:39 +00:00
c07c5f8235 Update .gitignore 2025-11-04 06:47:31 +00:00
b32ad97034 Merge pull request 'Add side bar menus mobile mode' (#13) from lavoce into main
Reviewed-on: #13
2025-11-04 06:42:09 +00:00
76244f6f6e Merge pull request 'lavoce' (#12) from lavoce into main
Reviewed-on: #12
2025-11-04 06:23:15 +00:00
0a128cbb3c Merge pull request 'lavoce' (#11) from lavoce into main
Reviewed-on: #11
2025-10-28 09:47:36 +00:00
bd4ab26680 Merge pull request 'lavoce' (#10) from lavoce into main
Reviewed-on: #10
2025-10-28 04:48:54 +00:00
3e728a1ff5 Merge pull request 'lavoce' (#9) from lavoce into main
Reviewed-on: #9
2025-10-27 03:48:58 +00:00
9db143972e Merge pull request 'lavoce' (#8) from lavoce into main
Reviewed-on: #8
2025-10-25 09:19:36 +00:00
029ea269a7 Merge pull request 'lavoce' (#7) from lavoce into main
Reviewed-on: #7
2025-10-24 05:43:32 +00:00
4cdaa042da Merge pull request 'lavoce' (#6) from lavoce into main
Reviewed-on: #6
2025-10-23 07:28:11 +00:00
56af2a16c0 Merge pull request 'update file svg to src assets' (#5) from lavoce into main
Reviewed-on: #5
2025-10-23 04:52:13 +00:00
deadf2ffb4 Merge pull request 'lavoce' (#4) from lavoce into main
Reviewed-on: #4
2025-10-23 04:27:57 +00:00
4da80c7089 Merge pull request 'lavoce' (#3) from lavoce into main
Reviewed-on: #3
2025-10-22 05:59:57 +00:00
56e3ce78a6 Merge pull request 'lavoce' (#2) from lavoce into main
Reviewed-on: #2
2025-10-20 04:06:02 +00:00
7c2a019dd2 Merge pull request 'lavoce' (#1) from lavoce into main
Reviewed-on: #1
2025-09-17 08:39:35 +00:00
36 changed files with 1809 additions and 1871 deletions

1
.gitignore vendored
View File

@@ -6,6 +6,7 @@ yarn-debug.log*
yarn-error.log* yarn-error.log*
pnpm-debug.log* pnpm-debug.log*
lerna-debug.log* lerna-debug.log*
*.config
node_modules node_modules
dist dist

View File

@@ -3,7 +3,7 @@
<system.webServer> <system.webServer>
<rewrite> <rewrite>
<rules> <rules>
<rule name="reactViteSypiu"> <rule name="CallOfDuty">
<match url=".*" /> <match url=".*" />
<conditions logicalGrouping="MatchAll"> <conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />

View File

@@ -53,7 +53,6 @@ import IndexHistoryEvent from './pages/history/event/IndexHistoryEvent';
// Image Viewer // Image Viewer
import ImageViewer from './Utils/ImageViewer'; import ImageViewer from './Utils/ImageViewer';
import RedirectWa from './pages/blank/RedirectWa';
const App = () => { const App = () => {
return ( return (
@@ -73,8 +72,6 @@ const App = () => {
element={<IndexVerificationSparepart />} element={<IndexVerificationSparepart />}
/> />
<Route path="/redirect" element={<RedirectWa />} />
{/* Protected Routes */} {/* Protected Routes */}
<Route path="/dashboard" element={<ProtectedRoute />}> <Route path="/dashboard" element={<ProtectedRoute />}>
<Route path="home" element={<Home />} /> <Route path="home" element={<Home />} />

View File

@@ -46,60 +46,10 @@ const getNotificationLogByNotificationId = async (notificationId) => {
return response.data; return response.data;
}; };
// update is_read status
const updateIsRead = async (notificationId) => {
const response = await SendRequest({
method: 'put',
prefix: `notification/${notificationId}`,
});
return response.data;
};
// Resend notification to specific user
const resendNotificationToUser = async (notificationId, userId) => {
const response = await SendRequest({
method: 'post',
prefix: `notification/${notificationId}/resend/${userId}`,
});
return response.data;
};
// Resend Chat by User
const resendChatByUser = async (notificationId, userPhone) => {
const response = await SendRequest({
method: 'post',
prefix: `notification-user/resend/${notificationId}/${userPhone}`,
});
return response.data;
};
// Resend Chat All User
const resendChatAllUser = async (notificationId) => {
const response = await SendRequest({
method: 'post',
prefix: `notification/resend/${notificationId}`,
});
return response.data;
};
// Searching
const searchData = async (queryParams) => {
const response = await SendRequest({
method: 'get',
prefix: `notification?criteria=${queryParams}`,
});
return response.data;
};
export { export {
getAllNotification, getAllNotification,
getNotificationById, getNotificationById,
getNotificationDetail, getNotificationDetail,
createNotificationLog, createNotificationLog,
getNotificationLogByNotificationId, getNotificationLogByNotificationId
updateIsRead,
resendNotificationToUser,
resendChatByUser,
resendChatAllUser,
searchData,
}; };

View File

@@ -30,18 +30,18 @@ instance.interceptors.response.use(
originalRequest._retry = true; originalRequest._retry = true;
try { try {
// console.log('🔄 Refresh token dipanggil...'); console.log('🔄 Refresh token dipanggil...');
const refreshRes = await refreshApi.post('/auth/refresh-token'); const refreshRes = await refreshApi.post('/auth/refresh-token');
const newAccessToken = refreshRes.data.data.accessToken; const newAccessToken = refreshRes.data.data.accessToken;
localStorage.setItem('token', newAccessToken); localStorage.setItem('token', newAccessToken);
// console.log('✅ Token refreshed successfully'); console.log('✅ Token refreshed successfully');
// update token di header // update token di header
instance.defaults.headers.common['Authorization'] = `Bearer ${newAccessToken}`; instance.defaults.headers.common['Authorization'] = `Bearer ${newAccessToken}`;
originalRequest.headers['Authorization'] = `Bearer ${newAccessToken}`; originalRequest.headers['Authorization'] = `Bearer ${newAccessToken}`;
// console.log('🔁 Retrying original request...'); console.log('🔁 Retrying original request...');
return instance(originalRequest); return instance(originalRequest);
} catch (refreshError) { } catch (refreshError) {
console.error( console.error(
@@ -70,35 +70,24 @@ async function ApiRequest({ method = 'GET', params = {}, prefix = '/', token = t
}, },
}; };
const tokenRedirect = sessionStorage.getItem('token_redirect'); const rawToken = localStorage.getItem('token');
let rawToken = '';
if (tokenRedirect !== null) {
rawToken = tokenRedirect;
// console.log(`sessionStorage: ${tokenRedirect}`);
} else {
rawToken = localStorage.getItem('token');
// console.log(`localStorage: ${rawToken}`);
}
if (token && rawToken) { if (token && rawToken) {
const cleanToken = rawToken.replace(/"/g, ''); const cleanToken = rawToken.replace(/"/g, '');
request.headers['Authorization'] = `Bearer ${cleanToken}`; request.headers['Authorization'] = `Bearer ${cleanToken}`;
// console.log('🔐 Sending request with token:', cleanToken.substring(0, 20) + '...'); console.log('🔐 Sending request with token:', cleanToken.substring(0, 20) + '...');
} else { } else {
console.warn('⚠️ No token found in localStorage'); console.warn('⚠️ No token found in localStorage');
} }
// console.log('📤 API Request:', { method, url: prefix, hasToken: !!rawToken }); console.log('📤 API Request:', { method, url: prefix, hasToken: !!rawToken });
try { try {
const response = await instance(request); const response = await instance(request);
// console.log('✅ API Response:', { console.log('✅ API Response:', {
// url: prefix, url: prefix,
// status: response.status, status: response.status,
// statusCode: response.data?.statusCode, statusCode: response.data?.statusCode,
// }); });
return { ...response, error: false }; return { ...response, error: false };
} catch (error) { } catch (error) {
const status = error?.response?.status || 500; const status = error?.response?.status || 500;
@@ -143,10 +132,17 @@ async function cekError(status, message = '') {
const SendRequest = async (queryParams) => { const SendRequest = async (queryParams) => {
try { try {
const response = await ApiRequest(queryParams); const response = await ApiRequest(queryParams);
console.log('📦 SendRequest response:', {
hasError: response.error,
status: response.status,
statusCode: response.data?.statusCode,
data: response.data,
});
// If ApiRequest returned error flag, return error structure // If ApiRequest returned error flag, return error structure
if (response.error) { if (response.error) {
const errorMsg = response.data?.message || response.statusText || 'Request failed'; const errorMsg = response.data?.message || response.statusText || 'Request failed';
console.error('❌ SendRequest error response:', errorMsg);
// Return consistent error structure instead of empty array // Return consistent error structure instead of empty array
return { return {

View File

@@ -2,16 +2,7 @@
import mqtt from 'mqtt'; import mqtt from 'mqtt';
const mqttUrl = `${import.meta.env.VITE_MQTT_SERVER ?? 'ws://localhost:1884'}`; const mqttUrl = `${import.meta.env.VITE_MQTT_SERVER ?? 'ws://localhost:1884'}`;
const topics = [ const topics = ['cod/air_dryer/air_dryer1'];
'PIU_COD/AIR_DRYER/OVERVIEW',
'PIU_COD/AIR_DRYER/AIR_DRYER_A',
'PIU_COD/AIR_DRYER/AIR_DRYER_B',
'PIU_COD/AIR_DRYER/AIR_DRYER_C',
'PIU_COD/COMPRESSOR/OVERVIEW',
'PIU_COD/COMPRESSOR/COMPRESSOR_A',
'PIU_COD/COMPRESSOR/COMPRESSOR_B',
'PIU_COD/COMPRESSOR/COMPRESSOR_C'
];
const options = { const options = {
keepalive: 30, keepalive: 30,
clientId: 'react_mqtt_' + Math.random().toString(16).substr(2, 8), clientId: 'react_mqtt_' + Math.random().toString(16).substr(2, 8),

View File

@@ -146,7 +146,7 @@ const allItems = [
{ {
key: 'master-sparepart', key: 'master-sparepart',
icon: <ToolOutlined style={{ fontSize: '19px' }} />, icon: <ToolOutlined style={{ fontSize: '19px' }} />,
label: <Link to="/master/sparepart">Sparepart</Link>, label: <Link to="/master/sparepart">sparepart</Link>,
}, },
// { // {
// key: 'master-shift', // key: 'master-shift',

View File

@@ -1,49 +0,0 @@
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { verifyRedirect } from '../../api/auth';
import { encryptData } from '../../components/Global/Formatter';
import NotFound from './NotFound';
import Waiting from './Waiting';
import NotificationDetailTab from '../notificationDetail/IndexNotificationDetail';
export default function RedirectWa() {
const [idData, setIdData] = useState(0);
const [ready, setReady] = useState(0);
const location = useLocation();
// URLSearchParams untuk ambil query
const queryParams = new URLSearchParams(location.search);
const token = queryParams.get('token');
const handleInitForm = async (encodedToken) => {
const originalToken = decodeURIComponent(encodedToken);
// console.log(originalToken);
const response = await verifyRedirect({
tokenRedirect: originalToken,
});
console.log('tes', response);
const tokenResult = JSON.stringify(response.data?.data?.accessToken);
sessionStorage.setItem('token_redirect', tokenResult);
response.data.auth = true;
sessionStorage.setItem('session', encryptData(response?.data));
setIdData(response.data.data.idData);
setReady(1);
};
useEffect(() => {
handleInitForm(token);
}, [idData]);
if (ready == 0) return <Waiting />;
if (idData === 0) return <NotFound />;
return <NotificationDetailTab id={idData} />;
}

View File

@@ -267,6 +267,9 @@ const ListContact = memo(function ListContact(props) {
} }
} }
// Backend doesn't support is_active filter or order parameter
// Contact hanya supports: criteria, name, code, limit, page
const queryParams = new URLSearchParams(); const queryParams = new URLSearchParams();
Object.entries(searchParams).forEach(([key, value]) => { Object.entries(searchParams).forEach(([key, value]) => {
if (value !== '' && value !== null && value !== undefined) { if (value !== '' && value !== null && value !== undefined) {
@@ -306,10 +309,11 @@ const ListContact = memo(function ListContact(props) {
// Listen for saved contact data // Listen for saved contact data
useEffect(() => { useEffect(() => {
if (props.lastSavedContact) { if (props.lastSavedContact) {
fetchContacts(); fetchContacts(); // Refetch all contacts when data is saved
} }
}, [props.lastSavedContact]); }, [props.lastSavedContact]);
// Get contacts (already filtered by backend)
const getFilteredContacts = () => { const getFilteredContacts = () => {
return filteredContacts; return filteredContacts;
}; };
@@ -322,7 +326,7 @@ const ListContact = memo(function ListContact(props) {
const showAddModal = () => { const showAddModal = () => {
props.setSelectedData(null); props.setSelectedData(null);
props.setActionMode('add'); props.setActionMode('add');
// Pass the current active tab to determine contact type
props.setContactType?.(activeTab); props.setContactType?.(activeTab);
}; };

View File

@@ -8,7 +8,7 @@ import filePathSvg from '../../assets/svg/air_dryer_A_rev.svg';
const { Text } = Typography; const { Text } = Typography;
// const filePathSvg = '/src/assets/svg/air_dryer_A_rev.svg'; // const filePathSvg = '/src/assets/svg/air_dryer_A_rev.svg';
const topicMqtt = 'PIU_COD/AIR_DRYER/AIR_DRYER_A'; const topicMqtt = 'PIU_GGCP/Devices/PB';
const SvgAirDryerA = () => { const SvgAirDryerA = () => {
return ( return (

View File

@@ -8,7 +8,7 @@ import filePathSvg from '../../assets/svg/air_dryer_B_rev.svg';
const { Text } = Typography; const { Text } = Typography;
// const filePathSvg = '/src/assets/svg/air_dryer_B_rev.svg'; // const filePathSvg = '/src/assets/svg/air_dryer_B_rev.svg';
const topicMqtt = 'PIU_COD/AIR_DRYER/AIR_DRYER_B'; const topicMqtt = 'PIU_GGCP/Devices/PB';
const SvgAirDryerB = () => { const SvgAirDryerB = () => {
return ( return (

View File

@@ -8,7 +8,7 @@ import filePathSvg from '../../assets/svg/air_dryer_C_rev.svg';
const { Text } = Typography; const { Text } = Typography;
// const filePathSvg = '/src/assets/svg/air_dryer_C_rev.svg'; // const filePathSvg = '/src/assets/svg/air_dryer_C_rev.svg';
const topicMqtt = 'PIU_COD/AIR_DRYER/AIR_DRYER_C'; const topicMqtt = 'PIU_GGCP/Devices/PB';
const SvgAirDryerC = () => { const SvgAirDryerC = () => {
return ( return (

View File

@@ -8,7 +8,7 @@ import filePathSvg from '../../assets/svg/compressorA_rev.svg';
const { Text } = Typography; const { Text } = Typography;
// const filePathSvg = '/src/assets/svg/test-new.svg'; // const filePathSvg = '/src/assets/svg/test-new.svg';
const topicMqtt = 'PIU_COD/COMPRESSOR/COMPRESSOR_A'; const topicMqtt = 'PIU_GGCP/Devices/PB';
const SvgCompressorA = () => { const SvgCompressorA = () => {
return ( return (

View File

@@ -6,7 +6,7 @@ import SvgViewer from './SvgViewer';
import filePathSvg from '../../assets/svg/compressorB_rev.svg'; import filePathSvg from '../../assets/svg/compressorB_rev.svg';
const { Text } = Typography; const { Text } = Typography;
const topicMqtt = 'PIU_COD/COMPRESSOR/COMPRESSOR_B'; const topicMqtt = 'cod/air_dryer/air_dryer1';
const SvgCompressorB = () => { const SvgCompressorB = () => {
return ( return (

View File

@@ -8,7 +8,7 @@ import filePathSvg from '../../assets/svg/compressorC_rev.svg';
const { Text } = Typography; const { Text } = Typography;
// const filePathSvg = '/src/assets/svg/test-new.svg'; // const filePathSvg = '/src/assets/svg/test-new.svg';
const topicMqtt = 'PIU_COD/COMPRESSOR/COMPRESSOR_C'; const topicMqtt = 'PIU_GGCP/Devices/PB';
const SvgCompressorC = () => { const SvgCompressorC = () => {
return ( return (

View File

@@ -8,7 +8,7 @@ import filePathSvg from '../../assets/svg/overview-airdryer.svg';
const { Text } = Typography; const { Text } = Typography;
// const filePathSvg = '/src/assets/svg/test-new.svg'; // const filePathSvg = '/src/assets/svg/test-new.svg';
const topicMqtt = 'PIU_COD/AIR_DRYER/OVERVIEW'; const topicMqtt = 'PIU_GGCP/Devices/PB';
const SvgOverviewAirDryer = () => { const SvgOverviewAirDryer = () => {
return ( return (

View File

@@ -8,7 +8,7 @@ import filePathSvg from '../../assets/svg/overview-compressor.svg';
const { Text } = Typography; const { Text } = Typography;
// const filePathSvg = '/src/assets/svg/test-new.svg'; // const filePathSvg = '/src/assets/svg/test-new.svg';
const topicMqtt = 'PIU_COD/COMPRESSOR/OVERVIEW'; const topicMqtt = 'PIU_GGCP/Devices/PB';
const SvgOverviewCompressor = () => { const SvgOverviewCompressor = () => {
return ( return (

View File

@@ -352,7 +352,7 @@ const ListJadwalShift = memo(function ListJadwalShift(props) {
<Title level={3}>Jadwal Shift</Title> <Title level={3}>Jadwal Shift</Title>
<Divider /> <Divider />
{/* <Row> <Row>
<Col xs={24}> <Col xs={24}>
<Row justify="end" align="middle" gutter={[8, 8]}> <Row justify="end" align="middle" gutter={[8, 8]}>
<Col xs={24} sm={24} md={12} lg={12}> <Col xs={24} sm={24} md={12} lg={12}>
@@ -383,7 +383,7 @@ const ListJadwalShift = memo(function ListJadwalShift(props) {
</Col> </Col>
</Row> </Row>
</Col> </Col>
</Row> */} </Row>
<div style={{ marginTop: '24px' }}> <div style={{ marginTop: '24px' }}>
{loading ? ( {loading ? (

View File

@@ -13,18 +13,13 @@ import {
Space, Space,
ConfigProvider, ConfigProvider,
} from 'antd'; } from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'; import {
EditOutlined,
DeleteOutlined
} from '@ant-design/icons';
import { NotifAlert, NotifOk, NotifConfirmDialog } from '../../../components/Global/ToastNotif'; import { NotifAlert, NotifOk, NotifConfirmDialog } from '../../../components/Global/ToastNotif';
import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb'; import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb';
import { import { getBrandById, createBrand, createErrorCode, getErrorCodesByBrandId, updateErrorCode, deleteErrorCode, deleteBrand } from '../../../api/master-brand';
getBrandById,
createBrand,
createErrorCode,
getErrorCodesByBrandId,
updateErrorCode,
deleteErrorCode,
deleteBrand,
} from '../../../api/master-brand';
import BrandForm from './component/BrandForm'; import BrandForm from './component/BrandForm';
import ErrorCodeForm from './component/ErrorCodeForm'; import ErrorCodeForm from './component/ErrorCodeForm';
import SolutionForm from './component/SolutionForm'; import SolutionForm from './component/SolutionForm';
@@ -47,9 +42,7 @@ const AddBrandDevice = () => {
const [selectedSparepartIds, setSelectedSparepartIds] = useState([]); const [selectedSparepartIds, setSelectedSparepartIds] = useState([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const tab = searchParams.get('tab'); const tab = searchParams.get('tab');
const [currentStep, setCurrentStep] = useState( const [currentStep, setCurrentStep] = useState(tab === 'error-codes' ? 1 : (location.state?.phase || 0));
tab === 'error-codes' ? 1 : location.state?.phase || 0
);
const [editingErrorCodeKey, setEditingErrorCodeKey] = useState(null); const [editingErrorCodeKey, setEditingErrorCodeKey] = useState(null);
const [isErrorCodeFormReadOnly, setIsErrorCodeFormReadOnly] = useState(false); const [isErrorCodeFormReadOnly, setIsErrorCodeFormReadOnly] = useState(false);
const [searchText, setSearchText] = useState(''); const [searchText, setSearchText] = useState('');
@@ -75,7 +68,7 @@ const AddBrandDevice = () => {
const values = solutionForm.getFieldsValue(true); const values = solutionForm.getFieldsValue(true);
const solutions = []; const solutions = [];
solutionFields.forEach((fieldKey) => { solutionFields.forEach(fieldKey => {
let solution = null; let solution = null;
if (values.solution_items && values.solution_items[fieldKey]) { if (values.solution_items && values.solution_items[fieldKey]) {
@@ -92,16 +85,9 @@ const AddBrandDevice = () => {
if (solutionType === 'text') { if (solutionType === 'text') {
isValid = solution.text && solution.text.trim() !== ''; isValid = solution.text && solution.text.trim() !== '';
} else if (solutionType === 'file') { } else if (solutionType === 'file') {
const hasPathSolution = const hasPathSolution = solution.path_solution && solution.path_solution.trim() !== '';
solution.path_solution && solution.path_solution.trim() !== ''; const hasFileUpload = (solution.fileUpload && typeof solution.fileUpload === 'object' && Object.keys(solution.fileUpload).length > 0);
const hasFileUpload = const hasFile = (solution.file && typeof solution.file === 'object' && Object.keys(solution.file).length > 0);
solution.fileUpload &&
typeof solution.fileUpload === 'object' &&
Object.keys(solution.fileUpload).length > 0;
const hasFile =
solution.file &&
typeof solution.file === 'object' &&
Object.keys(solution.file).length > 0;
isValid = hasPathSolution || hasFileUpload || hasFile; isValid = hasPathSolution || hasFileUpload || hasFile;
} }
@@ -132,9 +118,9 @@ const AddBrandDevice = () => {
text: '', text: '',
status: true, status: true,
file: null, file: null,
fileUpload: null, fileUpload: null
}, }
}, }
}); });
}, 100); }, 100);
} }
@@ -142,6 +128,7 @@ const AddBrandDevice = () => {
}; };
const setSolutionsForExistingRecord = (solutions, targetForm) => { const setSolutionsForExistingRecord = (solutions, targetForm) => {
if (!targetForm || !solutions || solutions.length === 0) { if (!targetForm || !solutions || solutions.length === 0) {
return; return;
} }
@@ -166,14 +153,11 @@ const AddBrandDevice = () => {
fileObject = { fileObject = {
uploadPath: solution.path_solution || solution.path_document, uploadPath: solution.path_solution || solution.path_document,
path_solution: solution.path_solution || solution.path_document, path_solution: solution.path_solution || solution.path_document,
name: name: solution.file_upload_name || (solution.path_solution || solution.path_document).split('/').pop() || 'File',
solution.file_upload_name ||
(solution.path_solution || solution.path_document).split('/').pop() ||
'File',
type_solution: solution.type_solution, type_solution: solution.type_solution,
isExisting: true, isExisting: true,
size: 0, size: 0,
url: solution.path_solution || solution.path_document, url: solution.path_solution || solution.path_document
}; };
} }
@@ -186,7 +170,7 @@ const AddBrandDevice = () => {
file: fileObject, file: fileObject,
fileUpload: fileObject, fileUpload: fileObject,
path_solution: solution.path_solution || solution.path_document || null, path_solution: solution.path_solution || solution.path_document || null,
fileName: solution.file_upload_name || null, fileName: solution.file_upload_name || null
}; };
}); });
@@ -196,35 +180,28 @@ const AddBrandDevice = () => {
setSolutionStatuses(newSolutionStatuses); setSolutionStatuses(newSolutionStatuses);
targetForm.resetFields(); targetForm.resetFields();
setTimeout(() => { setTimeout(() => {
targetForm.setFieldsValue({ targetForm.setFieldsValue({
solution_items: solutionItems, solution_items: solutionItems
}); });
setTimeout(() => { setTimeout(() => {
Object.keys(solutionItems).forEach((key) => { Object.keys(solutionItems).forEach(key => {
const solution = solutionItems[key]; const solution = solutionItems[key];
targetForm.setFieldValue(['solution_items', key, 'name'], solution.name); targetForm.setFieldValue(['solution_items', key, 'name'], solution.name);
targetForm.setFieldValue(['solution_items', key, 'type'], solution.type); targetForm.setFieldValue(['solution_items', key, 'type'], solution.type);
targetForm.setFieldValue(['solution_items', key, 'text'], solution.text); targetForm.setFieldValue(['solution_items', key, 'text'], solution.text);
targetForm.setFieldValue(['solution_items', key, 'file'], solution.file); targetForm.setFieldValue(['solution_items', key, 'file'], solution.file);
targetForm.setFieldValue( targetForm.setFieldValue(['solution_items', key, 'fileUpload'], solution.fileUpload);
['solution_items', key, 'fileUpload'],
solution.fileUpload
);
targetForm.setFieldValue(['solution_items', key, 'status'], solution.status); targetForm.setFieldValue(['solution_items', key, 'status'], solution.status);
targetForm.setFieldValue( targetForm.setFieldValue(['solution_items', key, 'path_solution'], solution.path_solution);
['solution_items', key, 'path_solution'], targetForm.setFieldValue(['solution_items', key, 'fileName'], solution.fileName);
solution.path_solution
);
targetForm.setFieldValue(
['solution_items', key, 'fileName'],
solution.fileName
);
}); });
const finalValues = targetForm.getFieldsValue(); const finalValues = targetForm.getFieldsValue();
}, 100); }, 100);
}, 100); }, 100);
@@ -232,14 +209,14 @@ const AddBrandDevice = () => {
const handleAddSolutionField = () => { const handleAddSolutionField = () => {
const newKey = Math.max(...solutionFields, 0) + 1; const newKey = Math.max(...solutionFields, 0) + 1;
setSolutionFields((prev) => [...prev, newKey]); setSolutionFields(prev => [...prev, newKey]);
setSolutionTypes((prev) => ({ ...prev, [newKey]: 'text' })); setSolutionTypes(prev => ({ ...prev, [newKey]: 'text' }));
setSolutionStatuses((prev) => ({ ...prev, [newKey]: true })); setSolutionStatuses(prev => ({ ...prev, [newKey]: true }));
}; };
const handleRemoveSolutionField = (fieldKey) => { const handleRemoveSolutionField = (fieldKey) => {
if (solutionFields.length > 1) { if (solutionFields.length > 1) {
setSolutionFields((prev) => prev.filter((key) => key !== fieldKey)); setSolutionFields(prev => prev.filter(key => key !== fieldKey));
const newTypes = { ...solutionTypes }; const newTypes = { ...solutionTypes };
const newStatuses = { ...solutionStatuses }; const newStatuses = { ...solutionStatuses };
delete newTypes[fieldKey]; delete newTypes[fieldKey];
@@ -256,7 +233,7 @@ const AddBrandDevice = () => {
}; };
const handleSolutionTypeChange = (fieldKey, type) => { const handleSolutionTypeChange = (fieldKey, type) => {
setSolutionTypes((prev) => ({ ...prev, [fieldKey]: type })); setSolutionTypes(prev => ({ ...prev, [fieldKey]: type }));
if (type === 'file') { if (type === 'file') {
solutionForm.setFieldValue(['solution_items', fieldKey, 'text'], ''); solutionForm.setFieldValue(['solution_items', fieldKey, 'text'], '');
@@ -269,7 +246,7 @@ const AddBrandDevice = () => {
}; };
const handleSolutionStatusChange = (fieldKey, status) => { const handleSolutionStatusChange = (fieldKey, status) => {
setSolutionStatuses((prev) => ({ ...prev, [fieldKey]: status })); setSolutionStatuses(prev => ({ ...prev, [fieldKey]: status }));
}; };
const handleNextStep = async () => { const handleNextStep = async () => {
@@ -282,7 +259,7 @@ const AddBrandDevice = () => {
brand_type: brandValues.brand_type || '', brand_type: brandValues.brand_type || '',
brand_manufacture: brandValues.brand_manufacture || '', brand_manufacture: brandValues.brand_manufacture || '',
brand_model: brandValues.brand_model || '', brand_model: brandValues.brand_model || '',
is_active: brandValues.is_active !== undefined ? brandValues.is_active : true, is_active: brandValues.is_active !== undefined ? brandValues.is_active : true
}; };
const response = await createBrand(brandApiData); const response = await createBrand(brandApiData);
@@ -291,7 +268,7 @@ const AddBrandDevice = () => {
const newBrandInfo = { const newBrandInfo = {
...brandValues, ...brandValues,
brand_id: response.data.brand_id, brand_id: response.data.brand_id,
brand_code: response.data.brand_code, brand_code: response.data.brand_code
}; };
setBrandInfo(newBrandInfo); setBrandInfo(newBrandInfo);
setTemporaryBrandId(response.data.brand_id); setTemporaryBrandId(response.data.brand_id);
@@ -330,7 +307,8 @@ const AddBrandDevice = () => {
if (isTemporaryBrand && temporaryBrandId) { if (isTemporaryBrand && temporaryBrandId) {
try { try {
await deleteBrand(temporaryBrandId); await deleteBrand(temporaryBrandId);
} catch (error) {} } catch (error) {
}
} }
navigate('/master/brand-device'); navigate('/master/brand-device');
}; };
@@ -382,6 +360,8 @@ const AddBrandDevice = () => {
setTrigerFilter((prev) => !prev); setTrigerFilter((prev) => !prev);
}; };
const resetErrorCodeForm = () => { const resetErrorCodeForm = () => {
errorCodeForm.resetFields(); errorCodeForm.resetFields();
errorCodeForm.setFieldsValue({ errorCodeForm.setFieldsValue({
@@ -411,16 +391,16 @@ const AddBrandDevice = () => {
return; return;
} }
// if (!solutionData || solutionData.length === 0) { if (!solutionData || solutionData.length === 0) {
// NotifAlert({ NotifAlert({
// icon: 'warning', icon: 'warning',
// title: 'Perhatian', title: 'Perhatian',
// message: 'Setiap error code harus memiliki minimal 1 solution!', message: 'Setiap error code harus memiliki minimal 1 solution!',
// }); });
// return; return;
// } }
const formattedSolutions = solutionData.map((solution) => { const formattedSolutions = solutionData.map(solution => {
const solutionType = solution.type || 'text'; const solutionType = solution.type || 'text';
let typeSolution = solutionType === 'text' ? 'text' : 'image'; let typeSolution = solutionType === 'text' ? 'text' : 'image';
@@ -442,11 +422,7 @@ const AddBrandDevice = () => {
} else { } else {
formattedSolution.text_solution = ''; formattedSolution.text_solution = '';
formattedSolution.path_solution = formattedSolution.path_solution = solution.path_solution || solution.file?.uploadPath || solution.fileUpload?.uploadPath || '';
solution.path_solution ||
solution.file?.uploadPath ||
solution.fileUpload?.uploadPath ||
'';
} }
if (formattedSolution.brand_code_solution_id) { if (formattedSolution.brand_code_solution_id) {
@@ -464,7 +440,7 @@ const AddBrandDevice = () => {
path_icon: errorCodeIcon?.uploadPath || '', path_icon: errorCodeIcon?.uploadPath || '',
is_active: errorCodeValues.status === undefined ? true : errorCodeValues.status, is_active: errorCodeValues.status === undefined ? true : errorCodeValues.status,
solution: formattedSolutions, solution: formattedSolutions,
spareparts: selectedSparepartIds || [], spareparts: selectedSparepartIds || []
}; };
let response; let response;
@@ -480,13 +456,11 @@ const AddBrandDevice = () => {
NotifOk({ NotifOk({
icon: 'success', icon: 'success',
title: 'Berhasil', title: 'Berhasil',
message: editingErrorCodeKey message: editingErrorCodeKey ? 'Error code berhasil diupdate!' : 'Error code berhasil ditambahkan!',
? 'Error code berhasil diupdate!'
: 'Error code berhasil ditambahkan!',
}); });
resetErrorCodeForm(); resetErrorCodeForm();
setTrigerFilter((prev) => !prev); setTrigerFilter(prev => !prev);
} else { } else {
NotifAlert({ NotifAlert({
icon: 'error', icon: 'error',
@@ -505,10 +479,12 @@ const AddBrandDevice = () => {
} }
}; };
const handleErrorCodeIconRemove = () => { const handleErrorCodeIconRemove = () => {
setErrorCodeIcon(null); setErrorCodeIcon(null);
}; };
const handleFinish = async () => { const handleFinish = async () => {
setConfirmLoading(true); setConfirmLoading(true);
try { try {
@@ -530,10 +506,10 @@ const AddBrandDevice = () => {
const response = await getErrorCodesByBrandId(brandInfo.brand_id, queryParams); const response = await getErrorCodesByBrandId(brandInfo.brand_id, queryParams);
if (response && response.statusCode === 200 && response.data) { if (response && response.statusCode === 200 && response.data) {
const freshErrorCodes = response.data.map((ec) => ({ const freshErrorCodes = response.data.map(ec => ({
...ec, ...ec,
tempId: `existing_${ec.error_code_id}`, tempId: `existing_${ec.error_code_id}`,
status: 'existing', status: 'existing'
})); }));
setApiErrorCodes(freshErrorCodes); setApiErrorCodes(freshErrorCodes);
@@ -541,8 +517,7 @@ const AddBrandDevice = () => {
NotifAlert({ NotifAlert({
icon: 'warning', icon: 'warning',
title: 'Perhatian', title: 'Perhatian',
message: message: 'Harap tambahkan minimal 1 error code sebelum menyelesaikan.',
'Harap tambahkan minimal 1 error code sebelum menyelesaikan.',
}); });
return; return;
} }
@@ -551,8 +526,7 @@ const AddBrandDevice = () => {
NotifAlert({ NotifAlert({
icon: 'warning', icon: 'warning',
title: 'Perhatian', title: 'Perhatian',
message: message: 'Harap tambahkan minimal 1 error code sebelum menyelesaikan.',
'Harap tambahkan minimal 1 error code sebelum menyelesaikan.',
}); });
return; return;
} }
@@ -617,7 +591,11 @@ const AddBrandDevice = () => {
<Spin size="large" /> <Spin size="large" />
</div> </div>
)} )}
<BrandForm form={brandForm} isEdit={false} brandInfo={brandInfo} /> <BrandForm
form={brandForm}
isEdit={false}
brandInfo={brandInfo}
/>
</div> </div>
); );
} }
@@ -657,39 +635,31 @@ const AddBrandDevice = () => {
</Col> </Col>
<Col xs={24} md={16} lg={16}> <Col xs={24} md={16} lg={16}>
<div <div style={{
style={{ paddingLeft: '12px'
paddingLeft: '12px', }}>
}}
>
<Card <Card
title={ title={
<div <div style={{
style={{
display: 'flex', display: 'flex',
alignItems: 'center', alignItems: 'center',
justifyContent: 'space-between', justifyContent: 'space-between',
width: '100%', width: '100%'
}} }}>
> <span style={{
<span
style={{
fontSize: '16px', fontSize: '16px',
fontWeight: '600', fontWeight: '600',
color: '#262626', color: '#262626',
display: 'flex', display: 'flex',
alignItems: 'center', alignItems: 'center',
gap: '8px', gap: '8px'
}} }}>
> <span style={{
<span
style={{
width: '4px', width: '4px',
height: '20px', height: '20px',
backgroundColor: '#23A55A', backgroundColor: '#23A55A',
borderRadius: '2px', borderRadius: '2px'
}} }}></span>
></span>
Error Code Form Error Code Form
</span> </span>
<Button <Button
@@ -705,51 +675,43 @@ const AddBrandDevice = () => {
padding: '0 24px', padding: '0 24px',
fontWeight: '500', fontWeight: '500',
boxShadow: '0 2px 4px rgba(35, 165, 90, 0.2)', boxShadow: '0 2px 4px rgba(35, 165, 90, 0.2)',
transition: 'all 0.3s ease', transition: 'all 0.3s ease'
}} }}
onMouseEnter={(e) => { onMouseEnter={(e) => {
e.target.style.boxShadow = e.target.style.boxShadow = '0 4px 8px rgba(35, 165, 90, 0.3)';
'0 4px 8px rgba(35, 165, 90, 0.3)';
}} }}
onMouseLeave={(e) => { onMouseLeave={(e) => {
e.target.style.boxShadow = e.target.style.boxShadow = '0 2px 4px rgba(35, 165, 90, 0.2)';
'0 2px 4px rgba(35, 165, 90, 0.2)';
}} }}
> >
{editingErrorCodeKey {editingErrorCodeKey ? 'Update Error Code' : 'Save Error Code'}
? 'Update Error Code'
: 'Save Error Code'}
</Button> </Button>
</div> </div>
} }
style={{ style={{
width: '100%', width: '100%',
boxShadow: '0 2px 8px rgba(0,0,0,0.06)', boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
borderRadius: '12px', borderRadius: '12px'
}} }}
styles={{ styles={{
body: { padding: '16px 24px 12px 24px' }, body: { padding: '16px 24px 12px 24px' },
header: { header: {
padding: '16px 24px', padding: '16px 24px',
borderBottom: '1px solid #f0f0f0', borderBottom: '1px solid #f0f0f0',
backgroundColor: '#fafafa', backgroundColor: '#fafafa'
}, }
}} }}
> >
<div <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
style={{ display: 'flex', flexDirection: 'column', gap: '8px' }} <div style={{
>
<div
style={{
padding: '16px', padding: '16px',
border: '1px solid #f0f0f0', border: '1px solid #f0f0f0',
borderRadius: '10px', borderRadius: '10px',
backgroundColor: '#ffffff', backgroundColor: '#ffffff',
marginBottom: '0', marginBottom: '0',
transition: 'all 0.3s ease', transition: 'all 0.3s ease',
boxShadow: '0 1px 3px rgba(0,0,0,0.04)', boxShadow: '0 1px 3px rgba(0,0,0,0.04)'
}} }}>
>
<ErrorCodeForm <ErrorCodeForm
errorCodeForm={errorCodeForm} errorCodeForm={errorCodeForm}
isErrorCodeFormReadOnly={isErrorCodeFormReadOnly} isErrorCodeFormReadOnly={isErrorCodeFormReadOnly}
@@ -762,42 +724,29 @@ const AddBrandDevice = () => {
<Row gutter={[20, 0]} style={{ marginTop: '0' }}> <Row gutter={[20, 0]} style={{ marginTop: '0' }}>
<Col xs={24} md={12} lg={12}> <Col xs={24} md={12} lg={12}>
<div <div style={{
style={{
padding: '16px', padding: '16px',
border: '1px solid #f0f0f0', border: '1px solid #f0f0f0',
borderRadius: '10px', borderRadius: '10px',
backgroundColor: '#ffffff', backgroundColor: '#ffffff',
transition: 'all 0.3s ease', transition: 'all 0.3s ease',
boxShadow: '0 1px 3px rgba(0,0,0,0.04)', boxShadow: '0 1px 3px rgba(0,0,0,0.04)'
}} }}>
> <div style={{
<div
style={{
display: 'flex', display: 'flex',
alignItems: 'center', alignItems: 'center',
gap: '8px', gap: '8px',
marginBottom: '12px', marginBottom: '12px',
paddingBottom: '8px', paddingBottom: '8px',
borderBottom: '1px solid #f5f5f5', borderBottom: '1px solid #f5f5f5'
}} }}>
> <div style={{
<div
style={{
width: '3px', width: '3px',
height: '16px', height: '16px',
backgroundColor: '#1890ff', backgroundColor: '#1890ff',
borderRadius: '2px', borderRadius: '2px'
}} }}></div>
></div> <h4 style={{ margin: 0, color: '#262626', fontSize: '14px', fontWeight: '600' }}>
<h4
style={{
margin: 0,
color: '#262626',
fontSize: '14px',
fontWeight: '600',
}}
>
Solution Solution
</h4> </h4>
</div> </div>
@@ -807,23 +756,14 @@ const AddBrandDevice = () => {
solutionTypes={solutionTypes} solutionTypes={solutionTypes}
solutionStatuses={solutionStatuses} solutionStatuses={solutionStatuses}
onAddSolutionField={handleAddSolutionField} onAddSolutionField={handleAddSolutionField}
onRemoveSolutionField={ onRemoveSolutionField={handleRemoveSolutionField}
handleRemoveSolutionField
}
onSolutionTypeChange={handleSolutionTypeChange} onSolutionTypeChange={handleSolutionTypeChange}
onSolutionStatusChange={ onSolutionStatusChange={handleSolutionStatusChange}
handleSolutionStatusChange onSolutionFileUpload={(fileData) => {
} }}
onSolutionFileUpload={(fileData) => {}}
onFileView={(fileData) => { onFileView={(fileData) => {
if ( if (fileData && (fileData.url || fileData.uploadPath)) {
fileData && window.open(fileData.url || fileData.uploadPath, '_blank');
(fileData.url || fileData.uploadPath)
) {
window.open(
fileData.url || fileData.uploadPath,
'_blank'
);
} }
}} }}
isReadOnly={false} isReadOnly={false}
@@ -832,55 +772,40 @@ const AddBrandDevice = () => {
</div> </div>
</Col> </Col>
<Col xs={24} md={12} lg={12}> <Col xs={24} md={12} lg={12}>
<div <div style={{
style={{
padding: '16px', padding: '16px',
border: '1px solid #f0f0f0', border: '1px solid #f0f0f0',
borderRadius: '10px', borderRadius: '10px',
backgroundColor: '#ffffff', backgroundColor: '#ffffff',
transition: 'all 0.3s ease', transition: 'all 0.3s ease',
boxShadow: '0 1px 3px rgba(0,0,0,0.04)', boxShadow: '0 1px 3px rgba(0,0,0,0.04)'
}} }}>
> <div style={{
<div
style={{
display: 'flex', display: 'flex',
alignItems: 'center', alignItems: 'center',
gap: '8px', gap: '8px',
marginBottom: '12px', marginBottom: '12px',
paddingBottom: '8px', paddingBottom: '8px',
borderBottom: '1px solid #f5f5f5', borderBottom: '1px solid #f5f5f5'
}} }}>
> <div style={{
<div
style={{
width: '3px', width: '3px',
height: '16px', height: '16px',
backgroundColor: '#faad14', backgroundColor: '#faad14',
borderRadius: '2px', borderRadius: '2px'
}} }}></div>
></div> <h4 style={{ margin: 0, color: '#262626', fontSize: '14px', fontWeight: '600' }}>
<h4
style={{
margin: 0,
color: '#262626',
fontSize: '14px',
fontWeight: '600',
}}
>
Sparepart Selection Sparepart Selection
</h4> </h4>
</div> </div>
<div <div style={{
style={{
maxHeight: '45vh', maxHeight: '45vh',
overflow: 'auto', overflow: 'auto',
border: '1px solid #e8e8e8', border: '1px solid #e8e8e8',
borderRadius: '8px', borderRadius: '8px',
padding: '12px', padding: '12px',
backgroundColor: '#fafafa', backgroundColor: '#fafafa'
}} }}>
>
<SparepartSelect <SparepartSelect
selectedSparepartIds={selectedSparepartIds} selectedSparepartIds={selectedSparepartIds}
onSparepartChange={setSelectedSparepartIds} onSparepartChange={setSelectedSparepartIds}
@@ -891,16 +816,15 @@ const AddBrandDevice = () => {
</Col> </Col>
</Row> </Row>
<div <div style={{
style={{
display: 'flex', display: 'flex',
justifyContent: 'space-between', justifyContent: 'space-between',
alignItems: 'center', alignItems: 'center',
padding: '16px 0 0 0', padding: '16px 0 0 0',
borderTop: '1px solid #f0f0f0', borderTop: '1px solid #f0f0f0',
marginTop: '12px', marginTop: '12px'
}} }}>
>
{editingErrorCodeKey && ( {editingErrorCodeKey && (
<Button <Button
size="large" size="large"
@@ -913,7 +837,7 @@ const AddBrandDevice = () => {
height: '40px', height: '40px',
padding: '0 24px', padding: '0 24px',
fontWeight: '500', fontWeight: '500',
transition: 'all 0.3s ease', transition: 'all 0.3s ease'
}} }}
onMouseEnter={(e) => { onMouseEnter={(e) => {
e.target.style.borderColor = '#ff4d4f'; e.target.style.borderColor = '#ff4d4f';
@@ -947,7 +871,7 @@ const AddBrandDevice = () => {
setBreadcrumbItems([ setBreadcrumbItems([
{ {
title: <span style={{ fontSize: '14px', fontWeight: 'bold' }}> Master</span>, title: <span style={{ fontSize: '14px', fontWeight: 'bold' }}> Master</span>
}, },
{ {
title: ( title: (
@@ -971,11 +895,12 @@ const AddBrandDevice = () => {
if (location.state?.fromFileViewer && location.state.phase !== undefined) { if (location.state?.fromFileViewer && location.state.phase !== undefined) {
setCurrentStep(location.state.phase); setCurrentStep(location.state.phase);
} }
}, [setBreadcrumbItems, navigate, searchParams, location.state]); }, [setBreadcrumbItems, navigate, searchParams, location.state]);
useEffect(() => { useEffect(() => {
if (brandInfo.brand_id && currentStep === 1) { if (brandInfo.brand_id && currentStep === 1) {
setTrigerFilter((prev) => !prev); setTrigerFilter(prev => !prev);
} }
}, [brandInfo.brand_id, currentStep]); }, [brandInfo.brand_id, currentStep]);
@@ -988,7 +913,8 @@ const AddBrandDevice = () => {
const errorCodes = response.data || []; const errorCodes = response.data || [];
setApiErrorCodes(errorCodes); setApiErrorCodes(errorCodes);
} }
} catch (error) {} } catch (error) {
}
} }
}; };
fetchErrorCodes(); fetchErrorCodes();
@@ -999,7 +925,8 @@ const AddBrandDevice = () => {
if (isTemporaryBrand && temporaryBrandId && currentStep === 0) { if (isTemporaryBrand && temporaryBrandId && currentStep === 0) {
try { try {
await deleteBrand(temporaryBrandId); await deleteBrand(temporaryBrandId);
} catch (error) {} } catch (error) {
}
} }
}; };
@@ -1010,6 +937,7 @@ const AddBrandDevice = () => {
}; };
}, [isTemporaryBrand, temporaryBrandId, currentStep]); }, [isTemporaryBrand, temporaryBrandId, currentStep]);
return ( return (
<ConfigProvider <ConfigProvider
theme={{ theme={{
@@ -1060,9 +988,14 @@ const AddBrandDevice = () => {
<Divider /> <Divider />
<div style={{ display: 'flex', justifyContent: 'space-between' }}> <div style={{ display: 'flex', justifyContent: 'space-between' }}>
<div> <div>
<Button onClick={handleCancel}>Cancel</Button> <Button onClick={handleCancel}>
Cancel
</Button>
{currentStep === 1 && ( {currentStep === 1 && (
<Button onClick={handlePrevStep} style={{ marginLeft: 8 }}> <Button
onClick={handlePrevStep}
style={{ marginLeft: 8 }}
>
Kembali ke Brand Info Kembali ke Brand Info
</Button> </Button>
)} )}

View File

@@ -479,14 +479,14 @@ const EditBrandDevice = () => {
return; return;
} }
// if (!solutionData || solutionData.length === 0) { if (!solutionData || solutionData.length === 0) {
// NotifAlert({ NotifAlert({
// icon: 'warning', icon: 'warning',
// title: 'Perhatian', title: 'Perhatian',
// message: 'Setiap error code harus memiliki minimal 1 solution!', message: 'Setiap error code harus memiliki minimal 1 solution!',
// }); });
// return; return;
// } }
const formattedSolutions = solutionData.map(solution => { const formattedSolutions = solutionData.map(solution => {
const solutionType = solution.type || 'text'; const solutionType = solution.type || 'text';

View File

@@ -214,6 +214,7 @@ const ListErrorCode = ({
marginBottom: 12, marginBottom: 12,
height: '32px', height: '32px',
width: '100%', width: '100%',
maxWidth: '300px'
}} }}
/> />

View File

@@ -36,7 +36,7 @@ const SparepartSelect = ({
setLoading(true); setLoading(true);
try { try {
const params = new URLSearchParams(); const params = new URLSearchParams();
params.set('limit', '10'); params.set('limit', '1000');
if (searchQuery && searchQuery.trim() !== '') { if (searchQuery && searchQuery.trim() !== '') {
params.set('criteria', searchQuery.trim()); params.set('criteria', searchQuery.trim());
@@ -137,7 +137,7 @@ const SparepartSelect = ({
> >
{spareparts {spareparts
.filter(sparepart => !selectedSpareparts.some(sp => sp.sparepart_id === sparepart.sparepart_id)) .filter(sparepart => !selectedSpareparts.some(sp => sp.sparepart_id === sparepart.sparepart_id))
.slice(0, 10) .slice(0, 5)
.map((sparepart) => ( .map((sparepart) => (
<Option key={sparepart.sparepart_id} value={sparepart.sparepart_id}> <Option key={sparepart.sparepart_id} value={sparepart.sparepart_id}>
<div> <div>

View File

@@ -0,0 +1,263 @@
import { useState, useEffect } from 'react';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
export const useErrorCodeLogic = (errorCodeForm, fileList) => {
const [solutionFields, setSolutionFields] = useState([0]);
const [solutionTypes, setSolutionTypes] = useState({ 0: 'text' });
const [solutionStatuses, setSolutionStatuses] = useState({ 0: true });
const [firstSolutionValid, setFirstSolutionValid] = useState(false);
const [solutionsToDelete, setSolutionsToDelete] = useState(new Set());
const checkPreviousSolutionValid = (currentSolutionIndex) => {
for (let i = 0; i < currentSolutionIndex; i++) {
const fieldId = solutionFields[i];
const solutionType = solutionTypes[fieldId];
const solutionName = errorCodeForm.getFieldValue(`solution_name_${fieldId}`);
if (!solutionName || solutionName.trim() === '') {
return false;
}
if (solutionType === 'text') {
const textSolution = errorCodeForm.getFieldValue(`text_solution_${fieldId}`);
if (!textSolution || textSolution.trim() === '') {
return false;
}
} else if (solutionType === 'file') {
const filesForSolution = fileList.filter(file => file.solutionId === fieldId);
if (filesForSolution.length === 0) {
return false;
}
}
}
return true;
};
const checkFirstSolutionValid = () => {
if (solutionFields.length === 0) {
setFirstSolutionValid(false);
return false;
}
const isValid = checkPreviousSolutionValid(1);
setFirstSolutionValid(isValid);
return isValid;
};
const handleAddSolutionField = () => {
const currentSolutionCount = solutionFields.length;
const nextSolutionNumber = currentSolutionCount + 1;
if (!checkPreviousSolutionValid(currentSolutionCount)) {
let incompleteSolutionIndex = -1;
for (let i = 0; i < currentSolutionCount; i++) {
const fieldId = solutionFields[i];
const solutionType = solutionTypes[fieldId];
const solutionName = errorCodeForm.getFieldValue(`solution_name_${fieldId}`);
let hasContent = false;
if (solutionType === 'text') {
const textSolution = errorCodeForm.getFieldValue(`text_solution_${fieldId}`);
hasContent = textSolution && textSolution.trim();
} else if (solutionType === 'file') {
const filesForSolution = fileList.filter(file => file.solutionId === fieldId);
hasContent = filesForSolution.length > 0;
}
if (!solutionName?.trim() || !hasContent) {
incompleteSolutionIndex = i + 1;
break;
}
}
NotifAlert({
icon: 'warning',
title: 'Perhatian',
message: `Harap lengkapi Solution ${incompleteSolutionIndex} terlebih dahulu sebelum menambah Solution ${nextSolutionNumber}!`
});
return;
}
const newId = `new-${Date.now()}`;
setSolutionFields(prev => [...prev, newId]);
setSolutionTypes(prev => ({ ...prev, [newId]: 'text' }));
setSolutionStatuses(prev => ({ ...prev, [newId]: true }));
errorCodeForm.setFieldValue(`solution_status_${newId}`, true);
errorCodeForm.setFieldValue(`solution_type_${newId}`, 'text');
};
const handleRemoveSolutionField = (id) => {
const isNewSolution = !id.toString().startsWith('existing-');
if (isNewSolution) {
if (solutionFields.length > 1) {
setSolutionFields(solutionFields.filter(fieldId => fieldId !== id));
setSolutionTypes(prev => {
const newTypes = { ...prev };
delete newTypes[id];
return newTypes;
});
setSolutionStatuses(prev => {
const newStatuses = { ...prev };
delete newStatuses[id];
return newStatuses;
});
setSolutionsToDelete(prev => {
const newSet = new Set(prev);
newSet.delete(id);
return newSet;
});
} else {
NotifAlert({
icon: 'warning',
title: 'Perhatian',
message: 'Setiap error code harus memiliki minimal 1 solution!'
});
}
} else {
const solutionName = errorCodeForm.getFieldValue(`solution_name_${id}`);
const solutionType = solutionTypes[id];
let isEmpty = true;
const existingSolution = window.currentSolutionData?.[id];
const hasExistingData = existingSolution && (
(existingSolution.solution_name && existingSolution.solution_name.trim()) ||
(existingSolution.text_solution && existingSolution.text_solution.trim()) ||
(existingSolution.path_solution && existingSolution.path_solution.trim())
);
if (solutionType === 'text') {
const textSolution = errorCodeForm.getFieldValue(`text_solution_${id}`);
isEmpty = !solutionName?.trim() && !textSolution?.trim() && !hasExistingData;
} else if (solutionType === 'file') {
const filesForSolution = fileList.filter(file => file.solutionId === id);
isEmpty = !solutionName?.trim() && filesForSolution.length === 0 && !hasExistingData;
}
if (isEmpty) {
if (solutionFields.length > 1) {
setSolutionFields(solutionFields.filter(fieldId => fieldId !== id));
setSolutionTypes(prev => {
const newTypes = { ...prev };
delete newTypes[id];
return newTypes;
});
setSolutionStatuses(prev => {
const newStatuses = { ...prev };
delete newStatuses[id];
return newStatuses;
});
if (window.currentSolutionData) {
delete window.currentSolutionData[id];
}
setSolutionsToDelete(prev => {
const newSet = new Set(prev);
newSet.delete(id);
return newSet;
});
} else {
NotifAlert({
icon: 'warning',
title: 'Perhatian',
message: 'Setiap error code harus memiliki minimal 1 solution!'
});
}
} else {
if (solutionFields.length > 1) {
setSolutionsToDelete(prev => new Set(prev).add(id));
const solutionElement = document.querySelector(`[data-solution-id="${id}"]`);
if (solutionElement) {
solutionElement.style.opacity = '0.5';
solutionElement.style.border = '2px dashed #ff4d4f';
}
NotifOk({
icon: 'success',
title: 'Berhasil',
message: 'Solution ditandai untuk dihapus. Klik "Update Error Code" untuk menyimpan perubahan.'
});
} else {
NotifAlert({
icon: 'warning',
title: 'Perhatian',
message: 'Setiap error code harus memiliki minimal 1 solution!'
});
}
}
}
};
const handleSolutionTypeChange = (fieldId, type) => {
setSolutionTypes(prev => ({ ...prev, [fieldId]: type }));
};
const handleSolutionStatusChange = (fieldId, status) => {
setSolutionStatuses(prev => ({
...prev,
[fieldId]: status
}));
};
const setSolutionsForExistingRecord = (solutions, errorCodeForm) => {
const newSolutionFields = [];
const newSolutionTypes = {};
const newSolutionStatuses = {};
const newSolutionData = {};
solutions.forEach((solution, index) => {
const fieldId = `existing-${index}`;
newSolutionFields.push(fieldId);
newSolutionTypes[fieldId] = solution.type_solution || 'text';
newSolutionStatuses[fieldId] = solution.is_active !== false;
newSolutionData[fieldId] = {
...solution
};
setTimeout(() => {
errorCodeForm.setFieldsValue({
[`solution_name_${fieldId}`]: solution.solution_name,
[`text_solution_${fieldId}`]: solution.text_solution || '',
[`solution_status_${fieldId}`]: solution.is_active !== false,
[`solution_type_${fieldId}`]: solution.type_solution === 'image' || solution.type_solution === 'pdf' ? 'file' : solution.type_solution
});
}, 100);
});
setSolutionFields(newSolutionFields);
setSolutionTypes(newSolutionTypes);
setSolutionStatuses(newSolutionStatuses);
window.currentSolutionData = newSolutionData;
};
const resetSolutionFields = () => {
setSolutionFields([0]);
setSolutionTypes({ 0: 'text' });
setSolutionStatuses({ 0: true });
setFirstSolutionValid(false);
setSolutionsToDelete(new Set());
};
useEffect(() => {
const timer = setTimeout(() => {
checkFirstSolutionValid();
}, 100);
return () => clearTimeout(timer);
}, [solutionFields, solutionTypes, fileList, errorCodeForm]);
return {
solutionFields,
solutionTypes,
solutionStatuses,
firstSolutionValid,
solutionsToDelete,
handleAddSolutionField,
handleRemoveSolutionField,
handleSolutionTypeChange,
handleSolutionStatusChange,
resetSolutionFields,
checkFirstSolutionValid,
setSolutionsForExistingRecord
};
};

View File

@@ -0,0 +1,453 @@
import { useState, useEffect } from 'react';
export const useSolutionLogic = (solutionForm) => {
const [solutionFields, setSolutionFields] = useState([0]);
const [solutionTypes, setSolutionTypes] = useState({ 0: 'text' });
const [solutionStatuses, setSolutionStatuses] = useState({ 0: true });
const [solutionsToDelete, setSolutionsToDelete] = useState([]);
useEffect(() => {
setTimeout(() => {
if (solutionForm) {
solutionForm.setFieldsValue({
solution_items: {
0: {
name: 'Solution 1',
status: true,
type: 'text',
text: 'Solution description',
file: null,
fileUpload: null
}
}
});
}
}, 100);
}, [solutionForm]);
const handleAddSolutionField = () => {
const newKey = Date.now();
setSolutionFields(prev => [...prev, newKey]);
setSolutionTypes(prev => ({ ...prev, [newKey]: 'text' }));
setSolutionStatuses(prev => ({ ...prev, [newKey]: true }));
setTimeout(() => {
const currentFormValues = solutionForm.getFieldsValue(true);
const existingNames = [];
Object.keys(currentFormValues).forEach(key => {
if (key.startsWith('solution_items,') || key.startsWith('solution_items.')) {
const solutionData = currentFormValues[key];
if (solutionData && solutionData.name) {
existingNames.push(solutionData.name);
}
}
});
if (currentFormValues.solution_items) {
Object.values(currentFormValues.solution_items).forEach(solution => {
if (solution && solution.name) {
existingNames.push(solution.name);
}
});
}
let solutionNumber = solutionFields.length + 1;
let defaultName = `Solution ${solutionNumber}`;
while (existingNames.includes(defaultName)) {
solutionNumber++;
defaultName = `Solution ${solutionNumber}`;
}
solutionForm.setFieldValue(['solution_items', newKey, 'name'], defaultName);
solutionForm.setFieldValue(['solution_items', newKey, 'type'], 'text');
solutionForm.setFieldValue(['solution_items', newKey, 'text'], 'Solution description');
solutionForm.setFieldValue(['solution_items', newKey, 'status'], true);
solutionForm.setFieldValue(['solution_items', newKey, 'file'], null);
solutionForm.setFieldValue(['solution_items', newKey, 'fileUpload'], null);
}, 100);
};
const handleRemoveSolutionField = (key) => {
if (solutionFields.length <= 1) {
return;
}
setSolutionFields(prev => prev.filter(field => field !== key));
const newTypes = { ...solutionTypes };
const newStatuses = { ...solutionStatuses };
delete newTypes[key];
delete newStatuses[key];
setSolutionTypes(newTypes);
setSolutionStatuses(newStatuses);
setTimeout(() => {
try {
solutionForm.setFieldValue(['solution_items', key], undefined);
solutionForm.setFieldValue(['solution_items', key, 'name'], undefined);
solutionForm.setFieldValue(['solution_items', key, 'type'], undefined);
solutionForm.setFieldValue(['solution_items', key, 'text'], undefined);
solutionForm.setFieldValue(['solution_items', key, 'status'], undefined);
solutionForm.setFieldValue(['solution_items', key, 'file'], undefined);
solutionForm.setFieldValue(['solution_items', key, 'fileUpload'], undefined);
} catch (error) {
}
}, 50);
};
const handleSolutionTypeChange = (key, value) => {
setSolutionTypes(prev => ({ ...prev, [key]: value }));
setTimeout(() => {
const fieldName = ['solution_items', key];
const currentSolutionData = solutionForm.getFieldsValue([fieldName]) || {};
const solutionData = currentSolutionData[`solution_items,${key}`] || currentSolutionData[`solution_items.${key}`] || {};
if (value === 'text') {
const updatedSolutionData = {
...solutionData,
fileUpload: null,
file: null,
path_solution: null,
fileName: null,
text: solutionData.text || 'Solution description'
};
solutionForm.setFieldValue([...fieldName, 'fileUpload'], null);
solutionForm.setFieldValue([...fieldName, 'file'], null);
solutionForm.setFieldValue([...fieldName, 'path_solution'], null);
solutionForm.setFieldValue([...fieldName, 'fileName'], null);
solutionForm.setFieldValue([...fieldName, 'text'], updatedSolutionData.text);
} else if (value === 'file') {
const updatedSolutionData = {
...solutionData,
text: '',
fileUpload: null,
file: null,
path_solution: null,
fileName: null
};
solutionForm.setFieldValue([...fieldName, 'text'], '');
solutionForm.setFieldValue([...fieldName, 'fileUpload'], null);
solutionForm.setFieldValue([...fieldName, 'file'], null);
solutionForm.setFieldValue([...fieldName, 'path_solution'], null);
solutionForm.setFieldValue([...fieldName, 'fileName'], null);
}
}, 0);
};
const handleSolutionStatusChange = (key, value) => {
setSolutionStatuses(prev => ({ ...prev, [key]: value }));
};
const resetSolutionFields = () => {
setSolutionFields([0]);
setSolutionTypes({ 0: 'text' });
setSolutionStatuses({ 0: true });
if (!solutionForm || !solutionForm.resetFields) {
return;
}
solutionForm.resetFields();
setTimeout(() => {
solutionForm.setFieldsValue({
solution_items: {
0: {
name: 'Solution 1',
status: true,
type: 'text',
text: 'Solution description',
file: null,
fileUpload: null
}
}
});
solutionForm.setFieldValue(['solution_items', 0, 'name'], 'Solution 1');
solutionForm.setFieldValue(['solution_items', 0, 'type'], 'text');
solutionForm.setFieldValue(['solution_items', 0, 'text'], 'Solution description');
solutionForm.setFieldValue(['solution_items', 0, 'status'], true);
solutionForm.setFieldValue(['solution_items', 0, 'file'], null);
solutionForm.setFieldValue(['solution_items', 0, 'fileUpload'], null);
}, 100);
};
const checkFirstSolutionValid = () => {
if (!solutionForm || !solutionForm.getFieldsValue) {
return false;
}
const values = solutionForm.getFieldsValue();
const firstField = solutionFields[0];
if (!firstField) {
return false;
}
const solutionKey = firstField.key || firstField;
const commaPath = `solution_items,${solutionKey}`;
const dotPath = `solution_items.${solutionKey}`;
const firstSolution = values[commaPath] || values[dotPath];
if (!firstSolution || !firstSolution.name || firstSolution.name.trim() === '') {
return false;
}
if (solutionTypes[solutionKey] === 'text' && (!firstSolution.text || firstSolution.text.trim() === '')) {
return false;
}
return true;
};
const getSolutionData = () => {
try {
const values = solutionForm.getFieldsValue(true);
const result = [];
solutionFields.forEach(key => {
let solution = null;
try {
solution = solutionForm.getFieldValue(['solution_items', key]);
} catch (error) {
}
if (!solution && values.solution_items && values.solution_items[key]) {
solution = values.solution_items[key];
}
if (!solution) {
const commaKey = `solution_items,${key}`;
solution = values[commaKey];
}
if (!solution) {
const dotKey = `solution_items.${key}`;
solution = values[dotKey];
}
if (!solution) {
const allKeys = Object.keys(values);
const foundKey = allKeys.find(k =>
k.includes(key.toString()) &&
k.includes('solution_items')
);
if (foundKey) {
solution = values[foundKey];
}
}
if (!solution) {
const rawValues = solutionForm.getFieldsValue();
if (rawValues.solution_items && rawValues.solution_items[key]) {
solution = rawValues.solution_items[key];
}
}
if (!solution) {
return;
}
const hasName = solution.name && solution.name.trim() !== '';
if (!hasName) {
return;
}
const solutionType = solutionTypes[key] || solution.type || 'text';
let isValidType = true;
if (solutionType === 'text') {
isValidType = solution.text && solution.text.trim() !== '';
if (!isValidType) {
return;
}
} else if (solutionType === 'file') {
const hasPathSolution = solution.path_solution && solution.path_solution.trim() !== '';
const hasFileUpload = (solution.fileUpload && typeof solution.fileUpload === 'object' && Object.keys(solution.fileUpload).length > 0);
const hasFile = (solution.file && typeof solution.file === 'object' && Object.keys(solution.file).length > 0);
isValidType = hasPathSolution || hasFileUpload || hasFile;
if (!isValidType) {
return;
}
}
let pathSolution = '';
let fileObject = null;
const typeSolution = solutionTypes[key] || solution.type || 'text';
if (typeSolution === 'file') {
if (solution.fileUpload && typeof solution.fileUpload === 'object' && Object.keys(solution.fileUpload).length > 0) {
pathSolution = solution.fileUpload.path_solution || solution.fileUpload.uploadPath || '';
fileObject = solution.fileUpload;
} else if (solution.file && typeof solution.file === 'object' && Object.keys(solution.file).length > 0) {
pathSolution = solution.file.path_solution || solution.file.uploadPath || '';
fileObject = solution.file;
} else if (solution.file && typeof solution.file === 'string' && solution.file.trim() !== '') {
pathSolution = solution.file;
} else if (solution.path_solution && solution.path_solution.trim() !== '') {
pathSolution = solution.path_solution;
} else {
}
}
let finalTypeSolution = typeSolution;
if (typeSolution === 'file') {
if (fileObject && fileObject.type_solution) {
finalTypeSolution = fileObject.type_solution;
} else {
finalTypeSolution = 'image';
}
}
const finalSolution = {
solution_name: solution.name,
type_solution: finalTypeSolution,
is_active: solution.status !== false && solution.status !== undefined ? solution.status : (solutionStatuses[key] !== false),
};
if (typeSolution === 'text') {
finalSolution.text_solution = solution.text || '';
finalSolution.path_solution = '';
} else {
finalSolution.text_solution = '';
finalSolution.path_solution = pathSolution;
}
result.push(finalSolution);
});
return result;
} catch (error) {
return [];
}
};
const setSolutionsForExistingRecord = (solutions, form) => {
if (!solutions || solutions.length === 0) return;
const newFields = solutions.map((solution, index) => solution.id || index);
setSolutionFields(newFields);
const solutionsValues = {};
const newTypes = {};
const newStatuses = {};
solutions.forEach((solution, index) => {
const key = solution.brand_code_solution_id || solution.id || index;
let fileObject = null;
if (solution.path_solution && solution.path_solution.trim() !== '') {
const fileName = solution.file_upload_name || solution.path_solution.split('/').pop() || `file_${index}`;
fileObject = {
uploadPath: solution.path_solution,
path_solution: solution.path_solution,
name: fileName,
type_solution: solution.type_solution || 'image',
isExisting: true,
size: 0,
type: solution.type_solution === 'pdf' ? 'application/pdf' : 'image/jpeg',
fileExtension: solution.type_solution === 'pdf' ? 'pdf' : (fileName.split('.').pop().toLowerCase() || 'jpg')
};
}
const isFileType = solution.type_solution && solution.type_solution !== 'text' && fileObject;
solutionsValues[key] = {
name: solution.solution_name || '',
type: isFileType ? 'file' : 'text',
text: solution.text_solution || '',
file: fileObject,
fileUpload: fileObject,
status: solution.is_active !== false,
path_solution: solution.path_solution || ''
};
newTypes[key] = isFileType ? 'file' : 'text';
newStatuses[key] = solution.is_active !== false;
});
const nestedFormValues = {
solution_items: {}
};
Object.keys(solutionsValues).forEach(key => {
const solution = solutionsValues[key];
nestedFormValues.solution_items[key] = {
name: solution.name,
type: solution.type,
text: solution.text,
file: solution.file,
fileUpload: solution.fileUpload,
status: solution.status,
path_solution: solution.path_solution
};
});
form.setFieldsValue(nestedFormValues);
const fallbackFormValues = {};
Object.keys(solutionsValues).forEach(key => {
const solution = solutionsValues[key];
fallbackFormValues[`solution_items,${key}`] = {
name: solution.name,
type: solution.type,
text: solution.text,
file: solution.file,
fileUpload: solution.fileUpload,
status: solution.status,
path_solution: solution.path_solution
};
});
form.setFieldsValue(fallbackFormValues);
Object.keys(solutionsValues).forEach(key => {
const solution = solutionsValues[key];
form.setFieldValue([`solution_items,${key}`, 'name'], solution.name);
form.setFieldValue([`solution_items,${key}`, 'type'], solution.type);
form.setFieldValue([`solution_items,${key}`, 'text'], solution.text);
form.setFieldValue([`solution_items,${key}`, 'file'], solution.file);
form.setFieldValue([`solution_items,${key}`, 'fileUpload'], solution.fileUpload);
form.setFieldValue([`solution_items,${key}`, 'status'], solution.status);
form.setFieldValue([`solution_items,${key}`, 'path_solution'], solution.path_solution);
form.setFieldValue(['solution_items', key, 'name'], solution.name);
form.setFieldValue(['solution_items', key, 'type'], solution.type);
form.setFieldValue(['solution_items', key, 'text'], solution.text);
form.setFieldValue(['solution_items', key, 'file'], solution.file);
form.setFieldValue(['solution_items', key, 'fileUpload'], solution.fileUpload);
form.setFieldValue(['solution_items', key, 'status'], solution.status);
form.setFieldValue(['solution_items', key, 'path_solution'], solution.path_solution);
});
setSolutionTypes(newTypes);
setSolutionStatuses(newStatuses);
};
return {
solutionFields,
solutionTypes,
solutionStatuses,
solutionsToDelete,
firstSolutionValid: checkFirstSolutionValid(),
handleAddSolutionField,
handleRemoveSolutionField,
handleSolutionTypeChange,
handleSolutionStatusChange,
resetSolutionFields,
checkFirstSolutionValid,
getSolutionData,
setSolutionsForExistingRecord,
};
};

View File

@@ -38,7 +38,7 @@ const DetailPlantSubSection = (props) => {
return; return;
} }
// console.log(`📝 Input change: ${name} = ${value}`); console.log(`📝 Input change: ${name} = ${value}`);
if (name) { if (name) {
setFormData((prev) => ({ setFormData((prev) => ({
@@ -74,20 +74,16 @@ const DetailPlantSubSection = (props) => {
return; return;
try { try {
// console.log('💾 Current formData before save:', formData); console.log('💾 Current formData before save:', formData);
const payload = { const payload = {
plant_sub_section_name: formData.plant_sub_section_name, plant_sub_section_name: formData.plant_sub_section_name,
plant_sub_section_description: plant_sub_section_description: (formData.plant_sub_section_description && formData.plant_sub_section_description.trim() !== '') ? formData.plant_sub_section_description : ' ',
formData.plant_sub_section_description &&
formData.plant_sub_section_description.trim() !== ''
? formData.plant_sub_section_description
: ' ',
table_name_value: formData.table_name_value, // Fix field name table_name_value: formData.table_name_value, // Fix field name
is_active: formData.is_active, is_active: formData.is_active,
}; };
// console.log('📤 Payload to be sent:', payload); console.log('📤 Payload to be sent:', payload);
const response = const response =
props.actionMode === 'edit' props.actionMode === 'edit'
@@ -130,17 +126,17 @@ const DetailPlantSubSection = (props) => {
}; };
useEffect(() => { useEffect(() => {
// console.log('🔄 Modal state changed:', { console.log('🔄 Modal state changed:', {
// showModal: props.showModal, showModal: props.showModal,
// actionMode: props.actionMode, actionMode: props.actionMode,
// selectedData: props.selectedData, selectedData: props.selectedData,
// }); });
if (props.selectedData) { if (props.selectedData) {
// console.log('📋 Setting form data from selectedData:', props.selectedData); console.log('📋 Setting form data from selectedData:', props.selectedData);
setFormData(props.selectedData); setFormData(props.selectedData);
} else { } else {
// console.log('📋 Resetting to default data'); console.log('📋 Resetting to default data');
setFormData(defaultData); setFormData(defaultData);
} }
}, [props.showModal, props.selectedData, props.actionMode]); }, [props.showModal, props.selectedData, props.actionMode]);

View File

@@ -112,9 +112,9 @@ const DetailShift = (props) => {
is_active: formData.is_active, is_active: formData.is_active,
}; };
// console.log('Payload yang dikirim:', payload); console.log('Payload yang dikirim:', payload);
// console.log('Type start_time:', typeof payload.start_time, payload.start_time); console.log('Type start_time:', typeof payload.start_time, payload.start_time);
// console.log('Type end_time:', typeof payload.end_time, payload.end_time); console.log('Type end_time:', typeof payload.end_time, payload.end_time);
const response = const response =
props.actionMode === 'edit' props.actionMode === 'edit'

View File

@@ -95,11 +95,11 @@ const DetailSparepart = (props) => {
const newFile = fileList.length > 0 ? fileList[0] : null; const newFile = fileList.length > 0 ? fileList[0] : null;
if (newFile && newFile.originFileObj) { if (newFile && newFile.originFileObj) {
// console.log('Uploading file:', newFile.originFileObj); console.log('Uploading file:', newFile.originFileObj);
const uploadResponse = await uploadFile(newFile.originFileObj, 'images'); const uploadResponse = await uploadFile(newFile.originFileObj, 'images');
// Log untuk debugging // Log untuk debugging
// console.log('Upload response:', uploadResponse); console.log('Upload response:', uploadResponse);
// Cek berbagai kemungkinan struktur respons dari API // Cek berbagai kemungkinan struktur respons dari API
let uploadedUrl = null; let uploadedUrl = null;
@@ -169,7 +169,7 @@ const DetailSparepart = (props) => {
} }
if (uploadedUrl) { if (uploadedUrl) {
// console.log('Successfully extracted image URL:', uploadedUrl); console.log('Successfully extracted image URL:', uploadedUrl);
imageUrl = uploadedUrl; imageUrl = uploadedUrl;
} else { } else {
console.error('Upload response structure:', uploadResponse); console.error('Upload response structure:', uploadResponse);
@@ -209,10 +209,7 @@ const DetailSparepart = (props) => {
sparepart_name: formData.sparepart_name, // Wajib sparepart_name: formData.sparepart_name, // Wajib
}; };
payload.sparepart_description = payload.sparepart_description = (formData.sparepart_description && formData.sparepart_description.trim() !== '') ? formData.sparepart_description : ' ';
formData.sparepart_description && formData.sparepart_description.trim() !== ''
? formData.sparepart_description
: ' ';
if (formData.sparepart_model && formData.sparepart_model.trim() !== '') { if (formData.sparepart_model && formData.sparepart_model.trim() !== '') {
payload.sparepart_model = formData.sparepart_model; payload.sparepart_model = formData.sparepart_model;
} }
@@ -236,13 +233,13 @@ const DetailSparepart = (props) => {
payload.sparepart_foto = imageUrl; payload.sparepart_foto = imageUrl;
} }
// console.log('Sending payload:', payload); console.log('Sending payload:', payload);
const response = formData.sparepart_id const response = formData.sparepart_id
? await updateSparepart(formData.sparepart_id, payload) ? await updateSparepart(formData.sparepart_id, payload)
: await createSparepart(payload); : await createSparepart(payload);
// console.log('API response:', response); console.log('API response:', response);
if (response && (response.statusCode === 200 || response.statusCode === 201)) { if (response && (response.statusCode === 200 || response.statusCode === 201)) {
NotifOk({ NotifOk({

View File

@@ -164,7 +164,7 @@ const ListUnit = memo(function ListUnit(props) {
const handleDelete = async (param) => { const handleDelete = async (param) => {
try { try {
const response = await deleteUnit(param.unit_id); const response = await deleteUnit(param.unit_id);
// console.log('deleteUnit response:', response); console.log('deleteUnit response:', response);
if (response.statusCode === 200) { if (response.statusCode === 200) {
NotifAlert({ NotifAlert({

View File

@@ -38,14 +38,7 @@ import {
SearchOutlined, SearchOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import { useNavigate, Link as RouterLink } from 'react-router-dom'; import { useNavigate, Link as RouterLink } from 'react-router-dom';
import { import { getAllNotification } from '../../../api/notification';
getAllNotification,
getNotificationLogByNotificationId,
getNotificationDetail,
resendChatByUser,
resendChatAllUser,
searchData,
} from '../../../api/notification';
const { Text, Paragraph, Link: AntdLink } = Typography; const { Text, Paragraph, Link: AntdLink } = Typography;
@@ -54,21 +47,19 @@ const transformNotificationData = (apiData) => {
return apiData.map((item, index) => ({ return apiData.map((item, index) => ({
id: `notification-${item.notification_error_id}-${index}`, // Unique key prefix with array index id: `notification-${item.notification_error_id}-${index}`, // Unique key prefix with array index
type: item.is_read ? 'resolved' : item.is_delivered ? 'warning' : 'critical', type: item.is_read ? 'resolved' : item.is_delivered ? 'warning' : 'critical',
title: item.error_code_name || 'Unknown Error', title: item.error_code?.error_code_name || item.device_name || 'Unknown Error',
issue: item.error_code || item.error_code_name || 'Unknown Error', issue: item.error_code || item.error_code_name || 'Unknown Error',
description: `${item.error_code} - ${item.error_code_name || ''}`, description: `${item.error_code} - ${item.error_code_name || ''}`,
timestamp: item.created_at timestamp:
? new Date(item.created_at).toLocaleString('id-ID', { item.created_at ? new Date(item.created_at).toLocaleString('id-ID', {
day: '2-digit', day: '2-digit',
month: '2-digit', month: '2-digit',
year: 'numeric', year: 'numeric',
hour: '2-digit', hour: '2-digit',
minute: '2-digit', minute: '2-digit',
}) + ' WIB' }) + ' WIB' : 'N/A',
: 'N/A',
location: item.plant_sub_section_name || item.device_location || 'Location not specified', location: item.plant_sub_section_name || item.device_location || 'Location not specified',
details: item.device_name || '-', details: item.message_error_issue || 'No details available',
errId: item.notification_error_id || 0,
link: `/verification-sparepart/${item.notification_error_id}`, // Dummy URL untuk verifikasi spare part link: `/verification-sparepart/${item.notification_error_id}`, // Dummy URL untuk verifikasi spare part
subsection: item.plant_sub_section_name || 'N/A', subsection: item.plant_sub_section_name || 'N/A',
isRead: item.is_read, isRead: item.is_read,
@@ -77,14 +68,67 @@ const transformNotificationData = (apiData) => {
errorCode: item.error_code, errorCode: item.error_code,
solutionName: item.error_code?.solution?.[0]?.solution_name || 'N/A', solutionName: item.error_code?.solution?.[0]?.solution_name || 'N/A',
typeSolution: item.error_code?.solution?.[0]?.type_solution || 'N/A', typeSolution: item.error_code?.solution?.[0]?.type_solution || 'N/A',
pathSolution: pathSolution: item.error_code?.solution?.[0]?.path_document || item.error_code?.solution?.[0]?.path_solution || 'N/A',
item.error_code?.solution?.[0]?.path_document ||
item.error_code?.solution?.[0]?.path_solution ||
'N/A',
error_code: item.error_code, error_code: item.error_code,
})); }));
}; };
// Dummy data untuk user history
const userHistoryData = [
{
id: '1',
name: 'John Doe',
phone: '081234567890',
status: 'Delivered',
timestamp: '04-11-2025 11:40 WIB',
},
{
id: '2',
name: 'Jane Smith',
phone: '087654321098',
status: 'Delivered',
timestamp: '04-11-2025 11:41 WIB',
},
{
id: '3',
name: 'Peter Jones',
phone: '082345678901',
status: 'Delivered',
timestamp: '04-11-2025 11:42 WIB',
},
];
// Dummy data untuk log history
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.',
},
];
const ListNotification = memo(function ListNotification(props) { const ListNotification = memo(function ListNotification(props) {
const [notifications, setNotifications] = useState([]); const [notifications, setNotifications] = useState([]);
const [activeTab, setActiveTab] = useState('all'); const [activeTab, setActiveTab] = useState('all');
@@ -94,10 +138,6 @@ const ListNotification = memo(function ListNotification(props) {
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 [logHistoryData, setLogHistoryData] = useState([]);
const [logLoading, setLogLoading] = useState(false);
const [userHistoryData, setUserHistoryData] = useState([]);
const [userLoading, setUserLoading] = useState(false);
const [pagination, setPagination] = useState({ const [pagination, setPagination] = useState({
current_page: 1, current_page: 1,
current_limit: 10, current_limit: 10,
@@ -199,9 +239,9 @@ const ListNotification = memo(function ListNotification(props) {
content: `Are you sure you want to resend the notification for "${notification.title}"?`, content: `Are you sure you want to resend the notification for "${notification.title}"?`,
okText: 'Resend', okText: 'Resend',
cancelText: 'Cancel', cancelText: 'Cancel',
async onOk() { onOk() {
console.log('Resending notification:', notification.id); console.log('Resending notification:', notification.id);
await resendChatAllUser(notification.errId);
message.success( message.success(
`Notification for "${notification.title}" has been resent successfully.` `Notification for "${notification.title}" has been resent successfully.`
); );
@@ -220,49 +260,13 @@ const ListNotification = memo(function ListNotification(props) {
); );
}; };
const fetchSearch = async (data) => {
setLoading(true);
try {
const response = await searchData(data);
if (response && response.data) {
const transformedData = transformNotificationData(response.data);
setNotifications(transformedData);
// Update pagination with API response or calculate from data
if (response.paging) {
setPagination({
current_page: response.paging.current_page || page,
current_limit: response.paging.current_limit || limit,
total_limit: response.paging.total_limit || transformedData.length,
total_page:
response.paging.total_page || Math.ceil(transformedData.length / limit),
});
} else {
// Fallback: calculate pagination from data
const totalItems = transformedData.length;
setPagination((prev) => ({
...prev,
current_page: page,
current_limit: limit,
total_limit: totalItems,
total_page: Math.ceil(totalItems / limit),
}));
}
}
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
};
const handleSearch = () => { const handleSearch = () => {
fetchSearch(searchValue); setSearchTerm(searchValue);
}; };
const handleSearchClear = () => { const handleSearchClear = () => {
setSearchValue(''); setSearchValue('');
fetchSearch(''); setSearchTerm('');
}; };
const getUnreadCount = () => notifications.filter((n) => !n.isRead).length; const getUnreadCount = () => notifications.filter((n) => !n.isRead).length;
@@ -277,78 +281,6 @@ const ListNotification = memo(function ListNotification(props) {
}); });
}; };
// Fetch log history from API
const fetchLogHistory = async (notificationId) => {
try {
setLogLoading(true);
const response = await getNotificationLogByNotificationId(notificationId);
if (response && response.data) {
// Transform API data to component format
const transformedLogs = response.data.map((log) => ({
id: log.notification_error_log_id,
timestamp: log.created_at
? new Date(log.created_at).toLocaleString('id-ID', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
}) + ' WIB'
: 'N/A',
addedBy: {
name: log.contact_name || 'Unknown',
phone: log.contact_phone || 'N/A',
},
description: log.notification_error_log_description || '',
}));
setLogHistoryData(transformedLogs);
}
} catch (err) {
console.error('Error fetching log history:', err);
setLogHistoryData([]); // Set empty array on error
} finally {
setLogLoading(false);
}
};
// Fetch user history from API
const fetchUserHistory = async (notificationId) => {
try {
setUserLoading(true);
const response = await getNotificationDetail(notificationId);
if (response && response.data && response.data.users) {
// Transform API data to component format
const transformedUsers = response.data.users.map((user) => ({
id: user.notification_error_user_id.toString(),
name: user.contact_name,
phone: user.contact_phone,
status: user.is_send ? 'Delivered' : 'Pending',
timestamp: user.updated_at
? new Date(user.updated_at)
.toLocaleString('id-ID', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
})
.replace('.', ':') + ' WIB'
: 'N/A',
}));
setUserHistoryData(transformedUsers);
} else {
setUserHistoryData([]);
}
} catch (err) {
console.error('Error fetching user history:', err);
setUserHistoryData([]); // Set empty array on error
} finally {
setUserLoading(false);
}
};
const tabButtonStyle = (isActive) => ({ const tabButtonStyle = (isActive) => ({
padding: '12px 16px', padding: '12px 16px',
border: 'none', border: 'none',
@@ -383,6 +315,7 @@ const ListNotification = memo(function ListNotification(props) {
borderColor: notification.isRead ? '#f0f0f0' : '#d6e4ff', borderColor: notification.isRead ? '#f0f0f0' : '#d6e4ff',
cursor: 'pointer', cursor: 'pointer',
}} }}
onClick={() => handleMarkAsRead(notification.id)}
> >
<div <div
style={{ style={{
@@ -421,7 +354,7 @@ const ListNotification = memo(function ListNotification(props) {
<Text strong>{notification.title}</Text> <Text strong>{notification.title}</Text>
<div style={{ marginTop: '4px' }}> <div style={{ marginTop: '4px' }}>
<Text style={{ color }}> <Text style={{ color }}>
Error Code {notification.issue} {notification.issue}
</Text> </Text>
</div> </div>
</div> </div>
@@ -438,7 +371,7 @@ const ListNotification = memo(function ListNotification(props) {
</div> </div>
</Col> </Col>
<Col flex="auto"> <Col flex="auto">
{/* <div <div
style={{ style={{
display: 'flex', display: 'flex',
gap: '8px', gap: '8px',
@@ -461,18 +394,12 @@ const ListNotification = memo(function ListNotification(props) {
> >
{notification.details} {notification.details}
</Paragraph> </Paragraph>
</div> */} </div>
<Space <Space
direction="vertical" direction="vertical"
size={4} size={4}
style={{ fontSize: '13px', color: '#8c8c8c' }} style={{ fontSize: '13px', color: '#8c8c8c' }}
> >
<Space>
<MobileOutlined />
<Text type="secondary">
{notification.details}
</Text>
</Space>
<Space> <Space>
<ClockCircleOutlined /> <ClockCircleOutlined />
<Text type="secondary"> <Text type="secondary">
@@ -486,10 +413,17 @@ const ListNotification = memo(function ListNotification(props) {
</Text> </Text>
</Space> </Space>
<Space> <Space>
<LinkOutlined />
<AntdLink
href={notification.link}
target="_blank"
>
{notification.link}
</AntdLink>
<Button <Button
type="link" type="link"
icon={<SendOutlined />} icon={<SendOutlined />}
style={{ paddingLeft: '0px' }} style={{ paddingLeft: '8px' }}
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
handleResend(notification); handleResend(notification);
@@ -525,18 +459,8 @@ const ListNotification = memo(function ListNotification(props) {
border: '1px solid #1890ff', border: '1px solid #1890ff',
borderRadius: '4px', borderRadius: '4px',
}} }}
onClick={async (e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
setSelectedNotification(notification);
// Extract notification ID from the notification object
const notificationId =
notification.id.split('-')[1];
// Fetch user history for the selected notification
await fetchUserHistory(notificationId);
setModalContent('user'); setModalContent('user');
}} }}
/> />
@@ -576,15 +500,6 @@ const ListNotification = memo(function ListNotification(props) {
}} }}
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
// Set the selected notification for the log history
const notificationId =
notification.id.split('-')[1];
setSelectedNotification(notification);
// Fetch log history for the selected notification
fetchLogHistory(notificationId);
setModalContent('log'); setModalContent('log');
}} }}
/> />
@@ -603,11 +518,6 @@ const ListNotification = memo(function ListNotification(props) {
const renderUserHistory = () => ( const renderUserHistory = () => (
<> <>
{userLoading ? (
<div style={{ textAlign: 'center', padding: '24px' }}>
<Spin size="large" />
</div>
) : (
<Space direction="vertical" size="middle" style={{ display: 'flex' }}> <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
{userHistoryData.map((user) => ( {userHistoryData.map((user) => (
<Card key={user.id} style={{ borderColor: '#91d5ff' }}> <Card key={user.id} style={{ borderColor: '#91d5ff' }}>
@@ -620,75 +530,31 @@ const ListNotification = memo(function ListNotification(props) {
<MobileOutlined /> {user.phone} <MobileOutlined /> {user.phone}
</Text> </Text>
<Text>|</Text> <Text>|</Text>
<Badge <Badge status="success" text={user.status} />
status={
user.status === 'Delivered' ? 'success' : 'default'
}
text={user.status}
/>
</Space> </Space>
<Divider style={{ margin: '8px 0' }} /> <Divider style={{ margin: '8px 0' }} />
<Space align="center"> <Space align="center">
{user.status === 'Delivered' ? (
<CheckCircleFilled style={{ color: '#52c41a' }} /> <CheckCircleFilled style={{ color: '#52c41a' }} />
) : (
<ClockCircleOutlined style={{ color: '#faad14' }} />
)}
<Text type="secondary"> <Text type="secondary">
{user.status === 'Delivered' Success Delivered at {user.timestamp}
? 'Success Delivered at'
: 'Status '}{' '}
{user.timestamp}
</Text> </Text>
</Space> </Space>
</Col> </Col>
<Col> <Col>
<Button <Button type="primary" ghost icon={<SendOutlined />}>
type="primary"
ghost
icon={<SendOutlined />}
onClick={async () => {
await resendChatByUser(user.id, user.phone);
}}
>
Resend Resend
</Button> </Button>
</Col> </Col>
</Row> </Row>
</Card> </Card>
))} ))}
{userHistoryData.length === 0 && (
<div style={{ textAlign: 'center', padding: '24px', color: '#8c8c8c' }}>
No user history available
</div>
)}
</Space> </Space>
)}
</> </>
); );
const renderLogHistory = () => ( const renderLogHistory = () => (
<> <>
{logLoading ? ( <div style={{ padding: '0 16px', position: 'relative' }}>
<div style={{ textAlign: 'center', padding: '24px' }}>
<Spin size="large" />
</div>
) : logHistoryData.length === 0 ? (
<div style={{ textAlign: 'center', padding: '24px', color: '#8c8c8c' }}>
Tidak ada log history
</div>
) : (
<div
style={{
height: '400px',
overflowY: 'auto',
padding: '0 16px',
position: 'relative',
border: '1px solid #f0f0f0',
borderRadius: '4px',
}}
>
<div style={{ position: 'relative' }}>
{/* Garis vertikal yang menyambung */} {/* Garis vertikal yang menyambung */}
<div <div
style={{ style={{
@@ -734,28 +600,20 @@ const ListNotification = memo(function ListNotification(props) {
{/* Kolom Kanan: Card */} {/* Kolom Kanan: Card */}
<Col flex="auto"> <Col flex="auto">
<Card size="small" style={{ borderColor: '#91d5ff' }}> <Card size="small" style={{ borderColor: '#91d5ff' }}>
<Row gutter={[16, 8]} align="top"> <Row gutter={[16, 8]} align="middle">
<Col xs={24} md={10}> <Col xs={24} md={12}>
<Space direction="vertical" size={4}> <Space direction="vertical" size={4}>
<Space> <Space>
<ClockCircleOutlined /> <ClockCircleOutlined />
<Text <Text type="secondary" style={{ fontSize: '12px' }}>
type="secondary"
style={{ fontSize: '12px' }}
>
Added at {log.timestamp} Added at {log.timestamp}
</Text> </Text>
</Space> </Space>
<div>
<Text strong>
{log.addedBy.name}
</Text>
</div>
<div> <div>
<Text strong>Added by: {log.addedBy.name}</Text>
<span <span
style={{ style={{
marginLeft: '8px',
border: '1px solid #52c41a', border: '1px solid #52c41a',
color: '#52c41a', color: '#52c41a',
padding: '2px 6px', padding: '2px 6px',
@@ -768,8 +626,7 @@ const ListNotification = memo(function ListNotification(props) {
</div> </div>
</Space> </Space>
</Col> </Col>
<Col xs={24} md={14}> <Col xs={24} md={12}>
<Text strong>Description:</Text>
<Paragraph <Paragraph
style={{ style={{
color: '#595959', color: '#595959',
@@ -786,8 +643,6 @@ const ListNotification = memo(function ListNotification(props) {
</Row> </Row>
))} ))}
</div> </div>
</div>
)}
</> </>
); );
@@ -958,16 +813,7 @@ const ListNotification = memo(function ListNotification(props) {
cursor: 'pointer', cursor: 'pointer',
}} }}
bodyStyle={{ padding: '12px' }} bodyStyle={{ padding: '12px' }}
onClick={() => { onClick={() => setModalContent('log')}
// Set the selected notification for the log history if not already set
if (selectedNotification) {
const notificationId =
selectedNotification.id.split('-')[1];
// Fetch log history for the selected notification
fetchLogHistory(notificationId);
}
setModalContent('log');
}}
> >
<Space> <Space>
<HistoryOutlined <HistoryOutlined
@@ -992,8 +838,7 @@ const ListNotification = memo(function ListNotification(props) {
<Text type="secondary" style={{ fontSize: '10px' }}> <Text type="secondary" style={{ fontSize: '10px' }}>
PDF PDF
</Text> </Text>
} } >
>
<div <div
style={{ style={{
display: 'flex', display: 'flex',
@@ -1284,22 +1129,7 @@ const ListNotification = memo(function ListNotification(props) {
</Button> </Button>
</Space> </Space>
</Card> </Card>
{logLoading ? ( {logHistoryData.map((log) => (
<div style={{ textAlign: 'center', padding: '12px' }}>
<Spin size="small" />
</div>
) : logHistoryData.length === 0 ? (
<div
style={{
textAlign: 'center',
padding: '12px',
color: '#8c8c8c',
}}
>
Tidak ada log history
</div>
) : (
logHistoryData.map((log) => (
<Card <Card
key={log.id} key={log.id}
size="small" size="small"
@@ -1316,8 +1146,7 @@ const ListNotification = memo(function ListNotification(props) {
{log.timestamp} {log.timestamp}
</Text> </Text>
</Card> </Card>
)) ))}
)}
</Space> </Space>
</Card> </Card>
</Col> </Col>
@@ -1457,7 +1286,7 @@ const ListNotification = memo(function ListNotification(props) {
</div> </div>
) : ( ) : (
<Typography.Title level={4} style={{ margin: 0 }}> <Typography.Title level={4} style={{ margin: 0 }}>
{modalContent === 'user' && 'History User Notification'} {modalContent === 'user' && 'User History Notification'}
{modalContent === 'log' && 'Log History Notification'} {modalContent === 'log' && 'Log History Notification'}
</Typography.Title> </Typography.Title>
)} )}

View File

@@ -1,12 +1,6 @@
import React from 'react'; import React from 'react';
import { Modal, Typography, Card, Row, Col, Avatar, Tag, Button, Space } from 'antd'; import { Modal, Typography, Card, Row, Col, Avatar, Tag, Button, Space } from 'antd';
import { import { UserOutlined, PhoneOutlined, CheckCircleOutlined, SyncOutlined, SendOutlined } from '@ant-design/icons';
UserOutlined,
PhoneOutlined,
CheckCircleOutlined,
SyncOutlined,
SendOutlined,
} from '@ant-design/icons';
const { Text } = Typography; const { Text } = Typography;
@@ -47,17 +41,9 @@ const UserHistoryModal = ({ visible, onCancel, notificationData }) => {
const getStatusTag = (status) => { const getStatusTag = (status) => {
switch (status) { switch (status) {
case 'delivered': case 'delivered':
return ( return <Tag icon={<CheckCircleOutlined />} color="success">Delivered</Tag>;
<Tag icon={<CheckCircleOutlined />} color="success">
Delivered
</Tag>
);
case 'sent': case 'sent':
return ( return <Tag icon={<SyncOutlined spin />} color="processing">Sent</Tag>;
<Tag icon={<SyncOutlined spin />} color="processing">
Sent
</Tag>
);
case 'failed': case 'failed':
return <Tag color="error">Failed</Tag>; return <Tag color="error">Failed</Tag>;
default: default:
@@ -69,7 +55,7 @@ const UserHistoryModal = ({ visible, onCancel, notificationData }) => {
<Modal <Modal
title={ title={
<Text strong style={{ fontSize: '18px' }}> <Text strong style={{ fontSize: '18px' }}>
History User Notification User History Notification
</Text> </Text>
} }
open={visible} open={visible}
@@ -92,13 +78,7 @@ const UserHistoryModal = ({ visible, onCancel, notificationData }) => {
<Avatar size="large" icon={<UserOutlined />} /> <Avatar size="large" icon={<UserOutlined />} />
<div> <div>
<Text strong>{user.name}</Text> <Text strong>{user.name}</Text>
<div <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
style={{
display: 'flex',
alignItems: 'center',
gap: '4px',
}}
>
<PhoneOutlined style={{ color: '#8c8c8c' }} /> <PhoneOutlined style={{ color: '#8c8c8c' }} />
<Text type="secondary">{user.phone}</Text> <Text type="secondary">{user.phone}</Text>
</div> </div>

View File

@@ -1,37 +1,14 @@
import React from 'react'; import React from 'react';
import { Button, Row, Col, Card, Badge, Typography, Space, Divider } from 'antd'; import { Button, Row, Col, Card, Badge, Typography, Space, Divider } from 'antd';
import { import { SendOutlined, MobileOutlined, CheckCircleFilled, ArrowLeftOutlined } from '@ant-design/icons';
SendOutlined,
MobileOutlined,
CheckCircleFilled,
ArrowLeftOutlined,
} from '@ant-design/icons';
const { Text } = Typography; const { Text } = Typography;
// Dummy data for user history // Dummy data for user history
const userHistoryData = [ const userHistoryData = [
{ { id: 1, name: 'John Doe', phone: '081234567890', status: 'Delivered', timestamp: '04-11-2025 11:40 WIB' },
id: 1, { id: 2, name: 'Jane Smith', phone: '087654321098', status: 'Delivered', timestamp: '04-11-2025 11:41 WIB' },
name: 'John Doe', { id: 3, name: 'Peter Jones', phone: '082345678901', status: 'Delivered', timestamp: '04-11-2025 11:42 WIB' },
phone: '081234567890',
status: 'Delivered',
timestamp: '04-11-2025 11:40 WIB',
},
{
id: 2,
name: 'Jane Smith',
phone: '087654321098',
status: 'Delivered',
timestamp: '04-11-2025 11:41 WIB',
},
{
id: 3,
name: 'Peter Jones',
phone: '082345678901',
status: 'Delivered',
timestamp: '04-11-2025 11:42 WIB',
},
]; ];
const UserHistory = ({ notification, onBack }) => { const UserHistory = ({ notification, onBack }) => {
@@ -41,9 +18,7 @@ const UserHistory = ({ notification, onBack }) => {
<Col> <Col>
<Space align="center"> <Space align="center">
<Button type="text" icon={<ArrowLeftOutlined />} onClick={onBack} /> <Button type="text" icon={<ArrowLeftOutlined />} onClick={onBack} />
<Typography.Title level={4} style={{ margin: 0 }}> <Typography.Title level={4} style={{ margin: 0 }}>User History Notification</Typography.Title>
History User Notification
</Typography.Title>
</Space> </Space>
<Text type="secondary" style={{ marginLeft: '40px' }}> <Text type="secondary" style={{ marginLeft: '40px' }}>
{notification.title} - {notification.issue} {notification.title} - {notification.issue}
@@ -52,34 +27,25 @@ const UserHistory = ({ notification, onBack }) => {
</Row> </Row>
<Space direction="vertical" size="middle" style={{ display: 'flex' }}> <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
{userHistoryData.map((user) => ( {userHistoryData.map(user => (
<Card <Card key={user.id} style={{ backgroundColor: '#e6f7ff', borderColor: '#91d5ff' }}>
key={user.id}
style={{ backgroundColor: '#e6f7ff', borderColor: '#91d5ff' }}
>
<Row align="middle" justify="space-between"> <Row align="middle" justify="space-between">
<Col> <Col>
<Space align="center"> <Space align="center">
<Text strong>{user.name}</Text> <Text strong>{user.name}</Text>
<Text>|</Text> <Text>|</Text>
<Text> <Text><MobileOutlined /> {user.phone}</Text>
<MobileOutlined /> {user.phone}
</Text>
<Text>|</Text> <Text>|</Text>
<Badge status="success" text={user.status} /> <Badge status="success" text={user.status} />
</Space> </Space>
<Divider style={{ margin: '8px 0' }} /> <Divider style={{ margin: '8px 0' }} />
<Space align="center"> <Space align="center">
<CheckCircleFilled style={{ color: '#52c41a' }} /> <CheckCircleFilled style={{ color: '#52c41a' }} />
<Text type="secondary"> <Text type="secondary">Success Delivered at {user.timestamp}</Text>
Success Delivered at {user.timestamp}
</Text>
</Space> </Space>
</Col> </Col>
<Col> <Col>
<Button type="primary" ghost icon={<SendOutlined />}> <Button type="primary" ghost icon={<SendOutlined />}>Resend</Button>
Resend
</Button>
</Col> </Col>
</Row> </Row>
</Card> </Card>

View File

@@ -1,22 +1,6 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom'; import { useParams, useNavigate } from 'react-router-dom';
import { import { Layout, Card, Row, Col, Typography, Space, Button, Spin, Result, Input, message } from 'antd';
Layout,
Card,
Row,
Col,
Typography,
Space,
Button,
Spin,
Result,
Input,
message,
Avatar,
Tag,
Badge,
Divider,
} from 'antd';
import { import {
ArrowLeftOutlined, ArrowLeftOutlined,
CloseCircleFilled, CloseCircleFilled,
@@ -31,21 +15,10 @@ import {
PlusOutlined, PlusOutlined,
UserOutlined, UserOutlined,
LoadingOutlined, LoadingOutlined,
PhoneOutlined,
CheckCircleOutlined,
SyncOutlined,
SendOutlined,
MobileOutlined,
ClockCircleOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import { import { getNotificationDetail, createNotificationLog, getNotificationLogByNotificationId } from '../../api/notification';
getNotificationDetail, import UserHistoryModal from '../notification/component/UserHistoryModal';
createNotificationLog, import LogHistoryCard from '../notification/component/LogHistoryCard';
getNotificationLogByNotificationId,
updateIsRead,
resendNotificationToUser,
resendChatByUser,
} from '../../api/notification';
const { Content } = Layout; const { Content } = Layout;
const { Text, Paragraph, Link } = Typography; const { Text, Paragraph, Link } = Typography;
@@ -101,55 +74,9 @@ const transformNotificationData = (apiData) => {
device_location: apiData.device_location, device_location: apiData.device_location,
brand_name: apiData.brand_name, brand_name: apiData.brand_name,
}, },
users: apiData.users || [],
}; };
}; };
// Function to get actual users from notification data
const getUsersFromNotification = (notification) => {
if (!notification || !notification.users) return [];
return notification.users.map((user) => ({
id: user.notification_error_user_id.toString(),
name: user.contact_name,
phone: user.contact_phone,
status: user.is_send ? 'Delivered' : 'Pending',
loading: user.loading || false,
timestamp: user.updated_at
? new Date(user.updated_at)
.toLocaleString('id-ID', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
})
.replace('.', ':') + ' WIB'
: 'N/A',
}));
};
const getStatusTag = (status) => {
switch (status) {
case 'delivered':
return (
<Tag icon={<CheckCircleOutlined />} color="success">
Delivered
</Tag>
);
case 'sent':
return (
<Tag icon={<SyncOutlined spin />} color="processing">
Sent
</Tag>
);
case 'failed':
return <Tag color="error">Failed</Tag>;
default:
return <Tag color="default">{status}</Tag>;
}
};
const getIconAndColor = (type) => { const getIconAndColor = (type) => {
switch (type) { switch (type) {
case 'critical': case 'critical':
@@ -163,13 +90,13 @@ const getIconAndColor = (type) => {
} }
}; };
const NotificationDetailTab = (props) => { const NotificationDetailTab = () => {
const params = useParams(); // Mungkin perlu disesuaikan jika route berbeda const { notificationId } = useParams(); // Mungkin perlu disesuaikan jika route berbeda
const notificationId = props.id ?? params.notificationId;
const navigate = useNavigate(); const navigate = useNavigate();
const [notification, setNotification] = useState(null); const [notification, setNotification] = useState(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState(null); const [error, setError] = useState(null);
const [modalContent, setModalContent] = useState(null); // 'user', atau null
const [isAddingLog, setIsAddingLog] = useState(false); const [isAddingLog, setIsAddingLog] = useState(false);
// Log history states // Log history states
@@ -258,9 +185,6 @@ const NotificationDetailTab = (props) => {
// Fetch log history // Fetch log history
fetchLogHistory(notificationId); fetchLogHistory(notificationId);
// Fetch using the actual API
const resUpdate = await updateIsRead(notificationId);
} else { } else {
throw new Error('Notification not found'); throw new Error('Notification not found');
} }
@@ -327,7 +251,6 @@ const NotificationDetailTab = (props) => {
marginBottom: '24px', marginBottom: '24px',
}} }}
> >
{!props.id && (
<Row justify="space-between" align="middle"> <Row justify="space-between" align="middle">
<Col> <Col>
<Button <Button
@@ -339,9 +262,15 @@ const NotificationDetailTab = (props) => {
Back to notification list Back to notification list
</Button> </Button>
</Col> </Col>
<Col>
<Button
icon={<UserOutlined />}
onClick={() => setModalContent('user')}
>
User History
</Button>
</Col>
</Row> </Row>
)}
<div <div
style={{ style={{
backgroundColor: '#f6ffed', backgroundColor: '#f6ffed',
@@ -394,7 +323,7 @@ const NotificationDetailTab = (props) => {
<Text>{notification.title}</Text> <Text>{notification.title}</Text>
<div style={{ marginTop: '2px' }}> <div style={{ marginTop: '2px' }}>
<Text strong style={{ fontSize: '16px' }}> <Text strong style={{ fontSize: '16px' }}>
Error Code {notification.issue} {notification.issue}
</Text> </Text>
</div> </div>
</Col> </Col>
@@ -458,109 +387,71 @@ const NotificationDetailTab = (props) => {
</Card> </Card>
</Col> </Col>
{/* Kolom Kanan: User History */} {/* Kolom Kanan: Log History */}
<Col xs={24} lg={8}> <Col xs={24} lg={8}>
<Card title="User History" size="small" style={{ height: '100%' }}> <LogHistoryCard
<div notificationData={notification}
style={{ logData={logHistoryData}
maxHeight: '400px', loading={logLoading}
overflowY: 'auto',
padding: '2px',
}}
>
<Space
direction="vertical"
size={2}
style={{ width: '100%' }}
>
{getUsersFromNotification(notification).map((user) => (
<Card
key={user.id}
size="small"
style={{ width: '100%', margin: 0 }}
>
<Row align="middle" justify="space-between">
<Col>
<Space align="center">
<Text strong>{user.name}</Text>
<Text>|</Text>
<Text>
<MobileOutlined /> {user.phone}
</Text>
<Text>|</Text>
<Badge
status={
user.status === 'Delivered'
? 'success'
: 'default'
}
text={user.status}
/> />
</Space>
<Divider style={{ margin: '8px 0' }} />
<Space align="center">
{user.status === 'Delivered' ? (
<CheckCircleFilled
style={{ color: '#52c41a' }}
/>
) : (
<ClockCircleOutlined
style={{ color: '#faad14' }}
/>
)}
<Text type="secondary">
{user.status === 'Delivered'
? 'Success Delivered at'
: 'Status '}{' '}
{user.timestamp}
</Text>
</Space>
</Col>
<Col>
<Col>
<Button
type="primary"
ghost
icon={<SendOutlined />}
onClick={async () => {
await resendChatByUser(
user.id,
user.phone
);
}}
>
Resend
</Button>
</Col>
</Col>
</Row>
</Card>
))}
</Space>
</div>
</Card>
</Col> </Col>
</Row> </Row>
<Row gutter={[8, 8]}> <Row gutter={[8, 8]} style={{ marginBottom: 'px' }}>
<Col xs={24} md={8}> <Col xs={24} md={8}>
<div>
<Card <Card
hoverable hoverable
bodyStyle={{ padding: '12px'}} bodyStyle={{ padding: '12px', textAlign: 'center' }}
> >
<Space> <Space>
<BookOutlined <BookOutlined
style={{ fontSize: '16px', color: '#1890ff' }} style={{ fontSize: '16px', color: '#1890ff' }}
/> />
<Text <Text strong style={{ fontSize: '16px', color: '#262626' }}>
strong
style={{ fontSize: '16px', color: '#262626' }}
>
Handling Guideline Handling Guideline
</Text> </Text>
</Space> </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} 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={[8, 8]} style={{ marginTop: '-12px' }}>
<Col xs={24} md={8}>
<Card
size="small"
title="Guideline Documents"
style={{ height: '100%' }}
>
<Space <Space
direction="vertical" direction="vertical"
size="small" size="small"
@@ -574,8 +465,7 @@ const NotificationDetailTab = (props) => {
.map((sol, index) => ( .map((sol, index) => (
<div <div
key={ key={
sol.brand_code_solution_id || sol.brand_code_solution_id || index
index
} }
> >
{sol.path_document ? ( {sol.path_document ? (
@@ -590,8 +480,7 @@ const NotificationDetailTab = (props) => {
<Text <Text
type="secondary" type="secondary"
style={{ style={{
fontSize: fontSize: '10px',
'10px',
}} }}
> >
PDF PDF
@@ -603,8 +492,7 @@ const NotificationDetailTab = (props) => {
display: 'flex', display: 'flex',
justifyContent: justifyContent:
'space-between', 'space-between',
alignItems: alignItems: 'center',
'center',
}} }}
> >
<div> <div>
@@ -647,11 +535,6 @@ const NotificationDetailTab = (props) => {
sol.text_solution ? ( sol.text_solution ? (
<Card <Card
size="small" size="small"
title={
<Text strong>
{sol.solution_name}:
</Text>
}
bodyStyle={{ bodyStyle={{
padding: '8px 12px', padding: '8px 12px',
marginBottom: '4px', marginBottom: '4px',
@@ -660,8 +543,7 @@ const NotificationDetailTab = (props) => {
<Text <Text
type="secondary" type="secondary"
style={{ style={{
fontSize: fontSize: '10px',
'10px',
}} }}
> >
{sol.type_solution.toUpperCase()} {sol.type_solution.toUpperCase()}
@@ -669,10 +551,12 @@ const NotificationDetailTab = (props) => {
} }
> >
<div> <div>
<Text strong>
{sol.solution_name}:
</Text>
<div <div
style={{ style={{
marginTop: marginTop: '4px',
'4px',
}} }}
> >
{sol.text_solution} {sol.text_solution}
@@ -696,26 +580,13 @@ const NotificationDetailTab = (props) => {
)} )}
</Space> </Space>
</Card> </Card>
</div>
</Col> </Col>
<Col xs={24} md={8}> <Col xs={24} md={8}>
<div>
<Card <Card
hoverable size="small"
bodyStyle={{ padding: '12px'}} title="Required Spare Parts"
style={{ height: '100%' }}
> >
<Space>
<ToolOutlined
style={{ fontSize: '16px', color: '#1890ff' }}
/>
<Text
strong
style={{ fontSize: '16px', color: '#262626' }}
>
Spare Part
</Text>
</Space>
<Space <Space
direction="vertical" direction="vertical"
size="small" size="small"
@@ -799,11 +670,9 @@ const NotificationDetailTab = (props) => {
marginTop: '8px', marginTop: '8px',
}} }}
> >
Kode:{' '} Kode: {sparepart.sparepart_code}{' '}
{sparepart.sparepart_code} | | Qty: {sparepart.sparepart_qty}{' '}
Qty:{' '} | Unit:{' '}
{sparepart.sparepart_qty} |
Unit:{' '}
{sparepart.sparepart_unit} {sparepart.sparepart_unit}
</div> </div>
</Space> </Space>
@@ -824,23 +693,9 @@ const NotificationDetailTab = (props) => {
)} )}
</Space> </Space>
</Card> </Card>
</div>
</Col> </Col>
<Col xs={24} md={8}> <Col span={8}>
<div> <Card size="small" style={{ height: '100%' }}>
<Card bodyStyle={{ padding: '12px'}}>
<Space>
<HistoryOutlined
style={{ fontSize: '16px', color: '#1890ff' }}
/>
<Text
strong
style={{ fontSize: '16px', color: '#262626' }}
>
Log Activity
</Text>
</Space>
<Space <Space
direction="vertical" direction="vertical"
size="small" size="small"
@@ -850,9 +705,7 @@ const NotificationDetailTab = (props) => {
size="small" size="small"
bodyStyle={{ bodyStyle={{
padding: '8px 12px', padding: '8px 12px',
backgroundColor: isAddingLog backgroundColor: isAddingLog ? '#fafafa' : '#fff',
? '#fafafa'
: '#fff',
}} }}
> >
<Space <Space
@@ -862,21 +715,14 @@ const NotificationDetailTab = (props) => {
> >
{isAddingLog && ( {isAddingLog && (
<> <>
<Text <Text strong style={{ fontSize: '12px' }}>
strong
style={{ fontSize: '12px' }}
>
Add New Log / Update Progress Add New Log / Update Progress
</Text> </Text>
<Input.TextArea <Input.TextArea
rows={2} rows={2}
placeholder="Tuliskan update penanganan di sini..." placeholder="Tuliskan update penanganan di sini..."
value={newLogDescription} value={newLogDescription}
onChange={(e) => onChange={(e) => setNewLogDescription(e.target.value)}
setNewLogDescription(
e.target.value
)
}
disabled={submitLoading} disabled={submitLoading}
/> />
</> </>
@@ -885,18 +731,8 @@ const NotificationDetailTab = (props) => {
type={isAddingLog ? 'primary' : 'dashed'} type={isAddingLog ? 'primary' : 'dashed'}
size="small" size="small"
block block
icon={ icon={submitLoading ? <LoadingOutlined /> : (!isAddingLog && <PlusOutlined />)}
submitLoading ? ( onClick={isAddingLog ? handleSubmitLog : () => setIsAddingLog(true)}
<LoadingOutlined />
) : (
!isAddingLog && <PlusOutlined />
)
}
onClick={
isAddingLog
? handleSubmitLog
: () => setIsAddingLog(true)
}
loading={submitLoading} loading={submitLoading}
disabled={submitLoading} disabled={submitLoading}
> >
@@ -927,27 +763,29 @@ const NotificationDetailTab = (props) => {
> >
<Paragraph <Paragraph
style={{ fontSize: '12px', margin: 0 }} style={{ fontSize: '12px', margin: 0 }}
// ellipsis={{ rows: 2 }} ellipsis={{ rows: 2 }}
> >
<Text strong>{log.addedBy.name}:</Text>{' '} <Text strong>{log.addedBy.name}:</Text>{' '}
{log.description} {log.description}
</Paragraph> </Paragraph>
<Text <Text type="secondary" style={{ fontSize: '11px' }}>
type="secondary"
style={{ fontSize: '11px' }}
>
{log.timestamp} {log.timestamp}
</Text> </Text>
</Card> </Card>
))} ))}
</Space> </Space>
</Card> </Card>
</div>
</Col> </Col>
</Row> </Row>
</Space> </Space>
</Card> </Card>
</Content> </Content>
<UserHistoryModal
visible={modalContent === 'user'}
onCancel={() => setModalContent(null)}
notificationData={notification}
/>
</Layout> </Layout>
); );
}; };

View File

@@ -9,8 +9,6 @@ import {
import { getAllPlantSection } from '../../../../api/master-plant-section'; import { getAllPlantSection } from '../../../../api/master-plant-section';
import jsPDF from 'jspdf'; import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable'; import autoTable from 'jspdf-autotable';
import ExcelJS from 'exceljs';
import { saveAs } from 'file-saver';
const { Text } = Typography; const { Text } = Typography;
@@ -56,9 +54,9 @@ const ListReport = memo(function ListReport(props) {
}; };
const fetchData = async (page = 1, pageSize = 10, showModal = false) => { const fetchData = async (page = 1, pageSize = 10, showModal = false) => {
// if (!plantSubSection) { if (!plantSubSection) {
// return; return;
// } }
if (showModal) { if (showModal) {
setIsLoadingModal(true); setIsLoadingModal(true);
@@ -197,34 +195,8 @@ const ListReport = memo(function ListReport(props) {
fetchData(pagination.current, pagination.pageSize, false); fetchData(pagination.current, pagination.pageSize, false);
}; };
const handleSearch = async () => { const handleSearch = () => {
setIsLoadingModal(true); fetchData(1, pagination.pageSize, true);
try {
const formattedDateStart = startDate.format('YYYY-MM-DD');
const formattedDateEnd = endDate.format('YYYY-MM-DD');
const params = new URLSearchParams({
plant_sub_section_id: plantSubSection,
from: formattedDateStart,
to: formattedDateEnd,
interval: periode,
page: 1,
limit: 1000,
});
const pivotResponse = await getAllHistoryValueReportPivot(params);
// Jika response sukses, proses data
if (pivotResponse && pivotResponse.data) {
await fetchData(1, pagination.pageSize, false);
}
} catch (error) {
console.error('Error fetching data:', error);
// Error akan ditangkap oleh api-request.js dan muncul Swal otomatis
} finally {
setIsLoadingModal(false);
}
}; };
const handleReset = () => { const handleReset = () => {
@@ -275,168 +247,6 @@ const ListReport = memo(function ListReport(props) {
{ value: 120, label: '2 Hour', disabled: false }, { value: 120, label: '2 Hour', disabled: false },
]; ];
const exportToExcel = async () => {
if (pivotData.length === 0) {
alert('No data to export');
return;
}
const tagMapping = {};
valueReportData.forEach(item => {
if (item.tag_name && item.tag_number) {
tagMapping[item.tag_name] = item.tag_number;
}
});
const selectedSection = plantSubSectionList.find(
item => item.plant_sub_section_id === plantSubSection
);
const sectionName = selectedSection ? selectedSection.plant_sub_section_name : 'Unknown';
// Buat struktur pivot yang sama seperti di tabel
const timeMap = new Map();
const tagSet = new Set();
pivotData.forEach((row) => {
const tagName = row.id;
tagSet.add(tagName);
const dataPoints = row.data || [];
dataPoints.forEach((item) => {
if (item && typeof item === 'object' && 'x' in item && 'y' in item) {
const datetime = item.x;
if (!timeMap.has(datetime)) {
timeMap.set(datetime, {});
}
timeMap.get(datetime)[tagName] = item.y;
}
});
});
const sortedTimes = Array.from(timeMap.keys()).sort();
const sortedTags = Array.from(tagSet).sort();
const pivotTableData = sortedTimes.map((datetime) => {
const rowData = {
datetime: datetime,
};
sortedTags.forEach((tagName) => {
rowData[tagName] = timeMap.get(datetime)[tagName];
});
return rowData;
});
console.log('Excel Pivot data:', pivotTableData.slice(0, 5));
console.log('Total rows for Excel:', pivotTableData.length);
const workbook = new ExcelJS.Workbook();
const ws = workbook.addWorksheet('Pivot Report');
// Buat header info (3 baris pertama)
ws.addRow(['PT. PUPUK INDONESIA UTILITAS']);
ws.addRow(['GRESIK GAS COGENERATION PLANT']);
ws.addRow([`${sectionName}`]);
ws.addRow([]); // Baris kosong sebagai pemisah
// Buat header kolom dengan tag number
const headerRow = [
'Datetime',
...sortedTags.map(tag => tagMapping[tag] || tag)
];
ws.addRow(headerRow);
// Buat data rows - PERBAIKAN: Simpan sebagai number murni
pivotTableData.forEach((rowData) => {
const row = [dayjs(rowData.datetime).format('DD-MM-YYYY HH:mm')];
sortedTags.forEach((tagName) => {
const value = rowData[tagName];
// Simpan sebagai number, bukan string
if (value !== undefined && value !== null) {
row.push(Number(value));
} else {
row.push('-');
}
});
ws.addRow(row);
});
// Set column widths
ws.getColumn(1).width = 18; // Datetime column
for (let i = 2; i <= sortedTags.length + 1; i++) {
ws.getColumn(i).width = 12; // Tag columns
}
// Merge cells untuk header info
const totalCols = sortedTags.length + 1;
ws.mergeCells(1, 1, 1, totalCols); // Baris 1
ws.mergeCells(2, 1, 2, totalCols); // Baris 2
ws.mergeCells(3, 1, 3, totalCols); // Baris 3
// Style untuk header info (3 baris pertama - bold dan center)
for (let i = 1; i <= 3; i++) {
const cell = ws.getCell(i, 1);
cell.font = { bold: true, size: 12 };
cell.alignment = { horizontal: 'center', vertical: 'middle', wrapText: true };
}
// Style untuk header kolom (bold, background color, center, border)
const headerRowIndex = 5; // Baris header
for (let col = 1; col <= totalCols; col++) {
const cell = ws.getCell(headerRowIndex, col);
cell.font = { bold: true, size: 11 };
cell.fill = {
type: 'pattern',
pattern: 'solid',
fgColor: { argb: 'FFDCDCDC' }
};
cell.alignment = { horizontal: 'center', vertical: 'middle', wrapText: true };
cell.border = {
top: { style: 'thin', color: { argb: 'FF000000' } },
bottom: { style: 'thin', color: { argb: 'FF000000' } },
left: { style: 'thin', color: { argb: 'FF000000' } },
right: { style: 'thin', color: { argb: 'FF000000' } }
};
}
// Style untuk data cells (border dan alignment) - PERBAIKAN: Format number dengan 2 desimal
for (let row = headerRowIndex + 1; row <= ws.rowCount; row++) {
for (let col = 1; col <= totalCols; col++) {
const cell = ws.getCell(row, col);
cell.alignment = {
horizontal: 'center',
vertical: 'middle',
wrapText: true
};
cell.border = {
top: { style: 'thin', color: { argb: 'FF000000' } },
bottom: { style: 'thin', color: { argb: 'FF000000' } },
left: { style: 'thin', color: { argb: 'FF000000' } },
right: { style: 'thin', color: { argb: 'FF000000' } }
};
// Format number dengan 2 desimal untuk kolom value (kolom 2 dst)
if (col > 1) {
const cellValue = cell.value;
// Hanya set format number jika cell berisi angka
if (typeof cellValue === 'number') {
cell.numFmt = '0.00';
}
}
}
}
// Generate file name
const fileName = `Report_Pivot_${startDate.format('DD-MM-YYYY')}_to_${endDate.format('DD-MM-YYYY')}.xlsx`;
// Save file
const buffer = await workbook.xlsx.writeBuffer();
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
saveAs(blob, fileName);
};
const exportToPDF = async () => { const exportToPDF = async () => {
if (pivotData.length === 0) { if (pivotData.length === 0) {
alert('No data to export'); alert('No data to export');
@@ -583,7 +393,7 @@ const ListReport = memo(function ListReport(props) {
doc.setFontSize(9); doc.setFontSize(9);
doc.setFont('helvetica', 'bold'); doc.setFont('helvetica', 'bold');
doc.setFontSize(10); doc.setFontSize(10);
doc.text(`${sectionName}`, marginLeft + col1Width + col2Width / 2, 38, { align: 'center' }); doc.text(`Plant Section : ${sectionName}`, marginLeft + col1Width + col2Width / 2, 41, { align: 'center' });
}; };
// Hitung total kolom tag chunks // Hitung total kolom tag chunks
@@ -724,7 +534,7 @@ const ListReport = memo(function ListReport(props) {
autoTable(doc, { autoTable(doc, {
head: [headerRow], head: [headerRow],
body: pdfRows, body: pdfRows,
startY: isFirstPage ? 43 : 15, startY: isFirstPage ? 50 : 15,
theme: 'grid', theme: 'grid',
rowPageBreak: 'avoid', rowPageBreak: 'avoid',
styles: { styles: {
@@ -732,7 +542,7 @@ const ListReport = memo(function ListReport(props) {
cellPadding: 1.5, cellPadding: 1.5,
minCellHeight: 8, minCellHeight: 8,
lineColor: [0, 0, 0], lineColor: [0, 0, 0],
lineWidth: 0.5, lineWidth: 0.1,
halign: 'center', halign: 'center',
valign: 'middle', valign: 'middle',
overflow: 'linebreak', overflow: 'linebreak',
@@ -744,7 +554,7 @@ const ListReport = memo(function ListReport(props) {
halign: 'center', halign: 'center',
valign: 'middle', valign: 'middle',
lineColor: [0, 0, 0], lineColor: [0, 0, 0],
lineWidth: 0.5, lineWidth: 0.3,
}, },
columnStyles: { columnStyles: {
0: { 0: {
@@ -884,23 +694,11 @@ const ListReport = memo(function ListReport(props) {
type="primary" type="primary"
icon={<DownloadOutlined />} icon={<DownloadOutlined />}
onClick={exportToPDF} onClick={exportToPDF}
disabled={pivotData.length === 0} disabled={false}
style={{ backgroundColor: '#1890ff', borderColor: '#1890ff' }}
> >
Export PDF Export PDF
</Button> </Button>
</Col> </Col>
<Col>
<Button
type="primary"
icon={<DownloadOutlined />}
onClick={exportToExcel}
disabled={pivotData.length === 0}
style={{ backgroundColor: '#28a745', borderColor: '#28a745' }}
>
Export Excel
</Button>
</Col>
<Col> <Col>
<Button <Button
onClick={handleReset} onClick={handleReset}

View File

@@ -130,26 +130,9 @@ const ReportTrending = memo(function ReportTrending(props) {
} }
}; };
// Fungsi untuk menentukan apakah rentang tanggal lebih dari 1 hari
const isMultipleDays = () => {
return !startDate.isSame(endDate, 'day');
};
// Format sumbu X yang otomatis menyesuaikan
const formatXAxis = (tickItem) => { const formatXAxis = (tickItem) => {
const date = new Date(tickItem); const date = new Date(tickItem);
const hours = date.getHours().toString().padStart(2, '0'); return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
const minutes = date.getMinutes().toString().padStart(2, '0');
// Jika rentang lebih dari 1 hari, tampilkan tanggal + waktu
if (isMultipleDays()) {
const day = date.getDate().toString().padStart(2, '0');
const month = (date.getMonth() + 1).toString().padStart(2, '0');
return `${day}/${month} ${hours}:${minutes}`;
}
// Jika hanya 1 hari, tampilkan waktu saja
return `${hours}:${minutes}`;
}; };
const CustomTooltip = ({ active, payload, label }) => { const CustomTooltip = ({ active, payload, label }) => {

View File

@@ -115,7 +115,7 @@ const ChangePasswordModal = (props) => {
try { try {
const response = await changePassword(props.selectedUser.user_id, formData.newPassword); const response = await changePassword(props.selectedUser.user_id, formData.newPassword);
// console.log('Change Password Response:', response); console.log('Change Password Response:', response);
if (response && response.statusCode === 200) { if (response && response.statusCode === 200) {
NotifOk({ NotifOk({

View File

@@ -220,27 +220,35 @@ const DetailUser = (props) => {
// For update mode: only send email if it has changed // For update mode: only send email if it has changed
if (FormData.user_id) { if (FormData.user_id) {
// Only include email if it has changed from original
if (FormData.user_email !== originalEmail) { if (FormData.user_email !== originalEmail) {
payload.user_email = FormData.user_email; payload.user_email = FormData.user_email;
} }
// Add is_active for update mode
payload.is_active = FormData.is_active; payload.is_active = FormData.is_active;
} else { } else {
// For create mode: always send email
payload.user_email = FormData.user_email; payload.user_email = FormData.user_email;
} }
// Only add role_id if it exists (backend requires number >= 1, no null)
if (FormData.role_id) { if (FormData.role_id) {
payload.role_id = FormData.role_id; payload.role_id = FormData.role_id;
} }
// Add password and name for new user (create mode) // Add password and name for new user (create mode)
if (!FormData.user_id) { if (!FormData.user_id) {
payload.user_name = FormData.user_name; payload.user_name = FormData.user_name; // Username only for create
payload.user_password = FormData.password; payload.user_password = FormData.password; // Backend expects 'user_password'
// Don't send confirmPassword, is_sa for create
} }
// For update mode:
// - Don't send 'user_name' (username is immutable)
// - is_active is now sent for update mode
// - Only send email if it has changed
try { try {
// console.log('Payload being sent:', payload); console.log('Payload being sent:', payload);
let response; let response;
if (!FormData.user_id) { if (!FormData.user_id) {
@@ -249,10 +257,11 @@ const DetailUser = (props) => {
response = await updateUser(FormData.user_id, payload); response = await updateUser(FormData.user_id, payload);
} }
// console.log('Save User Response:', response); console.log('Save User Response:', response);
// Check if response is successful // Check if response is successful
if (response && (response.statusCode === 200 || response.statusCode === 201)) { if (response && (response.statusCode === 200 || response.statusCode === 201)) {
// If in edit mode and newPassword is provided, change password
if (FormData.user_id && FormData.newPassword) { if (FormData.user_id && FormData.newPassword) {
try { try {
const passwordResponse = await changePassword( const passwordResponse = await changePassword(
@@ -376,9 +385,9 @@ const DetailUser = (props) => {
search: '', search: '',
}); });
// console.log('Fetching roles with params:', queryParams.toString()); console.log('Fetching roles with params:', queryParams.toString());
const response = await getAllRole(queryParams); const response = await getAllRole(queryParams);
// console.log('Fetched roles response:', response); console.log('Fetched roles response:', response);
// Handle different response structures // Handle different response structures
if (response && response.data) { if (response && response.data) {
@@ -399,7 +408,7 @@ const DetailUser = (props) => {
} }
setRoleList(roles); setRoleList(roles);
// console.log('Setting role list:', roles); console.log('Setting role list:', roles);
} else { } else {
// Add mock data as fallback // Add mock data as fallback
console.warn('No response data, using mock data'); console.warn('No response data, using mock data');
@@ -409,7 +418,7 @@ const DetailUser = (props) => {
{ role_id: 3, role_name: 'User', role_level: 3 }, { role_id: 3, role_name: 'User', role_level: 3 },
]; ];
setRoleList(mockRoles); setRoleList(mockRoles);
// console.log('Setting mock role list:', mockRoles); console.log('Setting mock role list:', mockRoles);
} }
} catch (error) { } catch (error) {
console.error('Error fetching roles:', error); console.error('Error fetching roles:', error);
@@ -420,7 +429,7 @@ const DetailUser = (props) => {
{ role_id: 3, role_name: 'User', role_level: 3 }, { role_id: 3, role_name: 'User', role_level: 3 },
]; ];
setRoleList(mockRoles); setRoleList(mockRoles);
// console.log('Setting mock role list due to error:', mockRoles); console.log('Setting mock role list due to error:', mockRoles);
// Only show error notification if we don't have fallback data // Only show error notification if we don't have fallback data
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
@@ -1137,7 +1146,9 @@ const DetailUser = (props) => {
))} ))}
</Select> </Select>
{errors.role_id && ( {errors.role_id && (
<Text style={{ color: 'red', fontSize: '12px' }}>{errors.role_id}</Text> <Text style={{ color: 'red', fontSize: '12px' }}>
{errors.role_id}
</Text>
)} )}
</div> </div>
</div> </div>