clean code master plant sub section and master device
This commit is contained in:
@@ -1,4 +1,5 @@
|
|||||||
VITE_API_SERVER=http://36.66.16.49:9528/api
|
VITE_API_SERVER=http://localhost:9530/api
|
||||||
|
# VITE_API_SERVER=https://117.102.231.130:9528/api
|
||||||
VITE_MQTT_SERVER=ws://localhost:1884
|
VITE_MQTT_SERVER=ws://localhost:1884
|
||||||
VITE_MQTT_USERNAME=
|
VITE_MQTT_USERNAME=
|
||||||
VITE_MQTT_PASSWORD=
|
VITE_MQTT_PASSWORD=
|
||||||
|
|||||||
71
src/Utils/validate.js
Normal file
71
src/Utils/validate.js
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
// utils/validate.js
|
||||||
|
|
||||||
|
// Daftar aturan validasi
|
||||||
|
const validationRules = [
|
||||||
|
{ field: 'name', label: 'Nama', required: true },
|
||||||
|
{
|
||||||
|
field: 'email',
|
||||||
|
label: 'Email',
|
||||||
|
required: true,
|
||||||
|
pattern: /\S+@\S+\.\S+/,
|
||||||
|
patternMessage: 'Format email tidak valid',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
field: 'age',
|
||||||
|
label: 'Umur',
|
||||||
|
required: true,
|
||||||
|
validator: (v) => !isNaN(v) && Number(v) >= 18,
|
||||||
|
message: 'Umur harus angka dan minimal 18 tahun',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fungsi validasi dinamis berbasis array objek aturan.
|
||||||
|
* @param {Object} data - data form (misal { name: '', email: '' })
|
||||||
|
* @param {Array} rules - array aturan validasi
|
||||||
|
* @returns {Object} errors - object berisi pesan error per field
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const validateRun = (data, rules, onError) => {
|
||||||
|
const errors = {};
|
||||||
|
const messages = [];
|
||||||
|
|
||||||
|
const ipRegex = /^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$/;
|
||||||
|
|
||||||
|
rules.forEach((rule) => {
|
||||||
|
const value = data[rule.field]?.toString().trim();
|
||||||
|
const fieldErrors = [];
|
||||||
|
|
||||||
|
if (rule.required && !value) {
|
||||||
|
fieldErrors.push(`${rule.label} wajib diisi`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ✅ IP Address check
|
||||||
|
if (rule.ip && value && !ipRegex.test(value)) {
|
||||||
|
fieldErrors.push(`${rule.label} harus berupa alamat IP yang valid`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rule.pattern && value && !rule.pattern.test(value)) {
|
||||||
|
fieldErrors.push(rule.patternMessage || `${rule.label} tidak valid`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rule.validator && value && !rule.validator(value)) {
|
||||||
|
fieldErrors.push(rule.message || `${rule.label} tidak valid`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Gabungkan error satu field jadi satu string (pisah baris)
|
||||||
|
if (fieldErrors.length > 0) {
|
||||||
|
errors[rule.field] = fieldErrors.join("\n");
|
||||||
|
messages.push(...fieldErrors);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Jika ada error total, tampilkan callback dan return false
|
||||||
|
|
||||||
|
if (messages.length > 0) {
|
||||||
|
if (onError) onError(messages.join("\n"));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
|
||||||
|
};
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
import { SendRequest } from '../components/Global/ApiRequest';
|
|
||||||
|
|
||||||
const getTotal = async (query = '') => {
|
|
||||||
const prefix = `${query ? `?${query}` : ''}`;
|
|
||||||
const fullUrl = `${import.meta.env.VITE_API_SERVER}/dashboard/${prefix}`;
|
|
||||||
try {
|
|
||||||
const response = await SendRequest({
|
|
||||||
method: 'get',
|
|
||||||
prefix: `dashboard/${prefix}`,
|
|
||||||
});
|
|
||||||
return response;
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`[API Call] Failed: GET ${fullUrl}`, error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getTotalPermit = async (query = '') => {
|
|
||||||
const prefix = `dashboard/permit-total${query ? `?${query}` : ''}`;
|
|
||||||
const fullUrl = `${import.meta.env.VITE_API_SERVER}/${prefix}`;
|
|
||||||
try {
|
|
||||||
const response = await SendRequest({
|
|
||||||
method: 'get',
|
|
||||||
prefix,
|
|
||||||
});
|
|
||||||
return response;
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`[API Call] Failed: GET ${fullUrl}`, error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getTotalPermitPerYear = async (query = '') => {
|
|
||||||
const prefix = `dashboard/permit-breakdown${query ? `?${query}` : ''}`;
|
|
||||||
const fullUrl = `${import.meta.env.VITE_API_SERVER}/${prefix}`;
|
|
||||||
try {
|
|
||||||
const response = await SendRequest({
|
|
||||||
method: 'get',
|
|
||||||
prefix,
|
|
||||||
});
|
|
||||||
return response;
|
|
||||||
} catch (error) {
|
|
||||||
console.error(`[API Call] Failed: GET ${fullUrl}`, error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export { getTotal, getTotalPermit, getTotalPermitPerYear };
|
|
||||||
@@ -1,55 +1,41 @@
|
|||||||
import { SendRequest } from '../components/Global/ApiRequest';
|
import { SendRequest } from '../components/Global/ApiRequest';
|
||||||
|
|
||||||
const getAllJadwalShift = async (queryParams) => {
|
const getAllJadwalShift = async (queryParams) => {
|
||||||
try {
|
const response = await SendRequest({
|
||||||
const response = await SendRequest({
|
method: 'get',
|
||||||
method: 'get',
|
prefix: `jadwal-shift?${queryParams.toString()}`,
|
||||||
prefix: `jadwal-shift?${queryParams.toString()}`,
|
});
|
||||||
});
|
|
||||||
return response;
|
return response.data;
|
||||||
} catch (error) {
|
};
|
||||||
console.error('getAllJadwalShift error:', error);
|
|
||||||
return {
|
const getJadwalShiftById = async (id) => {
|
||||||
status: 500,
|
const response = await SendRequest({
|
||||||
data: {
|
method: 'get',
|
||||||
data: [],
|
prefix: `jadwal-shift/${id}`,
|
||||||
paging: {
|
});
|
||||||
page: 1,
|
|
||||||
limit: 10,
|
return response.data;
|
||||||
total: 0,
|
|
||||||
page_total: 0
|
|
||||||
},
|
|
||||||
total: 0
|
|
||||||
},
|
|
||||||
error: error.message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const createJadwalShift = async (queryParams) => {
|
const createJadwalShift = async (queryParams) => {
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'post',
|
method: 'post',
|
||||||
prefix: `jadwal-shift`,
|
prefix: `jadwal-shift`,
|
||||||
data: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
return response.data;
|
||||||
data: response.data,
|
|
||||||
message: response.message
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateJadwalShift = async (id, queryParams) => {
|
const updateJadwalShift = async (id, queryParams) => {
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'put',
|
method: 'put',
|
||||||
prefix: `jadwal-shift/${id}`,
|
prefix: `jadwal-shift/${id}`,
|
||||||
data: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
return response.data;
|
||||||
data: response.data,
|
|
||||||
message: response.message
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteJadwalShift = async (id) => {
|
const deleteJadwalShift = async (id) => {
|
||||||
@@ -57,11 +43,13 @@ const deleteJadwalShift = async (id) => {
|
|||||||
method: 'delete',
|
method: 'delete',
|
||||||
prefix: `jadwal-shift/${id}`,
|
prefix: `jadwal-shift/${id}`,
|
||||||
});
|
});
|
||||||
return {
|
return response.data;
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export { getAllJadwalShift, createJadwalShift, updateJadwalShift, deleteJadwalShift };
|
export {
|
||||||
|
getAllJadwalShift,
|
||||||
|
getJadwalShiftById,
|
||||||
|
createJadwalShift,
|
||||||
|
updateJadwalShift,
|
||||||
|
deleteJadwalShift,
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
import { SendRequest } from '../components/Global/ApiRequest';
|
|
||||||
|
|
||||||
const getAllApd = async (queryParams) => {
|
|
||||||
const response = await SendRequest({
|
|
||||||
method: 'get',
|
|
||||||
prefix: `apd?${queryParams.toString()}`,
|
|
||||||
});
|
|
||||||
return response;
|
|
||||||
};
|
|
||||||
|
|
||||||
const createApd = async (queryParams) => {
|
|
||||||
const response = await SendRequest({
|
|
||||||
method: 'post',
|
|
||||||
prefix: `apd`,
|
|
||||||
params: queryParams,
|
|
||||||
});
|
|
||||||
return response.data;
|
|
||||||
};
|
|
||||||
|
|
||||||
const updateApd = async (vendor_id, queryParams) => {
|
|
||||||
const response = await SendRequest({
|
|
||||||
method: 'put',
|
|
||||||
prefix: `apd/${vendor_id}`,
|
|
||||||
params: queryParams,
|
|
||||||
});
|
|
||||||
return response.data;
|
|
||||||
};
|
|
||||||
|
|
||||||
const deleteApd = async (queryParams) => {
|
|
||||||
const response = await SendRequest({
|
|
||||||
method: 'delete',
|
|
||||||
prefix: `apd/${queryParams}`,
|
|
||||||
});
|
|
||||||
return response.data;
|
|
||||||
};
|
|
||||||
|
|
||||||
const getJenisPermit = async () => {
|
|
||||||
const response = await SendRequest({
|
|
||||||
method: 'get',
|
|
||||||
prefix: `apd/jenis-permit`,
|
|
||||||
});
|
|
||||||
return response.data;
|
|
||||||
};
|
|
||||||
|
|
||||||
export { getAllApd, createApd, updateApd, deleteApd, getJenisPermit };
|
|
||||||
@@ -1,70 +1,12 @@
|
|||||||
import { SendRequest } from '../components/Global/ApiRequest';
|
import { SendRequest } from '../components/Global/ApiRequest';
|
||||||
|
|
||||||
const getAllBrands = async (queryParams) => {
|
const getAllBrands = async (queryParams) => {
|
||||||
try {
|
const response = await SendRequest({
|
||||||
const response = await SendRequest({
|
method: 'get',
|
||||||
method: 'get',
|
prefix: `brand?${queryParams.toString()}`,
|
||||||
prefix: `brand?${queryParams.toString()}`,
|
});
|
||||||
});
|
|
||||||
if (response.paging) {
|
|
||||||
const totalData = response.data?.[0]?.total_data || response.rows || response.data?.length || 0;
|
|
||||||
|
|
||||||
return {
|
return response.data;
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: response.data || [],
|
|
||||||
paging: {
|
|
||||||
page: response.paging.current_page || 1,
|
|
||||||
limit: response.paging.current_limit || 10,
|
|
||||||
total: totalData,
|
|
||||||
page_total: response.paging.total_page || Math.ceil(totalData / (response.paging.current_limit || 10))
|
|
||||||
},
|
|
||||||
total: totalData
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const params = Object.fromEntries(queryParams);
|
|
||||||
const currentPage = parseInt(params.page) || 1;
|
|
||||||
const currentLimit = parseInt(params.limit) || 10;
|
|
||||||
|
|
||||||
const allData = response.data || [];
|
|
||||||
const totalData = allData.length;
|
|
||||||
|
|
||||||
const startIndex = (currentPage - 1) * currentLimit;
|
|
||||||
const endIndex = startIndex + currentLimit;
|
|
||||||
const paginatedData = allData.slice(startIndex, endIndex);
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: paginatedData,
|
|
||||||
paging: {
|
|
||||||
page: currentPage,
|
|
||||||
limit: currentLimit,
|
|
||||||
total: totalData,
|
|
||||||
page_total: Math.ceil(totalData / currentLimit)
|
|
||||||
},
|
|
||||||
total: totalData
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
console.error('getAllBrands error:', error);
|
|
||||||
return {
|
|
||||||
status: 500,
|
|
||||||
data: {
|
|
||||||
data: [],
|
|
||||||
paging: {
|
|
||||||
page: 1,
|
|
||||||
limit: 10,
|
|
||||||
total: 0,
|
|
||||||
page_total: 0
|
|
||||||
},
|
|
||||||
total: 0
|
|
||||||
},
|
|
||||||
error: error.message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getBrandById = async (id) => {
|
const getBrandById = async (id) => {
|
||||||
@@ -72,6 +14,7 @@ const getBrandById = async (id) => {
|
|||||||
method: 'get',
|
method: 'get',
|
||||||
prefix: `brand/${id}`,
|
prefix: `brand/${id}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
return response.data;
|
return response.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -81,55 +24,27 @@ const createBrand = async (queryParams) => {
|
|||||||
prefix: `brand`,
|
prefix: `brand`,
|
||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
if (Array.isArray(response) && response.length === 0) {
|
|
||||||
return {
|
return response.data;
|
||||||
statusCode: 500,
|
|
||||||
data: null,
|
|
||||||
message: 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data?.[0] || response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateBrand = async (brand_id, queryParams) => {
|
const updateBrand = async (id, queryParams) => {
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'put',
|
method: 'put',
|
||||||
prefix: `brand/${brand_id}`,
|
prefix: `brand/${id}`,
|
||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
if (Array.isArray(response) && response.length === 0) {
|
|
||||||
return {
|
return response.data;
|
||||||
statusCode: 500,
|
|
||||||
data: null,
|
|
||||||
message: 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data?.[0] || response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteBrand = async (queryParams) => {
|
const deleteBrand = async (id) => {
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'delete',
|
method: 'delete',
|
||||||
prefix: `brand/${queryParams}`,
|
prefix: `brand/${id}`,
|
||||||
});
|
});
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
return response.data;
|
||||||
data: response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export { getAllBrands, getBrandById, createBrand, updateBrand, deleteBrand };
|
export { getAllBrands, getBrandById, createBrand, updateBrand, deleteBrand };
|
||||||
|
|||||||
@@ -1,88 +1,12 @@
|
|||||||
import { SendRequest } from '../components/Global/ApiRequest';
|
import { SendRequest } from '../components/Global/ApiRequest';
|
||||||
|
|
||||||
const getAllDevice = async (queryParams) => {
|
const getAllDevice = async (queryParams) => {
|
||||||
try {
|
const response = await SendRequest({
|
||||||
const response = await SendRequest({
|
method: 'get',
|
||||||
method: 'get',
|
prefix: `device?${queryParams.toString()}`,
|
||||||
prefix: `device?${queryParams.toString()}`,
|
});
|
||||||
});
|
|
||||||
console.log('getAllDevice response:', response);
|
|
||||||
console.log('Query params:', queryParams.toString());
|
|
||||||
|
|
||||||
// Backend response structure:
|
return response.data;
|
||||||
// {
|
|
||||||
// statusCode: 200,
|
|
||||||
// data: [...devices],
|
|
||||||
// paging: {
|
|
||||||
// current_page: 1,
|
|
||||||
// current_limit: 10,
|
|
||||||
// total_limit: 50,
|
|
||||||
// total_page: 5
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// Check if backend returns paginated data
|
|
||||||
if (response.paging) {
|
|
||||||
const totalData = response.data?.[0]?.total_data || response.rows || response.data?.length || 0;
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: response.data || [],
|
|
||||||
paging: {
|
|
||||||
page: response.paging.current_page || 1,
|
|
||||||
limit: response.paging.current_limit || 10,
|
|
||||||
total: totalData,
|
|
||||||
page_total: response.paging.total_page || Math.ceil(totalData / (response.paging.current_limit || 10))
|
|
||||||
},
|
|
||||||
total: totalData
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback: If backend returns all data without pagination (old behavior)
|
|
||||||
const params = Object.fromEntries(queryParams);
|
|
||||||
const currentPage = parseInt(params.page) || 1;
|
|
||||||
const currentLimit = parseInt(params.limit) || 10;
|
|
||||||
|
|
||||||
const allData = response.data || [];
|
|
||||||
const totalData = allData.length;
|
|
||||||
|
|
||||||
// Client-side pagination
|
|
||||||
const startIndex = (currentPage - 1) * currentLimit;
|
|
||||||
const endIndex = startIndex + currentLimit;
|
|
||||||
const paginatedData = allData.slice(startIndex, endIndex);
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: paginatedData,
|
|
||||||
paging: {
|
|
||||||
page: currentPage,
|
|
||||||
limit: currentLimit,
|
|
||||||
total: totalData,
|
|
||||||
page_total: Math.ceil(totalData / currentLimit)
|
|
||||||
},
|
|
||||||
total: totalData
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
console.error('getAllDevice error:', error);
|
|
||||||
return {
|
|
||||||
status: 500,
|
|
||||||
data: {
|
|
||||||
data: [],
|
|
||||||
paging: {
|
|
||||||
page: 1,
|
|
||||||
limit: 10,
|
|
||||||
total: 0,
|
|
||||||
page_total: 0
|
|
||||||
},
|
|
||||||
total: 0
|
|
||||||
},
|
|
||||||
error: error.message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getDeviceById = async (id) => {
|
const getDeviceById = async (id) => {
|
||||||
@@ -90,6 +14,7 @@ const getDeviceById = async (id) => {
|
|||||||
method: 'get',
|
method: 'get',
|
||||||
prefix: `device/${id}`,
|
prefix: `device/${id}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
return response.data;
|
return response.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -99,71 +24,27 @@ const createDevice = async (queryParams) => {
|
|||||||
prefix: `device`,
|
prefix: `device`,
|
||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
console.log('createDevice full response:', response);
|
|
||||||
console.log('createDevice payload sent:', queryParams);
|
|
||||||
|
|
||||||
// Backend returns: { statusCode, message, rows, data: [device_object] }
|
return response.data;
|
||||||
// Check if response is empty array (error from SendRequest)
|
|
||||||
if (Array.isArray(response) && response.length === 0) {
|
|
||||||
return {
|
|
||||||
statusCode: 500,
|
|
||||||
data: null,
|
|
||||||
message: 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extract first item from data array
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data?.[0] || response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateDevice = async (device_id, queryParams) => {
|
const updateDevice = async (id, queryParams) => {
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'put',
|
method: 'put',
|
||||||
prefix: `device/${device_id}`,
|
prefix: `device/${id}`,
|
||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
console.log('updateDevice full response:', response);
|
|
||||||
console.log('updateDevice payload sent:', queryParams);
|
|
||||||
|
|
||||||
// Backend returns: { statusCode, message, rows, data: [device_object] }
|
return response.data;
|
||||||
// Check if response is empty array (error from SendRequest)
|
|
||||||
if (Array.isArray(response) && response.length === 0) {
|
|
||||||
return {
|
|
||||||
statusCode: 500,
|
|
||||||
data: null,
|
|
||||||
message: 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extract first item from data array
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data?.[0] || response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteDevice = async (queryParams) => {
|
const deleteDevice = async (id) => {
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'delete',
|
method: 'delete',
|
||||||
prefix: `device/${queryParams}`,
|
prefix: `device/${id}`,
|
||||||
});
|
});
|
||||||
console.log('deleteDevice full response:', response);
|
|
||||||
// Backend returns: { statusCode, message, rows: null, data: true }
|
return response.data;
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export { getAllDevice, getDeviceById, createDevice, updateDevice, deleteDevice };
|
export { getAllDevice, getDeviceById, createDevice, updateDevice, deleteDevice };
|
||||||
|
|||||||
@@ -1,97 +1,12 @@
|
|||||||
import { SendRequest } from '../components/Global/ApiRequest';
|
import { SendRequest } from '../components/Global/ApiRequest';
|
||||||
|
|
||||||
const getAllPlantSection = async (queryParams) => {
|
const getAllPlantSection = async (queryParams) => {
|
||||||
try {
|
const response = await SendRequest({
|
||||||
// Ensure queryParams is URLSearchParams object
|
method: 'get',
|
||||||
const params = queryParams instanceof URLSearchParams ? queryParams : new URLSearchParams(queryParams);
|
prefix: `plant-sub-section?${queryParams.toString()}`,
|
||||||
|
});
|
||||||
|
|
||||||
const response = await SendRequest({
|
return response.data;
|
||||||
method: 'get',
|
|
||||||
prefix: `plant-sub-section?${params.toString()}`,
|
|
||||||
});
|
|
||||||
console.log('getAllPlantSection response:', response);
|
|
||||||
console.log('Query params:', params.toString());
|
|
||||||
|
|
||||||
// Backend response structure:
|
|
||||||
// {
|
|
||||||
// statusCode: 200,
|
|
||||||
// data: [...plantSections],
|
|
||||||
// paging: {
|
|
||||||
// current_page: 1,
|
|
||||||
// current_limit: 10,
|
|
||||||
// total_limit: 50,
|
|
||||||
// total_page: 5
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// Check if backend returns paginated data
|
|
||||||
if (response.paging) {
|
|
||||||
// Extract total_data from first record, or fallback to total_limit or rows
|
|
||||||
const totalData = response.data?.[0]?.total_data || response.paging.total_limit || response.rows || response.data?.length || 0;
|
|
||||||
|
|
||||||
// Use total_limit as total count, handle 0 values for page/limit
|
|
||||||
const currentPage = response.paging.current_page || 1;
|
|
||||||
const currentLimit = response.paging.current_limit || 10;
|
|
||||||
const totalPages = response.paging.total_page || Math.ceil(totalData / currentLimit);
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: response.data || [],
|
|
||||||
paging: {
|
|
||||||
page: currentPage,
|
|
||||||
limit: currentLimit,
|
|
||||||
total: totalData,
|
|
||||||
page_total: totalPages
|
|
||||||
},
|
|
||||||
total: totalData
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback: If backend returns all data without pagination (old behavior)
|
|
||||||
const parsedParams = Object.fromEntries(params);
|
|
||||||
const currentPage = parseInt(parsedParams.page) || 1;
|
|
||||||
const currentLimit = parseInt(parsedParams.limit) || 10;
|
|
||||||
|
|
||||||
const allData = response.data || [];
|
|
||||||
const totalData = allData.length;
|
|
||||||
|
|
||||||
// Client-side pagination
|
|
||||||
const startIndex = (currentPage - 1) * currentLimit;
|
|
||||||
const endIndex = startIndex + currentLimit;
|
|
||||||
const paginatedData = allData.slice(startIndex, endIndex);
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: paginatedData,
|
|
||||||
paging: {
|
|
||||||
page: currentPage,
|
|
||||||
limit: currentLimit,
|
|
||||||
total: totalData,
|
|
||||||
page_total: Math.ceil(totalData / currentLimit)
|
|
||||||
},
|
|
||||||
total: totalData
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
console.error('getAllPlantSection error:', error);
|
|
||||||
return {
|
|
||||||
status: 500,
|
|
||||||
data: {
|
|
||||||
data: [],
|
|
||||||
paging: {
|
|
||||||
page: 1,
|
|
||||||
limit: 10,
|
|
||||||
total: 0,
|
|
||||||
page_total: 0
|
|
||||||
},
|
|
||||||
total: 0
|
|
||||||
},
|
|
||||||
error: error.message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getPlantSectionById = async (id) => {
|
const getPlantSectionById = async (id) => {
|
||||||
@@ -99,6 +14,7 @@ const getPlantSectionById = async (id) => {
|
|||||||
method: 'get',
|
method: 'get',
|
||||||
prefix: `plant-sub-section/${id}`,
|
prefix: `plant-sub-section/${id}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
return response.data;
|
return response.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -108,80 +24,33 @@ const createPlantSection = async (queryParams) => {
|
|||||||
prefix: `plant-sub-section`,
|
prefix: `plant-sub-section`,
|
||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
console.log('createPlantSection full response:', response);
|
|
||||||
console.log('createPlantSection payload sent:', queryParams);
|
|
||||||
|
|
||||||
// Check if response has error flag
|
return response.data;
|
||||||
if (response.error) {
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 500,
|
|
||||||
data: null,
|
|
||||||
message: response.message || 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backend returns: { statusCode, message, rows, data: [plantSection_object] }
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data?.[0] || response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const updatePlantSection = async (plant_section_id, queryParams) => {
|
const updatePlantSection = async (id, queryParams) => {
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'put',
|
method: 'put',
|
||||||
prefix: `plant-sub-section/${plant_section_id}`,
|
prefix: `plant-sub-section/${id}`,
|
||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
console.log('updatePlantSection full response:', response);
|
|
||||||
console.log('updatePlantSection payload sent:', queryParams);
|
|
||||||
|
|
||||||
// Check if response has error flag
|
return response.data;
|
||||||
if (response.error) {
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 500,
|
|
||||||
data: null,
|
|
||||||
message: response.message || 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backend returns: { statusCode, message, rows, data: [plantSection_object] }
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data?.[0] || response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const deletePlantSection = async (queryParams) => {
|
const deletePlantSection = async (id) => {
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'delete',
|
method: 'delete',
|
||||||
prefix: `plant-sub-section/${queryParams}`,
|
prefix: `plant-sub-section/${id}`,
|
||||||
});
|
});
|
||||||
console.log('deletePlantSection full response:', response);
|
|
||||||
|
|
||||||
// Check if response has error flag
|
return response.data;
|
||||||
if (response.error) {
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 500,
|
|
||||||
data: null,
|
|
||||||
message: response.message || 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backend returns: { statusCode, message, rows: null, data: true }
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export { getAllPlantSection, getPlantSectionById, createPlantSection, updatePlantSection, deletePlantSection };
|
export {
|
||||||
|
getAllPlantSection,
|
||||||
|
getPlantSectionById,
|
||||||
|
createPlantSection,
|
||||||
|
updatePlantSection,
|
||||||
|
deletePlantSection,
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,95 +1,12 @@
|
|||||||
import { SendRequest } from '../components/Global/ApiRequest';
|
import { SendRequest } from '../components/Global/ApiRequest';
|
||||||
|
|
||||||
const getAllShift = async (queryParams) => {
|
const getAllShift = async (queryParams) => {
|
||||||
try {
|
const response = await SendRequest({
|
||||||
const response = await SendRequest({
|
method: 'get',
|
||||||
method: 'get',
|
prefix: `shift?${queryParams.toString()}`,
|
||||||
prefix: `shift?${queryParams.toString()}`,
|
});
|
||||||
});
|
|
||||||
console.log('getAllShift response:', response);
|
|
||||||
console.log('Query params:', queryParams.toString());
|
|
||||||
|
|
||||||
// Check if response has error
|
return response.data;
|
||||||
if (response.error) {
|
|
||||||
console.error('getAllShift error response:', response);
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 500,
|
|
||||||
data: {
|
|
||||||
data: [],
|
|
||||||
paging: {
|
|
||||||
page: 1,
|
|
||||||
limit: 10,
|
|
||||||
total: 0,
|
|
||||||
page_total: 0
|
|
||||||
},
|
|
||||||
total: 0
|
|
||||||
},
|
|
||||||
error: response.message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if backend returns paginated data
|
|
||||||
if (response.paging) {
|
|
||||||
const totalData = response.data?.[0]?.total_data || response.rows || response.data?.length || 0;
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: response.data || [],
|
|
||||||
paging: {
|
|
||||||
page: response.paging.current_page || 1,
|
|
||||||
limit: response.paging.current_limit || 10,
|
|
||||||
total: totalData,
|
|
||||||
page_total: response.paging.total_page || Math.ceil(totalData / (response.paging.current_limit || 10))
|
|
||||||
},
|
|
||||||
total: totalData
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback: If backend returns all data without pagination
|
|
||||||
const params = Object.fromEntries(queryParams);
|
|
||||||
const currentPage = parseInt(params.page) || 1;
|
|
||||||
const currentLimit = parseInt(params.limit) || 10;
|
|
||||||
|
|
||||||
const allData = response.data || [];
|
|
||||||
const totalData = allData.length;
|
|
||||||
|
|
||||||
// Client-side pagination
|
|
||||||
const startIndex = (currentPage - 1) * currentLimit;
|
|
||||||
const endIndex = startIndex + currentLimit;
|
|
||||||
const paginatedData = allData.slice(startIndex, endIndex);
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: paginatedData,
|
|
||||||
paging: {
|
|
||||||
page: currentPage,
|
|
||||||
limit: currentLimit,
|
|
||||||
total: totalData,
|
|
||||||
page_total: Math.ceil(totalData / currentLimit)
|
|
||||||
},
|
|
||||||
total: totalData
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
console.error('getAllShift catch error:', error);
|
|
||||||
return {
|
|
||||||
status: 500,
|
|
||||||
data: {
|
|
||||||
data: [],
|
|
||||||
paging: {
|
|
||||||
page: 1,
|
|
||||||
limit: 10,
|
|
||||||
total: 0,
|
|
||||||
page_total: 0
|
|
||||||
},
|
|
||||||
total: 0
|
|
||||||
},
|
|
||||||
error: error.message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getShiftById = async (id) => {
|
const getShiftById = async (id) => {
|
||||||
@@ -97,6 +14,7 @@ const getShiftById = async (id) => {
|
|||||||
method: 'get',
|
method: 'get',
|
||||||
prefix: `shift/${id}`,
|
prefix: `shift/${id}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
return response.data;
|
return response.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -106,26 +24,8 @@ const createShift = async (queryParams) => {
|
|||||||
prefix: `shift`,
|
prefix: `shift`,
|
||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
console.log('createShift full response:', response);
|
|
||||||
console.log('createShift payload sent:', queryParams);
|
|
||||||
|
|
||||||
// Check if response has error flag
|
return response.data;
|
||||||
if (response.error) {
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 500,
|
|
||||||
data: null,
|
|
||||||
message: response.message || 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backend returns: { statusCode, message, rows, data: [shift_object] }
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data?.[0] || response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateShift = async (id, queryParams) => {
|
const updateShift = async (id, queryParams) => {
|
||||||
@@ -134,26 +34,8 @@ const updateShift = async (id, queryParams) => {
|
|||||||
prefix: `shift/${id}`,
|
prefix: `shift/${id}`,
|
||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
console.log('updateShift full response:', response);
|
|
||||||
console.log('updateShift payload sent:', queryParams);
|
|
||||||
|
|
||||||
// Check if response has error flag
|
return response.data;
|
||||||
if (response.error) {
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 500,
|
|
||||||
data: null,
|
|
||||||
message: response.message || 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backend returns: { statusCode, message, rows, data: [shift_object] }
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data?.[0] || response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteShift = async (id) => {
|
const deleteShift = async (id) => {
|
||||||
@@ -161,25 +43,8 @@ const deleteShift = async (id) => {
|
|||||||
method: 'delete',
|
method: 'delete',
|
||||||
prefix: `shift/${id}`,
|
prefix: `shift/${id}`,
|
||||||
});
|
});
|
||||||
console.log('deleteShift full response:', response);
|
|
||||||
|
|
||||||
// Check if response has error flag
|
return response.data;
|
||||||
if (response.error) {
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 500,
|
|
||||||
data: null,
|
|
||||||
message: response.message || 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backend returns: { statusCode, message, rows: null, data: true }
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export { getAllShift, getShiftById, createShift, updateShift, deleteShift };
|
export { getAllShift, getShiftById, createShift, updateShift, deleteShift };
|
||||||
|
|||||||
@@ -1,89 +1,12 @@
|
|||||||
import { SendRequest } from '../components/Global/ApiRequest';
|
import { SendRequest } from '../components/Global/ApiRequest';
|
||||||
|
|
||||||
const getAllStatus = async (queryParams) => {
|
const getAllStatuss = async (queryParams) => {
|
||||||
try {
|
const response = await SendRequest({
|
||||||
const response = await SendRequest({
|
method: 'get',
|
||||||
method: 'get',
|
prefix: `status?${queryParams.toString()}`,
|
||||||
prefix: `status?${queryParams.toString()}`,
|
});
|
||||||
});
|
|
||||||
|
|
||||||
if (response.error) {
|
return response.data;
|
||||||
console.error('getAllStatus error response:', response);
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 500,
|
|
||||||
data: {
|
|
||||||
data: [],
|
|
||||||
paging: {
|
|
||||||
page: 1,
|
|
||||||
limit: 10,
|
|
||||||
total: 0,
|
|
||||||
page_total: 0
|
|
||||||
},
|
|
||||||
total: 0
|
|
||||||
},
|
|
||||||
error: response.message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (response.paging) {
|
|
||||||
const totalData = response.data?.[0]?.total_data || response.rows || response.data?.length || 0;
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: response.data || [],
|
|
||||||
paging: {
|
|
||||||
page: response.paging.current_page || 1,
|
|
||||||
limit: response.paging.current_limit || 10,
|
|
||||||
total: totalData,
|
|
||||||
page_total: response.paging.total_page || Math.ceil(totalData / (response.paging.current_limit || 10))
|
|
||||||
},
|
|
||||||
total: totalData
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const params = Object.fromEntries(queryParams);
|
|
||||||
const currentPage = parseInt(params.page) || 1;
|
|
||||||
const currentLimit = parseInt(params.limit) || 10;
|
|
||||||
|
|
||||||
const allData = response.data || [];
|
|
||||||
const totalData = allData.length;
|
|
||||||
|
|
||||||
const startIndex = (currentPage - 1) * currentLimit;
|
|
||||||
const endIndex = startIndex + currentLimit;
|
|
||||||
const paginatedData = allData.slice(startIndex, endIndex);
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: paginatedData,
|
|
||||||
paging: {
|
|
||||||
page: currentPage,
|
|
||||||
limit: currentLimit,
|
|
||||||
total: totalData,
|
|
||||||
page_total: Math.ceil(totalData / currentLimit)
|
|
||||||
},
|
|
||||||
total: totalData
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
console.error('getAllStatus catch error:', error);
|
|
||||||
return {
|
|
||||||
status: 500,
|
|
||||||
data: {
|
|
||||||
data: [],
|
|
||||||
paging: {
|
|
||||||
page: 1,
|
|
||||||
limit: 10,
|
|
||||||
total: 0,
|
|
||||||
page_total: 0
|
|
||||||
},
|
|
||||||
total: 0
|
|
||||||
},
|
|
||||||
error: error.message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getStatusById = async (id) => {
|
const getStatusById = async (id) => {
|
||||||
@@ -91,6 +14,7 @@ const getStatusById = async (id) => {
|
|||||||
method: 'get',
|
method: 'get',
|
||||||
prefix: `status/${id}`,
|
prefix: `status/${id}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
return response.data;
|
return response.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -101,68 +25,26 @@ const createStatus = async (queryParams) => {
|
|||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.error) {
|
return response.data;
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 500,
|
|
||||||
data: null,
|
|
||||||
message: response.message || 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data?.[0] || response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateStatus = async (status_id, queryParams) => {
|
const updateStatus = async (id, queryParams) => {
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'put',
|
method: 'put',
|
||||||
prefix: `status/${status_id}`,
|
prefix: `status/${id}`,
|
||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.error) {
|
return response.data;
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 500,
|
|
||||||
data: null,
|
|
||||||
message: response.message || 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data?.[0] || response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteStatus = async (queryParams) => {
|
const deleteStatus = async (id) => {
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'delete',
|
method: 'delete',
|
||||||
prefix: `status/${queryParams}`,
|
prefix: `status/${id}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.error) {
|
return response.data;
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 500,
|
|
||||||
data: null,
|
|
||||||
message: response.message || 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export { getAllStatus, getStatusById, createStatus, updateStatus, deleteStatus };
|
export { getAllStatuss, getStatusById, createStatus, updateStatus, deleteStatus };
|
||||||
|
|||||||
@@ -1,93 +1,12 @@
|
|||||||
import { SendRequest } from '../components/Global/ApiRequest';
|
import { SendRequest } from '../components/Global/ApiRequest';
|
||||||
|
|
||||||
const getAllTag = async (queryParams) => {
|
const getAllTag = async (queryParams) => {
|
||||||
try {
|
const response = await SendRequest({
|
||||||
const response = await SendRequest({
|
method: 'get',
|
||||||
method: 'get',
|
prefix: `tags?${queryParams.toString()}`,
|
||||||
prefix: `tags?${queryParams.toString()}`,
|
});
|
||||||
});
|
|
||||||
|
|
||||||
// Check if response has error
|
return response.data;
|
||||||
if (response.error) {
|
|
||||||
console.error('getAllTag error response:', response);
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 500,
|
|
||||||
data: {
|
|
||||||
data: [],
|
|
||||||
paging: {
|
|
||||||
page: 1,
|
|
||||||
limit: 10,
|
|
||||||
total: 0,
|
|
||||||
page_total: 0
|
|
||||||
},
|
|
||||||
total: 0
|
|
||||||
},
|
|
||||||
error: response.message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if backend returns paginated data
|
|
||||||
if (response.paging) {
|
|
||||||
const totalData = response.data?.[0]?.total_data || response.rows || response.data?.length || 0;
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: response.data || [],
|
|
||||||
paging: {
|
|
||||||
page: response.paging.current_page || 1,
|
|
||||||
limit: response.paging.current_limit || 10,
|
|
||||||
total: totalData,
|
|
||||||
page_total: response.paging.total_page || Math.ceil(totalData / (response.paging.current_limit || 10))
|
|
||||||
},
|
|
||||||
total: totalData
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback: If backend returns all data without pagination (old behavior)
|
|
||||||
const params = Object.fromEntries(queryParams);
|
|
||||||
const currentPage = parseInt(params.page) || 1;
|
|
||||||
const currentLimit = parseInt(params.limit) || 10;
|
|
||||||
|
|
||||||
const allData = response.data || [];
|
|
||||||
const totalData = allData.length;
|
|
||||||
|
|
||||||
// Client-side pagination
|
|
||||||
const startIndex = (currentPage - 1) * currentLimit;
|
|
||||||
const endIndex = startIndex + currentLimit;
|
|
||||||
const paginatedData = allData.slice(startIndex, endIndex);
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: paginatedData,
|
|
||||||
paging: {
|
|
||||||
page: currentPage,
|
|
||||||
limit: currentLimit,
|
|
||||||
total: totalData,
|
|
||||||
page_total: Math.ceil(totalData / currentLimit)
|
|
||||||
},
|
|
||||||
total: totalData
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
console.error('getAllTag catch error:', error);
|
|
||||||
return {
|
|
||||||
status: 500,
|
|
||||||
data: {
|
|
||||||
data: [],
|
|
||||||
paging: {
|
|
||||||
page: 1,
|
|
||||||
limit: 10,
|
|
||||||
total: 0,
|
|
||||||
page_total: 0
|
|
||||||
},
|
|
||||||
total: 0
|
|
||||||
},
|
|
||||||
error: error.message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getTagById = async (id) => {
|
const getTagById = async (id) => {
|
||||||
@@ -95,6 +14,7 @@ const getTagById = async (id) => {
|
|||||||
method: 'get',
|
method: 'get',
|
||||||
prefix: `tags/${id}`,
|
prefix: `tags/${id}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
return response.data;
|
return response.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -105,74 +25,26 @@ const createTag = async (queryParams) => {
|
|||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Check if response has error flag
|
return response.data;
|
||||||
if (response.error) {
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 500,
|
|
||||||
data: null,
|
|
||||||
message: response.message || 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backend returns: { statusCode, message, rows, data: [tag_object] }
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data?.[0] || response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateTag = async (tag_id, queryParams) => {
|
const updateTag = async (id, queryParams) => {
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'put',
|
method: 'put',
|
||||||
prefix: `tags/${tag_id}`,
|
prefix: `tags/${id}`,
|
||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Check if response has error flag
|
return response.data;
|
||||||
if (response.error) {
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 500,
|
|
||||||
data: null,
|
|
||||||
message: response.message || 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backend returns: { statusCode, message, rows, data: [tag_object] }
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data?.[0] || response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteTag = async (queryParams) => {
|
const deleteTag = async (id) => {
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'delete',
|
method: 'delete',
|
||||||
prefix: `tags/${queryParams}`,
|
prefix: `tags/${id}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Check if response has error flag
|
return response.data;
|
||||||
if (response.error) {
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 500,
|
|
||||||
data: null,
|
|
||||||
message: response.message || 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backend returns: { statusCode, message, rows: null, data: true }
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export { getAllTag, getTagById, createTag, updateTag, deleteTag };
|
export { getAllTag, getTagById, createTag, updateTag, deleteTag };
|
||||||
|
|||||||
@@ -1,95 +1,12 @@
|
|||||||
import { SendRequest } from '../components/Global/ApiRequest';
|
import { SendRequest } from '../components/Global/ApiRequest';
|
||||||
|
|
||||||
const getAllUnit = async (queryParams) => {
|
const getAllUnit = async (queryParams) => {
|
||||||
try {
|
const response = await SendRequest({
|
||||||
const response = await SendRequest({
|
method: 'get',
|
||||||
method: 'get',
|
prefix: `unit?${queryParams.toString()}`,
|
||||||
prefix: `unit?${queryParams.toString()}`,
|
});
|
||||||
});
|
|
||||||
console.log('getAllUnit response:', response);
|
|
||||||
console.log('Query params:', queryParams.toString());
|
|
||||||
|
|
||||||
// Check if response has error
|
return response.data;
|
||||||
if (response.error) {
|
|
||||||
console.error('getAllUnit error response:', response);
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 500,
|
|
||||||
data: {
|
|
||||||
data: [],
|
|
||||||
paging: {
|
|
||||||
page: 1,
|
|
||||||
limit: 10,
|
|
||||||
total: 0,
|
|
||||||
page_total: 0
|
|
||||||
},
|
|
||||||
total: 0
|
|
||||||
},
|
|
||||||
error: response.message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if backend returns paginated data
|
|
||||||
if (response.paging) {
|
|
||||||
const totalData = response.data?.[0]?.total_data || response.rows || response.data?.length || 0;
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: response.data || [],
|
|
||||||
paging: {
|
|
||||||
page: response.paging.current_page || 1,
|
|
||||||
limit: response.paging.current_limit || 10,
|
|
||||||
total: totalData,
|
|
||||||
page_total: response.paging.total_page || Math.ceil(totalData / (response.paging.current_limit || 10))
|
|
||||||
},
|
|
||||||
total: totalData
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback: If backend returns all data without pagination
|
|
||||||
const params = Object.fromEntries(queryParams);
|
|
||||||
const currentPage = parseInt(params.page) || 1;
|
|
||||||
const currentLimit = parseInt(params.limit) || 10;
|
|
||||||
|
|
||||||
const allData = response.data || [];
|
|
||||||
const totalData = allData.length;
|
|
||||||
|
|
||||||
// Client-side pagination
|
|
||||||
const startIndex = (currentPage - 1) * currentLimit;
|
|
||||||
const endIndex = startIndex + currentLimit;
|
|
||||||
const paginatedData = allData.slice(startIndex, endIndex);
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: paginatedData,
|
|
||||||
paging: {
|
|
||||||
page: currentPage,
|
|
||||||
limit: currentLimit,
|
|
||||||
total: totalData,
|
|
||||||
page_total: Math.ceil(totalData / currentLimit)
|
|
||||||
},
|
|
||||||
total: totalData
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
console.error('getAllUnit catch error:', error);
|
|
||||||
return {
|
|
||||||
status: 500,
|
|
||||||
data: {
|
|
||||||
data: [],
|
|
||||||
paging: {
|
|
||||||
page: 1,
|
|
||||||
limit: 10,
|
|
||||||
total: 0,
|
|
||||||
page_total: 0
|
|
||||||
},
|
|
||||||
total: 0
|
|
||||||
},
|
|
||||||
error: error.message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getUnitById = async (id) => {
|
const getUnitById = async (id) => {
|
||||||
@@ -97,101 +14,37 @@ const getUnitById = async (id) => {
|
|||||||
method: 'get',
|
method: 'get',
|
||||||
prefix: `unit/${id}`,
|
prefix: `unit/${id}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
return response.data;
|
return response.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
const createUnit = async (queryParams) => {
|
const createUnit = async (queryParams) => {
|
||||||
// Map frontend fields to backend fields
|
|
||||||
const backendParams = {
|
|
||||||
unit_name: queryParams.name,
|
|
||||||
is_active: queryParams.is_active,
|
|
||||||
};
|
|
||||||
|
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'post',
|
method: 'post',
|
||||||
prefix: `unit`,
|
prefix: `unit`,
|
||||||
params: backendParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
console.log('createUnit full response:', response);
|
|
||||||
console.log('createUnit payload sent:', backendParams);
|
|
||||||
|
|
||||||
// Check if response has error flag
|
return response.data;
|
||||||
if (response.error) {
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 500,
|
|
||||||
data: null,
|
|
||||||
message: response.message || 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backend returns: { statusCode, message, rows, data: [unit_object] }
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data?.[0] || response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateUnit = async (unit_id, queryParams) => {
|
const updateUnit = async (id, queryParams) => {
|
||||||
// Map frontend fields to backend fields
|
|
||||||
const backendParams = {
|
|
||||||
unit_name: queryParams.name,
|
|
||||||
is_active: queryParams.is_active,
|
|
||||||
};
|
|
||||||
|
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'put',
|
method: 'put',
|
||||||
prefix: `unit/${unit_id}`,
|
prefix: `unit/${id}`,
|
||||||
params: backendParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
console.log('updateUnit full response:', response);
|
|
||||||
console.log('updateUnit payload sent:', backendParams);
|
|
||||||
|
|
||||||
// Check if response has error flag
|
return response.data;
|
||||||
if (response.error) {
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 500,
|
|
||||||
data: null,
|
|
||||||
message: response.message || 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backend returns: { statusCode, message, rows, data: [unit_object] }
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data?.[0] || response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteUnit = async (queryParams) => {
|
const deleteUnit = async (id) => {
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'delete',
|
method: 'delete',
|
||||||
prefix: `unit/${queryParams}`,
|
prefix: `unit/${id}`,
|
||||||
});
|
});
|
||||||
console.log('deleteUnit full response:', response);
|
|
||||||
|
|
||||||
// Check if response has error flag
|
return response.data;
|
||||||
if (response.error) {
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 500,
|
|
||||||
data: null,
|
|
||||||
message: response.message || 'Request failed',
|
|
||||||
rows: 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backend returns: { statusCode, message, rows: null, data: true }
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message,
|
|
||||||
rows: response.rows
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export { getAllUnit, getUnitById, createUnit, updateUnit, deleteUnit };
|
export { getAllUnit, getUnitById, createUnit, updateUnit, deleteUnit };
|
||||||
|
|||||||
164
src/api/role.jsx
164
src/api/role.jsx
@@ -1,70 +1,12 @@
|
|||||||
import { SendRequest } from '../components/Global/ApiRequest';
|
import { SendRequest } from '../components/Global/ApiRequest';
|
||||||
|
|
||||||
const getAllRole = async (queryParams) => {
|
const getAllRole = async (queryParams) => {
|
||||||
try {
|
const response = await SendRequest({
|
||||||
const response = await SendRequest({
|
method: 'get',
|
||||||
method: 'get',
|
prefix: `roles?${queryParams.toString()}`,
|
||||||
prefix: `roles?${queryParams.toString()}`,
|
});
|
||||||
});
|
|
||||||
|
|
||||||
console.log('Role API Response:', response);
|
return response.data;
|
||||||
|
|
||||||
// Check if backend returns paginated data
|
|
||||||
if (response.paging) {
|
|
||||||
// Backend already provides pagination info
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: response.data || [],
|
|
||||||
paging: response.paging,
|
|
||||||
total: response.paging.total || 0
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback: If backend returns all data without pagination
|
|
||||||
const params = Object.fromEntries(queryParams);
|
|
||||||
const currentPage = parseInt(params.page) || 1;
|
|
||||||
const currentLimit = parseInt(params.limit) || 10;
|
|
||||||
|
|
||||||
const allData = response.data || [];
|
|
||||||
const totalData = allData.length;
|
|
||||||
|
|
||||||
// Client-side pagination
|
|
||||||
const startIndex = (currentPage - 1) * currentLimit;
|
|
||||||
const endIndex = startIndex + currentLimit;
|
|
||||||
const paginatedData = allData.slice(startIndex, endIndex);
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: paginatedData,
|
|
||||||
paging: {
|
|
||||||
page: currentPage,
|
|
||||||
limit: currentLimit,
|
|
||||||
total: totalData,
|
|
||||||
page_total: Math.ceil(totalData / currentLimit),
|
|
||||||
},
|
|
||||||
total: totalData,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
console.error('getAllRole error:', error);
|
|
||||||
return {
|
|
||||||
status: 500,
|
|
||||||
data: {
|
|
||||||
data: [],
|
|
||||||
paging: {
|
|
||||||
page: 1,
|
|
||||||
limit: 10,
|
|
||||||
total: 0,
|
|
||||||
page_total: 0
|
|
||||||
},
|
|
||||||
total: 0
|
|
||||||
},
|
|
||||||
error: error.message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getRoleById = async (id) => {
|
const getRoleById = async (id) => {
|
||||||
@@ -72,6 +14,7 @@ const getRoleById = async (id) => {
|
|||||||
method: 'get',
|
method: 'get',
|
||||||
prefix: `roles/${id}`,
|
prefix: `roles/${id}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
return response.data;
|
return response.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -82,107 +25,26 @@ const createRole = async (queryParams) => {
|
|||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log('Create Role API Response:', response);
|
return response.data;
|
||||||
|
|
||||||
// Check for error status (not 200, 201, or success)
|
|
||||||
const isSuccess =
|
|
||||||
response.statusCode === 200 || response.statusCode === 201 || response.status === 'success';
|
|
||||||
|
|
||||||
if (!isSuccess && response.statusCode >= 400) {
|
|
||||||
let errorMessage = response.message || 'Gagal menambahkan role';
|
|
||||||
|
|
||||||
// Handle SQL unique constraint violation
|
|
||||||
if (
|
|
||||||
errorMessage.includes('UNIQUE KEY constraint') ||
|
|
||||||
errorMessage.includes('duplicate key')
|
|
||||||
) {
|
|
||||||
errorMessage = `Role dengan nama "${queryParams.role_name}" sudah ada. Silakan gunakan nama lain.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode,
|
|
||||||
data: response.data,
|
|
||||||
message: errorMessage,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return full response with statusCode
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message || 'Berhasil menambahkan role',
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateRole = async (role_id, queryParams) => {
|
const updateRole = async (id, queryParams) => {
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'put',
|
method: 'put',
|
||||||
prefix: `roles/${role_id}`,
|
prefix: `roles/${id}`,
|
||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log('Update Role API Response:', response);
|
return response.data;
|
||||||
|
|
||||||
// Check for error status (not 200, 201, or success)
|
|
||||||
const isSuccess =
|
|
||||||
response.statusCode === 200 || response.statusCode === 201 || response.status === 'success';
|
|
||||||
|
|
||||||
if (!isSuccess && response.statusCode >= 400) {
|
|
||||||
let errorMessage = response.message || 'Gagal mengubah role';
|
|
||||||
|
|
||||||
// Handle SQL unique constraint violation
|
|
||||||
if (
|
|
||||||
errorMessage.includes('UNIQUE KEY constraint') ||
|
|
||||||
errorMessage.includes('duplicate key')
|
|
||||||
) {
|
|
||||||
errorMessage = `Role dengan nama "${queryParams.role_name}" sudah ada. Silakan gunakan nama lain.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode,
|
|
||||||
data: response.data,
|
|
||||||
message: errorMessage,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return full response with statusCode
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message || 'Berhasil mengubah role',
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteRole = async (queryParams) => {
|
const deleteRole = async (id) => {
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'delete',
|
method: 'delete',
|
||||||
prefix: `roles/${queryParams}`,
|
prefix: `roles/${id}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log('Delete API Response:', response);
|
return response.data;
|
||||||
|
|
||||||
// Check for errors
|
|
||||||
if (response.statusCode !== 200) {
|
|
||||||
let errorMessage = response.message || 'Gagal menghapus role';
|
|
||||||
|
|
||||||
// Handle foreign key constraint
|
|
||||||
if (errorMessage.includes('REFERENCE constraint') || errorMessage.includes('foreign key')) {
|
|
||||||
errorMessage = 'Role tidak dapat dihapus karena masih digunakan oleh user.';
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode,
|
|
||||||
data: response.data,
|
|
||||||
message: errorMessage,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return full response with statusCode
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message,
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export { getAllRole, getRoleById, createRole, updateRole, deleteRole };
|
export { getAllRole, getRoleById, createRole, updateRole, deleteRole };
|
||||||
|
|||||||
@@ -1,15 +1,11 @@
|
|||||||
// user-admin.jsx
|
|
||||||
import axios from 'axios';
|
|
||||||
import { SendRequest } from '../components/Global/ApiRequest';
|
import { SendRequest } from '../components/Global/ApiRequest';
|
||||||
|
|
||||||
const baseURL = import.meta.env.VITE_API_SERVER;
|
|
||||||
|
|
||||||
const getAllUser = async (queryParams) => {
|
const getAllUser = async (queryParams) => {
|
||||||
const response = await SendRequest({
|
const response = await SendRequest({
|
||||||
method: 'get',
|
method: 'get',
|
||||||
prefix: `admin-user?${queryParams.toString()}`,
|
prefix: `admin-user?${queryParams.toString()}`,
|
||||||
});
|
});
|
||||||
return response;
|
return response.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
const getUserDetail = async (id) => {
|
const getUserDetail = async (id) => {
|
||||||
@@ -17,7 +13,7 @@ const getUserDetail = async (id) => {
|
|||||||
method: 'get',
|
method: 'get',
|
||||||
prefix: `admin-user/${id}`,
|
prefix: `admin-user/${id}`,
|
||||||
});
|
});
|
||||||
return response;
|
return response.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateUser = async (id, data) => {
|
const updateUser = async (id, data) => {
|
||||||
@@ -26,7 +22,7 @@ const updateUser = async (id, data) => {
|
|||||||
prefix: `admin-user/${id}`,
|
prefix: `admin-user/${id}`,
|
||||||
params: data,
|
params: data,
|
||||||
});
|
});
|
||||||
return response;
|
return response.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteUser = async (id) => {
|
const deleteUser = async (id) => {
|
||||||
@@ -34,7 +30,7 @@ const deleteUser = async (id) => {
|
|||||||
method: 'delete',
|
method: 'delete',
|
||||||
prefix: `admin-user/${id}`,
|
prefix: `admin-user/${id}`,
|
||||||
});
|
});
|
||||||
return response;
|
return response.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
const approvalUser = async (id, queryParams) => {
|
const approvalUser = async (id, queryParams) => {
|
||||||
@@ -43,42 +39,7 @@ const approvalUser = async (id, queryParams) => {
|
|||||||
prefix: `admin-user/approve/${id}`,
|
prefix: `admin-user/approve/${id}`,
|
||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
return response;
|
return response.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
const uploadFile = async (formData) => {
|
export { getAllUser, getUserDetail, updateUser, deleteUser, approvalUser };
|
||||||
try {
|
|
||||||
const token = localStorage.getItem('token')?.replace(/"/g, '') || '';
|
|
||||||
const url = `${baseURL}/file-upload`;
|
|
||||||
|
|
||||||
const response = await axios.post(url, formData, {
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${token}`,
|
|
||||||
'Accept-Language': 'en_US',
|
|
||||||
'Content-Type': 'multipart/form-data',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
statusCode: response.data?.statusCode ?? 0,
|
|
||||||
message: response.data?.message ?? '',
|
|
||||||
data: response.data?.data ?? {},
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
console.error('❌ ERROR di uploadFile:', error);
|
|
||||||
return {
|
|
||||||
statusCode: error?.response?.status || 500,
|
|
||||||
message: error?.response?.data?.message || 'Upload gagal',
|
|
||||||
data: {},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export { getAllUser, getUserDetail, updateUser, deleteUser, approvalUser, uploadFile };
|
|
||||||
|
|||||||
169
src/api/user.jsx
169
src/api/user.jsx
@@ -1,97 +1,12 @@
|
|||||||
import { SendRequest } from '../components/Global/ApiRequest';
|
import { SendRequest } from '../components/Global/ApiRequest';
|
||||||
|
|
||||||
const getAllUser = async (queryParams) => {
|
const getAllUser = async (queryParams) => {
|
||||||
try {
|
const response = await SendRequest({
|
||||||
console.log('getAllUser queryParams:', queryParams.toString());
|
method: 'get',
|
||||||
|
prefix: `user?${queryParams.toString()}`,
|
||||||
|
});
|
||||||
|
|
||||||
const response = await SendRequest({
|
return response.data;
|
||||||
method: 'get',
|
|
||||||
prefix: `user?${queryParams.toString()}`,
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('getAllUser response:', response);
|
|
||||||
|
|
||||||
// Backend now handles pagination, just return the response
|
|
||||||
// Expected backend response structure:
|
|
||||||
// {
|
|
||||||
// statusCode: 200,
|
|
||||||
// data: [...users],
|
|
||||||
// paging: { page, limit, total, page_total }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// Check if backend returns paginated data
|
|
||||||
if (response.paging) {
|
|
||||||
// Filter out super admin users (is_sa = true)
|
|
||||||
const allData = response.data || [];
|
|
||||||
const filteredData = allData.filter(user => user.is_sa !== true && user.is_sa !== 1);
|
|
||||||
|
|
||||||
// Recalculate pagination info after filtering
|
|
||||||
const totalAfterFilter = filteredData.length;
|
|
||||||
const currentPage = response.paging.page || 1;
|
|
||||||
const currentLimit = response.paging.limit || 10;
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: filteredData,
|
|
||||||
paging: {
|
|
||||||
page: currentPage,
|
|
||||||
limit: currentLimit,
|
|
||||||
total: totalAfterFilter,
|
|
||||||
page_total: Math.ceil(totalAfterFilter / currentLimit)
|
|
||||||
},
|
|
||||||
total: totalAfterFilter
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback: If backend returns all data without pagination (old behavior)
|
|
||||||
const params = Object.fromEntries(queryParams);
|
|
||||||
const currentPage = parseInt(params.page) || 1;
|
|
||||||
const currentLimit = parseInt(params.limit) || 10;
|
|
||||||
|
|
||||||
const allData = response.data || [];
|
|
||||||
|
|
||||||
// Filter out users with is_sa = true or 1 (client-side filtering)
|
|
||||||
const filteredData = allData.filter(user => user.is_sa !== true && user.is_sa !== 1);
|
|
||||||
const totalData = filteredData.length;
|
|
||||||
|
|
||||||
// Client-side pagination
|
|
||||||
const startIndex = (currentPage - 1) * currentLimit;
|
|
||||||
const endIndex = startIndex + currentLimit;
|
|
||||||
const paginatedData = filteredData.slice(startIndex, endIndex);
|
|
||||||
|
|
||||||
return {
|
|
||||||
status: response.statusCode || 200,
|
|
||||||
data: {
|
|
||||||
data: paginatedData,
|
|
||||||
paging: {
|
|
||||||
page: currentPage,
|
|
||||||
limit: currentLimit,
|
|
||||||
total: totalData,
|
|
||||||
page_total: Math.ceil(totalData / currentLimit)
|
|
||||||
},
|
|
||||||
total: totalData
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
console.error('getAllUser error:', error);
|
|
||||||
// Return empty data on error to prevent app crash
|
|
||||||
return {
|
|
||||||
status: 500,
|
|
||||||
data: {
|
|
||||||
data: [],
|
|
||||||
paging: {
|
|
||||||
page: 1,
|
|
||||||
limit: 10,
|
|
||||||
total: 0,
|
|
||||||
page_total: 0
|
|
||||||
},
|
|
||||||
total: 0
|
|
||||||
},
|
|
||||||
error: error.message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const getUserById = async (id) => {
|
const getUserById = async (id) => {
|
||||||
@@ -99,6 +14,7 @@ const getUserById = async (id) => {
|
|||||||
method: 'get',
|
method: 'get',
|
||||||
prefix: `user/${id}`,
|
prefix: `user/${id}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
return response.data;
|
return response.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -108,12 +24,8 @@ const createUser = async (queryParams) => {
|
|||||||
prefix: `user`,
|
prefix: `user`,
|
||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
// Return full response with statusCode
|
|
||||||
return {
|
return response.data;
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateUser = async (user_id, queryParams) => {
|
const updateUser = async (user_id, queryParams) => {
|
||||||
@@ -122,12 +34,8 @@ const updateUser = async (user_id, queryParams) => {
|
|||||||
prefix: `user/${user_id}`,
|
prefix: `user/${user_id}`,
|
||||||
params: queryParams,
|
params: queryParams,
|
||||||
});
|
});
|
||||||
// Return full response with statusCode
|
|
||||||
return {
|
return response.data;
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteUser = async (queryParams) => {
|
const deleteUser = async (queryParams) => {
|
||||||
@@ -135,12 +43,8 @@ const deleteUser = async (queryParams) => {
|
|||||||
method: 'delete',
|
method: 'delete',
|
||||||
prefix: `user/${queryParams}`,
|
prefix: `user/${queryParams}`,
|
||||||
});
|
});
|
||||||
// Return full response with statusCode
|
|
||||||
return {
|
return response.data;
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const approveUser = async (user_id) => {
|
const approveUser = async (user_id) => {
|
||||||
@@ -148,12 +52,8 @@ const approveUser = async (user_id) => {
|
|||||||
method: 'put',
|
method: 'put',
|
||||||
prefix: `user/${user_id}/approve`,
|
prefix: `user/${user_id}/approve`,
|
||||||
});
|
});
|
||||||
// Return full response with statusCode
|
|
||||||
return {
|
return response.data;
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const rejectUser = async (user_id) => {
|
const rejectUser = async (user_id) => {
|
||||||
@@ -161,12 +61,8 @@ const rejectUser = async (user_id) => {
|
|||||||
method: 'put',
|
method: 'put',
|
||||||
prefix: `user/${user_id}/reject`,
|
prefix: `user/${user_id}/reject`,
|
||||||
});
|
});
|
||||||
// Return full response with statusCode
|
|
||||||
return {
|
return response.data;
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const toggleActiveUser = async (user_id, is_active) => {
|
const toggleActiveUser = async (user_id, is_active) => {
|
||||||
@@ -174,15 +70,11 @@ const toggleActiveUser = async (user_id, is_active) => {
|
|||||||
method: 'put',
|
method: 'put',
|
||||||
prefix: `user/${user_id}`,
|
prefix: `user/${user_id}`,
|
||||||
params: {
|
params: {
|
||||||
is_active: is_active
|
is_active: is_active,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
// Return full response with statusCode
|
|
||||||
return {
|
return response.data;
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const changePassword = async (user_id, new_password) => {
|
const changePassword = async (user_id, new_password) => {
|
||||||
@@ -190,18 +82,21 @@ const changePassword = async (user_id, new_password) => {
|
|||||||
method: 'put',
|
method: 'put',
|
||||||
prefix: `user/change-password/${user_id}`,
|
prefix: `user/change-password/${user_id}`,
|
||||||
params: {
|
params: {
|
||||||
new_password: new_password
|
new_password: new_password,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log('Change Password Response:', response);
|
return response.data;
|
||||||
|
|
||||||
// Return full response with statusCode
|
|
||||||
return {
|
|
||||||
statusCode: response.statusCode || 200,
|
|
||||||
data: response.data,
|
|
||||||
message: response.message || 'Password berhasil diubah'
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export { getAllUser, getUserById, createUser, updateUser, deleteUser, approveUser, rejectUser, toggleActiveUser, changePassword };
|
export {
|
||||||
|
getAllUser,
|
||||||
|
getUserById,
|
||||||
|
createUser,
|
||||||
|
updateUser,
|
||||||
|
deleteUser,
|
||||||
|
approveUser,
|
||||||
|
rejectUser,
|
||||||
|
toggleActiveUser,
|
||||||
|
changePassword,
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,170 +1,171 @@
|
|||||||
import axios from "axios";
|
import axios from 'axios';
|
||||||
import Swal from "sweetalert2";
|
import Swal from 'sweetalert2';
|
||||||
|
|
||||||
const baseURL = import.meta.env.VITE_API_SERVER;
|
const baseURL = import.meta.env.VITE_API_SERVER;
|
||||||
|
|
||||||
const instance = axios.create({
|
const instance = axios.create({
|
||||||
baseURL,
|
baseURL,
|
||||||
withCredentials: true,
|
withCredentials: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
// axios khusus refresh
|
// axios khusus refresh
|
||||||
const refreshApi = axios.create({
|
const refreshApi = axios.create({
|
||||||
baseURL,
|
baseURL,
|
||||||
withCredentials: true,
|
withCredentials: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
instance.interceptors.response.use(
|
instance.interceptors.response.use(
|
||||||
(response) => response,
|
(response) => response,
|
||||||
async (error) => {
|
async (error) => {
|
||||||
const originalRequest = error.config;
|
const originalRequest = error.config;
|
||||||
|
|
||||||
console.error("🚨 Response Error Interceptor:", {
|
console.error('🚨 Response Error Interceptor:', {
|
||||||
status: error.response?.status,
|
status: error.response?.status,
|
||||||
url: originalRequest.url,
|
url: originalRequest.url,
|
||||||
message: error.response?.data?.message,
|
message: error.response?.data?.message,
|
||||||
hasRetried: originalRequest._retry
|
hasRetried: originalRequest._retry,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (error.response?.status === 401 && !originalRequest._retry) {
|
if (error.response?.status === 401 && !originalRequest._retry) {
|
||||||
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("❌ Refresh token gagal:", refreshError.response?.data || refreshError.message);
|
console.error(
|
||||||
localStorage.clear();
|
'❌ Refresh token gagal:',
|
||||||
window.location.href = "/signin";
|
refreshError.response?.data || refreshError.message
|
||||||
}
|
);
|
||||||
|
localStorage.clear();
|
||||||
|
window.location.href = '/signin';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Promise.reject(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
return Promise.reject(error);
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
|
|
||||||
async function ApiRequest({
|
async function ApiRequest({ method = 'GET', params = {}, prefix = '/', token = true } = {}) {
|
||||||
method = "GET",
|
const isFormData = params instanceof FormData;
|
||||||
params = {},
|
|
||||||
prefix = "/",
|
|
||||||
token = true,
|
|
||||||
} = {}) {
|
|
||||||
const isFormData = params instanceof FormData;
|
|
||||||
|
|
||||||
const request = {
|
const request = {
|
||||||
method,
|
method,
|
||||||
url: prefix,
|
url: prefix,
|
||||||
data: params,
|
data: params,
|
||||||
headers: {
|
headers: {
|
||||||
"Accept-Language": "en_US",
|
'Accept-Language': 'en_US',
|
||||||
...(isFormData ? {} : { "Content-Type": "application/json" }),
|
...(isFormData ? {} : { 'Content-Type': 'application/json' }),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const rawToken = localStorage.getItem("token");
|
const rawToken = localStorage.getItem('token');
|
||||||
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 });
|
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await instance(request);
|
|
||||||
console.log("✅ API Response:", { url: prefix, status: response.status, statusCode: response.data?.statusCode });
|
|
||||||
return { ...response, error: false };
|
|
||||||
} catch (error) {
|
|
||||||
const status = error?.response?.status || 500;
|
|
||||||
const message = error?.response?.data?.message || error.message || "Something Wrong";
|
|
||||||
console.error("❌ API Error:", {
|
|
||||||
url: prefix,
|
|
||||||
status,
|
|
||||||
message,
|
|
||||||
fullError: error?.response?.data
|
|
||||||
});
|
|
||||||
|
|
||||||
if (status !== 401) {
|
|
||||||
await cekError(status, message);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return { ...error.response, error: true };
|
console.log('📤 API Request:', { method, url: prefix, hasToken: !!rawToken });
|
||||||
}
|
|
||||||
|
try {
|
||||||
|
const response = await instance(request);
|
||||||
|
console.log('✅ API Response:', {
|
||||||
|
url: prefix,
|
||||||
|
status: response.status,
|
||||||
|
statusCode: response.data?.statusCode,
|
||||||
|
});
|
||||||
|
return { ...response, error: false };
|
||||||
|
} catch (error) {
|
||||||
|
const status = error?.response?.status || 500;
|
||||||
|
const message = error?.response?.data?.message || error.message || 'Something Wrong';
|
||||||
|
console.error('❌ API Error:', {
|
||||||
|
url: prefix,
|
||||||
|
status,
|
||||||
|
message,
|
||||||
|
fullError: error?.response?.data,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (status !== 401) {
|
||||||
|
await cekError(status, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ...error.response, error: true };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function cekError(status, message = "") {
|
async function cekError(status, message = '') {
|
||||||
if (status === 403) {
|
if (status === 403) {
|
||||||
await Swal.fire({
|
await Swal.fire({
|
||||||
icon: "warning",
|
icon: 'warning',
|
||||||
title: "Forbidden",
|
title: 'Forbidden',
|
||||||
text: message,
|
text: message,
|
||||||
});
|
});
|
||||||
} else if (status >= 500) {
|
} else if (status >= 500) {
|
||||||
await Swal.fire({
|
await Swal.fire({
|
||||||
icon: "error",
|
icon: 'error',
|
||||||
title: "Server Error",
|
title: 'Server Error',
|
||||||
text: message,
|
text: message,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
await Swal.fire({
|
await Swal.fire({
|
||||||
icon: "warning",
|
icon: 'warning',
|
||||||
title: "Peringatan",
|
title: 'Peringatan',
|
||||||
text: message,
|
text: 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:", {
|
console.log('📦 SendRequest response:', {
|
||||||
hasError: response.error,
|
hasError: response.error,
|
||||||
status: response.status,
|
status: response.status,
|
||||||
statusCode: response.data?.statusCode,
|
statusCode: response.data?.statusCode,
|
||||||
data: response.data
|
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);
|
console.error('❌ SendRequest error response:', errorMsg);
|
||||||
|
|
||||||
// Return consistent error structure instead of empty array
|
// Return consistent error structure instead of empty array
|
||||||
return {
|
return {
|
||||||
statusCode: response.status || 500,
|
statusCode: response.status || 500,
|
||||||
message: errorMsg,
|
message: errorMsg,
|
||||||
data: null,
|
data: null,
|
||||||
error: true
|
error: true,
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return response || { statusCode: 200, data: [], message: 'Success' };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ SendRequest catch error:', error);
|
||||||
|
|
||||||
|
// Don't show Swal here, let the calling code handle it
|
||||||
|
// This allows better error handling in each API call
|
||||||
|
return {
|
||||||
|
statusCode: 500,
|
||||||
|
message: error.message || 'Something went wrong',
|
||||||
|
data: null,
|
||||||
|
error: true,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
return response?.data || { statusCode: 200, data: [], message: "Success" };
|
|
||||||
} catch (error) {
|
|
||||||
console.error("❌ SendRequest catch error:", error);
|
|
||||||
|
|
||||||
// Don't show Swal here, let the calling code handle it
|
|
||||||
// This allows better error handling in each API call
|
|
||||||
return {
|
|
||||||
statusCode: 500,
|
|
||||||
message: error.message || "Something went wrong",
|
|
||||||
data: null,
|
|
||||||
error: true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export { ApiRequest, SendRequest };
|
export { ApiRequest, SendRequest };
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ const CardList = ({
|
|||||||
return (
|
return (
|
||||||
<Row gutter={[16, 16]} style={{ marginTop: '16px', justifyContent: 'left' }}>
|
<Row gutter={[16, 16]} style={{ marginTop: '16px', justifyContent: 'left' }}>
|
||||||
{data.map((item) => (
|
{data.map((item) => (
|
||||||
<Col xs={24} sm={24} md={12} lg={8} key={item.device_id}>
|
<Col xs={24} sm={24} md={12} lg={6} key={item.device_id}>
|
||||||
<Card
|
<Card
|
||||||
title={
|
title={
|
||||||
<div
|
<div
|
||||||
|
|||||||
@@ -1,18 +1,6 @@
|
|||||||
import React, { memo, useState, useEffect, useRef } from 'react';
|
import React, { memo, useState, useEffect, useRef } from 'react';
|
||||||
import { Table, Pagination, Row, Col, Card, Grid, Button, Typography, Tag, Segmented } from 'antd';
|
import { Table, Pagination, Row, Col, Card, Grid, Button, Typography, Tag, Segmented } from 'antd';
|
||||||
import {
|
import { AppstoreOutlined, TableOutlined } from '@ant-design/icons';
|
||||||
PlusOutlined,
|
|
||||||
FilterOutlined,
|
|
||||||
EditOutlined,
|
|
||||||
DeleteOutlined,
|
|
||||||
EyeOutlined,
|
|
||||||
SearchOutlined,
|
|
||||||
FilePdfOutlined,
|
|
||||||
AppstoreOutlined,
|
|
||||||
TableOutlined,
|
|
||||||
} from '@ant-design/icons';
|
|
||||||
import { setFilterData } from './DataFilter';
|
|
||||||
import CardDevice from '../../pages/master/device/component/CardDevice';
|
|
||||||
import CardList from './CardList';
|
import CardList from './CardList';
|
||||||
|
|
||||||
const { Text } = Typography;
|
const { Text } = Typography;
|
||||||
@@ -33,16 +21,12 @@ const TableList = memo(function TableList({
|
|||||||
const [gridLoading, setGridLoading] = useState(false);
|
const [gridLoading, setGridLoading] = useState(false);
|
||||||
|
|
||||||
const [data, setData] = useState([]);
|
const [data, setData] = useState([]);
|
||||||
const [pagingResponse, setPagingResponse] = useState({
|
|
||||||
totalData: 0,
|
|
||||||
perPage: 0,
|
|
||||||
totalPage: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
const [pagination, setPagination] = useState({
|
const [pagination, setPagination] = useState({
|
||||||
current: 1,
|
current_page: 1,
|
||||||
limit: 10,
|
current_limit: 10,
|
||||||
total: 0,
|
total_limit: 0,
|
||||||
|
total_page: 1,
|
||||||
});
|
});
|
||||||
|
|
||||||
const [viewMode, setViewMode] = useState('card');
|
const [viewMode, setViewMode] = useState('card');
|
||||||
@@ -50,20 +34,34 @@ const TableList = memo(function TableList({
|
|||||||
const { useBreakpoint } = Grid;
|
const { useBreakpoint } = Grid;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
filter(1, 10);
|
filter(1, pagination.current_limit);
|
||||||
}, [triger]);
|
}, [triger]);
|
||||||
|
|
||||||
const filter = async (currentPage, pageSize) => {
|
const filter = async (currentPage, pageSize) => {
|
||||||
setGridLoading(true);
|
setGridLoading(true);
|
||||||
|
|
||||||
const paging = {
|
const paging = {
|
||||||
page: currentPage,
|
page: Number(currentPage),
|
||||||
limit: pageSize,
|
limit: Number(pageSize),
|
||||||
};
|
};
|
||||||
|
|
||||||
const param = new URLSearchParams({ ...paging, ...queryParams });
|
const param = new URLSearchParams({ ...paging, ...queryParams });
|
||||||
const resData = await getData(param);
|
const resData = await getData(param);
|
||||||
|
|
||||||
|
setData(resData?.data ?? []);
|
||||||
|
|
||||||
|
const pagingData = resData?.paging;
|
||||||
|
|
||||||
|
if (pagingData) {
|
||||||
|
setPagination((prev) => ({
|
||||||
|
...prev,
|
||||||
|
current_page: pagingData.current_page || 1,
|
||||||
|
current_limit: pagingData.current_limit || 10,
|
||||||
|
total_limit: pagingData.total_limit || 0,
|
||||||
|
total_page: pagingData.total_page || 1,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
if (resData) {
|
if (resData) {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
setGridLoading(false);
|
setGridLoading(false);
|
||||||
@@ -72,29 +70,6 @@ const TableList = memo(function TableList({
|
|||||||
setGridLoading(false);
|
setGridLoading(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const dataToSet = resData.data?.data ?? resData.data ?? [];
|
|
||||||
setData(dataToSet);
|
|
||||||
setFilterData(dataToSet);
|
|
||||||
|
|
||||||
if (resData.status == 200) {
|
|
||||||
const pagingData = resData.data?.paging;
|
|
||||||
|
|
||||||
if (pagingData) {
|
|
||||||
setPagingResponse({
|
|
||||||
totalData: pagingData.total || 0,
|
|
||||||
perPage: pagingData.limit || 0,
|
|
||||||
totalPage: pagingData.page_total || 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
setPagination((prev) => ({
|
|
||||||
...prev,
|
|
||||||
current: pagingData.page || 1,
|
|
||||||
limit: pagingData.limit || 10,
|
|
||||||
total: pagingData.total || 0,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handlePaginationChange = (page, pageSize) => {
|
const handlePaginationChange = (page, pageSize) => {
|
||||||
@@ -146,8 +121,8 @@ const TableList = memo(function TableList({
|
|||||||
<Row justify="space-between" align="middle">
|
<Row justify="space-between" align="middle">
|
||||||
<Col>
|
<Col>
|
||||||
<div>
|
<div>
|
||||||
Menampilkan {pagingResponse.totalData} Data dari {pagingResponse.totalPage}{' '}
|
Menampilkan {pagination.current_limit} data halaman{' '}
|
||||||
Halaman
|
{pagination.current_page} dari total {pagination.total_limit} data
|
||||||
</div>
|
</div>
|
||||||
</Col>
|
</Col>
|
||||||
<Col>
|
<Col>
|
||||||
@@ -155,9 +130,9 @@ const TableList = memo(function TableList({
|
|||||||
showSizeChanger
|
showSizeChanger
|
||||||
onChange={handlePaginationChange}
|
onChange={handlePaginationChange}
|
||||||
onShowSizeChange={handlePaginationChange}
|
onShowSizeChange={handlePaginationChange}
|
||||||
current={pagination.current}
|
current={pagination.current_page}
|
||||||
pageSize={pagination.limit}
|
pageSize={pagination.current_limit}
|
||||||
total={pagination.total}
|
total={pagination.total_limit}
|
||||||
/>
|
/>
|
||||||
</Col>
|
</Col>
|
||||||
</Row>
|
</Row>
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ const NotifOk = ({ icon, title, message }) => {
|
|||||||
icon: icon,
|
icon: icon,
|
||||||
title: title,
|
title: title,
|
||||||
text: message,
|
text: message,
|
||||||
|
html: message.replace(/\n/g, '<br/>'),
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,461 +0,0 @@
|
|||||||
// import React, { useState } from 'react';
|
|
||||||
// import {
|
|
||||||
// Flex,
|
|
||||||
// Input,
|
|
||||||
// InputNumber,
|
|
||||||
// Form,
|
|
||||||
// Button,
|
|
||||||
// Card,
|
|
||||||
// Space,
|
|
||||||
// Upload,
|
|
||||||
// Divider,
|
|
||||||
// Tooltip,
|
|
||||||
// message,
|
|
||||||
// Select,
|
|
||||||
// } from 'antd';
|
|
||||||
// import {
|
|
||||||
// UploadOutlined,
|
|
||||||
// UserOutlined,
|
|
||||||
// IdcardOutlined,
|
|
||||||
// PhoneOutlined,
|
|
||||||
// LockOutlined,
|
|
||||||
// InfoCircleOutlined,
|
|
||||||
// MailOutlined,
|
|
||||||
// } from '@ant-design/icons';
|
|
||||||
// const { Item } = Form;
|
|
||||||
// const { Option } = Select;
|
|
||||||
// import sypiu_ggcp from 'assets/sypiu_ggcp.jpg';
|
|
||||||
// import { useNavigate } from 'react-router-dom';
|
|
||||||
// import { register, uploadFile, checkUsername } from '../../api/auth';
|
|
||||||
// import { NotifAlert } from '../../components/Global/ToastNotif';
|
|
||||||
|
|
||||||
// const Registration = () => {
|
|
||||||
// const [form] = Form.useForm();
|
|
||||||
// const navigate = useNavigate();
|
|
||||||
// const [loading, setLoading] = useState(false);
|
|
||||||
// const [fileListKontrak, setFileListKontrak] = useState([]);
|
|
||||||
// const [fileListHsse, setFileListHsse] = useState([]);
|
|
||||||
// const [fileListIcon, setFileListIcon] = useState([]);
|
|
||||||
|
|
||||||
// // Daftar jenis vendor
|
|
||||||
// const vendorTypes = [
|
|
||||||
// { vendor_type: 1, vendor_type_name: 'One-Time' },
|
|
||||||
// { vendor_type: 2, vendor_type_name: 'Rutin' },
|
|
||||||
// ];
|
|
||||||
|
|
||||||
// const onFinish = async (values) => {
|
|
||||||
// setLoading(true);
|
|
||||||
// try {
|
|
||||||
// if (!fileListKontrak.length || !fileListHsse.length) {
|
|
||||||
// message.error('Harap unggah Lampiran Kontrak Kerja dan HSSE Plan!');
|
|
||||||
// setLoading(false);
|
|
||||||
// return;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// const formData = new FormData();
|
|
||||||
// formData.append('path_kontrak', fileListKontrak[0].originFileObj);
|
|
||||||
// formData.append('path_hse_plant', fileListHsse[0].originFileObj);
|
|
||||||
// if (fileListIcon.length) {
|
|
||||||
// formData.append('path_icon', fileListIcon[0].originFileObj);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// const uploadResponse = await uploadFile(formData);
|
|
||||||
|
|
||||||
// if (!uploadResponse.data?.pathKontrak && !uploadResponse.data?.pathHsePlant) {
|
|
||||||
// message.error(uploadResponse.message || 'Gagal mengunggah file.');
|
|
||||||
// setLoading(false);
|
|
||||||
// return;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// const params = new URLSearchParams({ username: values.username });
|
|
||||||
// const usernameCheck = await checkUsername(params);
|
|
||||||
// if (usernameCheck.data.data && usernameCheck.data.data.available === false) {
|
|
||||||
// NotifAlert({
|
|
||||||
// icon: 'error',
|
|
||||||
// title: 'Gagal',
|
|
||||||
// message: usernameCheck.data.message || 'Terjadi kesalahan, silakan coba lagi',
|
|
||||||
// });
|
|
||||||
// setLoading(false);
|
|
||||||
// return;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// const registerData = {
|
|
||||||
// nama_perusahaan: values.namaPerusahaan,
|
|
||||||
// no_kontak_wo: values.noKontakWo,
|
|
||||||
// path_kontrak: uploadResponse.data.pathKontrak || '',
|
|
||||||
// durasi: values.durasiPekerjaan,
|
|
||||||
// nilai_csms: values.nilaiCsms.toString(),
|
|
||||||
// vendor_type: values.jenisVendor, // Tambahkan jenis vendor ke registerData
|
|
||||||
// path_hse_plant: uploadResponse.data.pathHsePlant || '',
|
|
||||||
// nama_leader: values.penanggungJawab,
|
|
||||||
// no_identitas: values.noIdentitas,
|
|
||||||
// no_hp: values.noHandphone,
|
|
||||||
// email_register: values.username,
|
|
||||||
// password_register: values.password,
|
|
||||||
// };
|
|
||||||
|
|
||||||
// const response = await register(registerData);
|
|
||||||
|
|
||||||
// if (response.data?.id_register) {
|
|
||||||
// message.success('Data berhasil disimpan!');
|
|
||||||
|
|
||||||
// try {
|
|
||||||
// form.resetFields();
|
|
||||||
// setFileListKontrak([]);
|
|
||||||
// setFileListHsse([]);
|
|
||||||
// setFileListIcon([]);
|
|
||||||
|
|
||||||
// navigate('/registration-submitted');
|
|
||||||
// } catch (postSuccessError) {
|
|
||||||
// message.warning(
|
|
||||||
// 'Registrasi berhasil, tetapi ada masalah setelahnya. Silakan ke halaman login secara manual.'
|
|
||||||
// );
|
|
||||||
// }
|
|
||||||
// } else {
|
|
||||||
// message.error(response.message || 'Pendaftaran gagal, silakan coba lagi.');
|
|
||||||
// }
|
|
||||||
// } catch (error) {
|
|
||||||
// console.error('Error saat registrasi:', error);
|
|
||||||
// NotifAlert({
|
|
||||||
// icon: 'error',
|
|
||||||
// title: 'Gagal',
|
|
||||||
// message: error.message || 'Terjadi kesalahan, silakan coba lagi',
|
|
||||||
// });
|
|
||||||
// } finally {
|
|
||||||
// setLoading(false);
|
|
||||||
// }
|
|
||||||
// };
|
|
||||||
|
|
||||||
// const onCancel = () => {
|
|
||||||
// form.resetFields();
|
|
||||||
// setFileListKontrak([]);
|
|
||||||
// setFileListHsse([]);
|
|
||||||
// setFileListIcon([]);
|
|
||||||
// navigate('/signin');
|
|
||||||
// };
|
|
||||||
|
|
||||||
// const handleChangeKontrak = ({ fileList }) => {
|
|
||||||
// setFileListKontrak(fileList);
|
|
||||||
// };
|
|
||||||
|
|
||||||
// const handleChangeHsse = ({ fileList }) => {
|
|
||||||
// setFileListHsse(fileList);
|
|
||||||
// };
|
|
||||||
|
|
||||||
// const handleChangeIcon = ({ fileList }) => {
|
|
||||||
// setFileListIcon(fileList);
|
|
||||||
// };
|
|
||||||
|
|
||||||
// const beforeUpload = (file, fieldname) => {
|
|
||||||
// const isValidType = [
|
|
||||||
// 'image/jpeg',
|
|
||||||
// 'image/jpg',
|
|
||||||
// 'image/png',
|
|
||||||
// fieldname !== 'path_icon' ? 'application/pdf' : null,
|
|
||||||
// ]
|
|
||||||
// .filter(Boolean)
|
|
||||||
// .includes(file.type);
|
|
||||||
// const isNotEmpty = file.size > 0;
|
|
||||||
// const isSizeValid = file.size / 1024 / 1024 < 10;
|
|
||||||
|
|
||||||
// if (!isValidType) {
|
|
||||||
// message.error(
|
|
||||||
// `Hanya file ${
|
|
||||||
// fieldname === 'path_icon' ? 'JPG/PNG' : 'PDF/JPG/PNG'
|
|
||||||
// } yang diperbolehkan!`
|
|
||||||
// );
|
|
||||||
// return false;
|
|
||||||
// }
|
|
||||||
// if (!isNotEmpty) {
|
|
||||||
// message.error('File tidak boleh kosong!');
|
|
||||||
// return false;
|
|
||||||
// }
|
|
||||||
// if (!isSizeValid) {
|
|
||||||
// message.error('Ukuran file maksimal 10MB!');
|
|
||||||
// return false;
|
|
||||||
// }
|
|
||||||
// return true;
|
|
||||||
// };
|
|
||||||
|
|
||||||
// return (
|
|
||||||
// <Flex
|
|
||||||
// align="center"
|
|
||||||
// justify="center"
|
|
||||||
// style={{
|
|
||||||
// minHeight: '100vh',
|
|
||||||
// backgroundImage: `url(${sypiu_ggcp})`,
|
|
||||||
// backgroundSize: 'cover',
|
|
||||||
// backgroundPosition: 'center',
|
|
||||||
// padding: '20px',
|
|
||||||
// }}
|
|
||||||
// >
|
|
||||||
// <Card
|
|
||||||
// style={{
|
|
||||||
// width: '100%',
|
|
||||||
// maxWidth: 800,
|
|
||||||
// background: 'rgba(255, 255, 255, 0.9)',
|
|
||||||
// backdropFilter: 'blur(10px)',
|
|
||||||
// borderRadius: '12px',
|
|
||||||
// boxShadow: '0 8px 16px rgba(0, 0, 0, 0.1)',
|
|
||||||
// padding: '24px',
|
|
||||||
// }}
|
|
||||||
// title={
|
|
||||||
// <Flex align="center" justify="space-between">
|
|
||||||
// <h2 style={{ margin: 0, color: '#1a3c34' }}>Formulir Pendaftaran</h2>
|
|
||||||
// <Button
|
|
||||||
// type="link"
|
|
||||||
// icon={<InfoCircleOutlined />}
|
|
||||||
// onClick={() => navigate('/signin')}
|
|
||||||
// >
|
|
||||||
// Kembali
|
|
||||||
// </Button>
|
|
||||||
// </Flex>
|
|
||||||
// }
|
|
||||||
// >
|
|
||||||
// <Form
|
|
||||||
// form={form}
|
|
||||||
// onFinish={onFinish}
|
|
||||||
// layout="horizontal"
|
|
||||||
// labelCol={{ span: 8 }}
|
|
||||||
// wrapperCol={{ span: 16 }}
|
|
||||||
// labelAlign="left"
|
|
||||||
// style={{ maxWidth: 800 }}
|
|
||||||
// >
|
|
||||||
// {/* Informasi Perusahaan */}
|
|
||||||
// <Divider
|
|
||||||
// orientation="left"
|
|
||||||
// orientationMargin={0}
|
|
||||||
// style={{
|
|
||||||
// color: '#23A55A',
|
|
||||||
// fontWeight: 'bold',
|
|
||||||
// marginLeft: 0,
|
|
||||||
// paddingLeft: 0,
|
|
||||||
// }}
|
|
||||||
// >
|
|
||||||
// Informasi Perusahaan
|
|
||||||
// </Divider>
|
|
||||||
// <Item
|
|
||||||
// label="Nama Perusahaan"
|
|
||||||
// name="namaPerusahaan"
|
|
||||||
// rules={[{ required: true, message: 'Masukkan Nama Perusahaan!' }]}
|
|
||||||
// >
|
|
||||||
// <Input
|
|
||||||
// prefix={<UserOutlined />}
|
|
||||||
// placeholder="Masukkan Nama Perusahaan"
|
|
||||||
// size="large"
|
|
||||||
// />
|
|
||||||
// </Item>
|
|
||||||
// <Item
|
|
||||||
// label="Durasi Pekerjaan (Hari)"
|
|
||||||
// name="durasiPekerjaan"
|
|
||||||
// rules={[{ required: true, message: 'Masukkan Durasi Pekerjaan!' }]}
|
|
||||||
// >
|
|
||||||
// <InputNumber
|
|
||||||
// min={1}
|
|
||||||
// style={{ width: '100%' }}
|
|
||||||
// placeholder="Masukkan Durasi Pekerjaan"
|
|
||||||
// size="large"
|
|
||||||
// />
|
|
||||||
// </Item>
|
|
||||||
// <Item
|
|
||||||
// label="No Kontrak Kerja / Agreement"
|
|
||||||
// name="noKontakWo"
|
|
||||||
// rules={[
|
|
||||||
// { required: true, message: 'Masukkan No Kontrak Kerja / Agreement!' },
|
|
||||||
// ]}
|
|
||||||
// >
|
|
||||||
// <Input
|
|
||||||
// style={{
|
|
||||||
// width: '100%',
|
|
||||||
// }}
|
|
||||||
// placeholder="Masukkan No Kontrak Kerja / Agreement"
|
|
||||||
// size="large"
|
|
||||||
// />
|
|
||||||
// </Item>
|
|
||||||
// <Item
|
|
||||||
// label="Lampiran Kontrak Kerja"
|
|
||||||
// name="lampiranKontrak"
|
|
||||||
// rules={[{ required: true, message: 'Unggah Lampiran Kontrak Kerja!' }]}
|
|
||||||
// >
|
|
||||||
// <Upload
|
|
||||||
// beforeUpload={(file) => beforeUpload(file, 'path_kontrak')}
|
|
||||||
// fileList={fileListKontrak}
|
|
||||||
// onChange={handleChangeKontrak}
|
|
||||||
// maxCount={1}
|
|
||||||
// >
|
|
||||||
// <Button icon={<UploadOutlined />} size="large">
|
|
||||||
// Unggah PDF/JPG
|
|
||||||
// </Button>
|
|
||||||
// </Upload>
|
|
||||||
// </Item>
|
|
||||||
// <Item
|
|
||||||
// label="HSSE Plan"
|
|
||||||
// name="hssePlan"
|
|
||||||
// rules={[{ required: true, message: 'Unggah HSSE Plan!' }]}
|
|
||||||
// >
|
|
||||||
// <Upload
|
|
||||||
// beforeUpload={(file) => beforeUpload(file, 'path_hse_plant')}
|
|
||||||
// fileList={fileListHsse}
|
|
||||||
// onChange={handleChangeHsse}
|
|
||||||
// maxCount={1}
|
|
||||||
// >
|
|
||||||
// <Button icon={<UploadOutlined />} size="large">
|
|
||||||
// Unggah PDF/JPG
|
|
||||||
// </Button>
|
|
||||||
// </Upload>
|
|
||||||
// </Item>
|
|
||||||
// <Item
|
|
||||||
// label="Nilai CSMS"
|
|
||||||
// name="nilaiCsms"
|
|
||||||
// rules={[{ required: true, message: 'Masukkan Nilai CSMS!' }]}
|
|
||||||
// >
|
|
||||||
// <InputNumber
|
|
||||||
// min={0}
|
|
||||||
// max={100}
|
|
||||||
// style={{ width: '100%' }}
|
|
||||||
// placeholder="Masukkan Nilai CSMS"
|
|
||||||
// size="large"
|
|
||||||
// />
|
|
||||||
// </Item>
|
|
||||||
// <Item
|
|
||||||
// label="Jenis Vendor"
|
|
||||||
// name="jenisVendor"
|
|
||||||
// rules={[{ required: true, message: 'Pilih Jenis Vendor!' }]}
|
|
||||||
// >
|
|
||||||
// <Select
|
|
||||||
// placeholder="Pilih Jenis Vendor"
|
|
||||||
// size="large"
|
|
||||||
// style={{ width: '100%' }}
|
|
||||||
// >
|
|
||||||
// {vendorTypes.map((vendor) => (
|
|
||||||
// <Option key={vendor.vendor_type} value={vendor.vendor_type}>
|
|
||||||
// {vendor.vendor_type_name}
|
|
||||||
// </Option>
|
|
||||||
// ))}
|
|
||||||
// </Select>
|
|
||||||
// </Item>
|
|
||||||
|
|
||||||
// {/* Informasi Penanggung Jawab */}
|
|
||||||
// <Divider
|
|
||||||
// orientation="left"
|
|
||||||
// orientationMargin={0}
|
|
||||||
// style={{
|
|
||||||
// color: '#23A55A',
|
|
||||||
// fontWeight: 'bold',
|
|
||||||
// marginLeft: 0,
|
|
||||||
// paddingLeft: 0,
|
|
||||||
// }}
|
|
||||||
// >
|
|
||||||
// Informasi Penanggung Jawab
|
|
||||||
// </Divider>
|
|
||||||
// <Item
|
|
||||||
// label="Nama Penanggung Jawab"
|
|
||||||
// name="penanggungJawab"
|
|
||||||
// rules={[{ required: true, message: 'Masukkan Nama Penanggung Jawab!' }]}
|
|
||||||
// >
|
|
||||||
// <Input
|
|
||||||
// prefix={<UserOutlined />}
|
|
||||||
// placeholder="Masukkan Nama Penanggung Jawab"
|
|
||||||
// size="large"
|
|
||||||
// />
|
|
||||||
// </Item>
|
|
||||||
// <Item
|
|
||||||
// label="No Handphone"
|
|
||||||
// name="noHandphone"
|
|
||||||
// rules={[
|
|
||||||
// { required: true, message: 'Masukkan No Handphone!' },
|
|
||||||
// {
|
|
||||||
// pattern: /^(\+62|0)[0-9]{9,12}$/,
|
|
||||||
// message:
|
|
||||||
// 'Format nomor telepon tidak valid! (Contoh: +62.... atau 0....)',
|
|
||||||
// },
|
|
||||||
// ]}
|
|
||||||
// >
|
|
||||||
// <Input
|
|
||||||
// prefix={<PhoneOutlined />}
|
|
||||||
// placeholder="Masukkan No Handphone (+62)"
|
|
||||||
// size="large"
|
|
||||||
// />
|
|
||||||
// </Item>
|
|
||||||
// <Item
|
|
||||||
// label="No Identitas"
|
|
||||||
// name="noIdentitas"
|
|
||||||
// rules={[{ required: true, message: 'Masukkan No Identitas!' }]}
|
|
||||||
// >
|
|
||||||
// <Input
|
|
||||||
// prefix={<IdcardOutlined />}
|
|
||||||
// placeholder="Masukkan No Identitas"
|
|
||||||
// size="large"
|
|
||||||
// />
|
|
||||||
// </Item>
|
|
||||||
|
|
||||||
// {/* Akun Pengguna */}
|
|
||||||
// <Divider
|
|
||||||
// orientation="left"
|
|
||||||
// orientationMargin={0}
|
|
||||||
// style={{
|
|
||||||
// color: '#23A55A',
|
|
||||||
// fontWeight: 'bold',
|
|
||||||
// marginLeft: 0,
|
|
||||||
// paddingLeft: 0,
|
|
||||||
// }}
|
|
||||||
// >
|
|
||||||
// Akun Pengguna (digunakan sebagai user login SYPIU)
|
|
||||||
// </Divider>
|
|
||||||
// <Item
|
|
||||||
// label="Email"
|
|
||||||
// name="username"
|
|
||||||
// rules={[
|
|
||||||
// { required: true, message: 'Masukkan Email!' },
|
|
||||||
// { type: 'email', message: 'Format email tidak valid!' },
|
|
||||||
// ]}
|
|
||||||
// >
|
|
||||||
// <Input
|
|
||||||
// prefix={<MailOutlined />}
|
|
||||||
// placeholder="Masukkan Email"
|
|
||||||
// size="large"
|
|
||||||
// />
|
|
||||||
// </Item>
|
|
||||||
// <Item
|
|
||||||
// label="Password"
|
|
||||||
// name="password"
|
|
||||||
// rules={[
|
|
||||||
// { required: true, message: 'Masukkan Password!' },
|
|
||||||
// { min: 6, message: 'Password minimal 6 karakter!' },
|
|
||||||
// ]}
|
|
||||||
// >
|
|
||||||
// <Input.Password
|
|
||||||
// prefix={<LockOutlined />}
|
|
||||||
// placeholder="Masukkan Password"
|
|
||||||
// size="large"
|
|
||||||
// />
|
|
||||||
// </Item>
|
|
||||||
|
|
||||||
// {/* Tombol */}
|
|
||||||
// <Item wrapperCol={{ offset: 8, span: 16 }}>
|
|
||||||
// <Space style={{ marginTop: '24px', width: '100%' }}>
|
|
||||||
// <Button
|
|
||||||
// type="primary"
|
|
||||||
// htmlType="submit"
|
|
||||||
// size="large"
|
|
||||||
// loading={loading}
|
|
||||||
// style={{
|
|
||||||
// backgroundColor: '#23A55A',
|
|
||||||
// borderColor: '#23A55A',
|
|
||||||
// width: 120,
|
|
||||||
// }}
|
|
||||||
// >
|
|
||||||
// Simpan
|
|
||||||
// </Button>
|
|
||||||
// <Button onClick={onCancel} size="large" style={{ width: 120 }}>
|
|
||||||
// Batal
|
|
||||||
// </Button>
|
|
||||||
// </Space>
|
|
||||||
// </Item>
|
|
||||||
// </Form>
|
|
||||||
// </Card>
|
|
||||||
// </Flex>
|
|
||||||
// );
|
|
||||||
// };
|
|
||||||
|
|
||||||
// export default Registration;
|
|
||||||
@@ -31,8 +31,9 @@ const SignIn = () => {
|
|||||||
prefix: 'auth/generate-captcha',
|
prefix: 'auth/generate-captcha',
|
||||||
token: false,
|
token: false,
|
||||||
});
|
});
|
||||||
setCaptchaSvg(res.data.svg || '');
|
|
||||||
setCaptchaText(res.data.text || '');
|
setCaptchaSvg(res.data?.data?.svg || '');
|
||||||
|
setCaptchaText(res.data?.data?.text || '');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Error fetching captcha:', err);
|
console.error('Error fetching captcha:', err);
|
||||||
}
|
}
|
||||||
@@ -57,8 +58,8 @@ const SignIn = () => {
|
|||||||
withCredentials: true,
|
withCredentials: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
const user = res?.data?.user || res?.user;
|
const user = res?.data?.data?.user || res?.user;
|
||||||
const accessToken = res?.data?.accessToken || res?.tokens?.accessToken;
|
const accessToken = res?.data?.data?.accessToken || res?.tokens?.accessToken;
|
||||||
|
|
||||||
if (user && accessToken) {
|
if (user && accessToken) {
|
||||||
localStorage.setItem('token', accessToken);
|
localStorage.setItem('token', accessToken);
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
import { NotifAlert, NotifConfirmDialog } from '../../../../components/Global/ToastNotif';
|
import { NotifAlert, NotifConfirmDialog } from '../../../../components/Global/ToastNotif';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import TableList from '../../../../components/Global/TableList';
|
import TableList from '../../../../components/Global/TableList';
|
||||||
|
import { getAllBrands } from '../../../../api/master-brand';
|
||||||
|
|
||||||
// Dummy data
|
// Dummy data
|
||||||
const initialBrandDeviceData = [
|
const initialBrandDeviceData = [
|
||||||
@@ -145,55 +146,6 @@ const ListBrandDevice = memo(function ListBrandDevice(props) {
|
|||||||
|
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
// Dummy data function to simulate API call - now uses state
|
|
||||||
const getAllBrandDevice = async (params) => {
|
|
||||||
// Simulate API delay
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
||||||
|
|
||||||
// Extract URLSearchParams - TableList sends URLSearchParams object
|
|
||||||
const searchParam = params.get('search') || '';
|
|
||||||
const page = parseInt(params.get('page')) || 1;
|
|
||||||
const limit = parseInt(params.get('limit')) || 10;
|
|
||||||
|
|
||||||
console.log('getAllBrandDevice called with:', { searchParam, page, limit });
|
|
||||||
|
|
||||||
// Filter by search
|
|
||||||
let filteredBrandDevices = brandDeviceData;
|
|
||||||
if (searchParam) {
|
|
||||||
const searchLower = searchParam.toLowerCase();
|
|
||||||
filteredBrandDevices = brandDeviceData.filter(
|
|
||||||
(brand) =>
|
|
||||||
brand.brandName.toLowerCase().includes(searchLower) ||
|
|
||||||
brand.brandType.toLowerCase().includes(searchLower) ||
|
|
||||||
brand.manufacturer.toLowerCase().includes(searchLower) ||
|
|
||||||
brand.model.toLowerCase().includes(searchLower)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pagination logic
|
|
||||||
const totalData = filteredBrandDevices.length;
|
|
||||||
const totalPages = Math.ceil(totalData / limit);
|
|
||||||
const startIndex = (page - 1) * limit;
|
|
||||||
const endIndex = startIndex + limit;
|
|
||||||
const paginatedData = filteredBrandDevices.slice(startIndex, endIndex);
|
|
||||||
|
|
||||||
// Return structure that matches TableList expectation
|
|
||||||
return {
|
|
||||||
status: 200,
|
|
||||||
statusCode: 200,
|
|
||||||
data: {
|
|
||||||
data: paginatedData,
|
|
||||||
total: totalData,
|
|
||||||
paging: {
|
|
||||||
page: page,
|
|
||||||
limit: limit,
|
|
||||||
total: totalData,
|
|
||||||
page_total: totalPages,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const token = localStorage.getItem('token');
|
const token = localStorage.getItem('token');
|
||||||
if (token) {
|
if (token) {
|
||||||
@@ -333,7 +285,7 @@ const ListBrandDevice = memo(function ListBrandDevice(props) {
|
|||||||
showPreviewModal={showPreviewModal}
|
showPreviewModal={showPreviewModal}
|
||||||
showEditModal={showEditModal}
|
showEditModal={showEditModal}
|
||||||
showDeleteDialog={showDeleteDialog}
|
showDeleteDialog={showDeleteDialog}
|
||||||
getData={getAllBrandDevice}
|
getData={getAllBrands}
|
||||||
queryParams={formDataFilter}
|
queryParams={formDataFilter}
|
||||||
columns={columns(showPreviewModal, showEditModal, showDeleteDialog)}
|
columns={columns(showPreviewModal, showEditModal, showDeleteDialog)}
|
||||||
triger={trigerFilter}
|
triger={trigerFilter}
|
||||||
|
|||||||
@@ -1,20 +1,8 @@
|
|||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import {
|
import { Modal, Input, Divider, Typography, Switch, Button, ConfigProvider } from 'antd';
|
||||||
Modal,
|
|
||||||
Input,
|
|
||||||
Divider,
|
|
||||||
Typography,
|
|
||||||
Switch,
|
|
||||||
Button,
|
|
||||||
ConfigProvider,
|
|
||||||
Radio,
|
|
||||||
Select,
|
|
||||||
} from 'antd';
|
|
||||||
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
|
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
|
||||||
import { createApd, getJenisPermit, updateApd } from '../../../../api/master-apd';
|
import { createDevice, updateDevice } from '../../../../api/master-device';
|
||||||
import { createDevice, updateDevice, getAllDevice } from '../../../../api/master-device';
|
import { validateRun } from '../../../../Utils/validate';
|
||||||
import { Checkbox } from 'antd';
|
|
||||||
const CheckboxGroup = Checkbox.Group;
|
|
||||||
|
|
||||||
const { Text } = Typography;
|
const { Text } = Typography;
|
||||||
const { TextArea } = Input;
|
const { TextArea } = Input;
|
||||||
@@ -27,156 +15,60 @@ const DetailDevice = (props) => {
|
|||||||
device_code: '',
|
device_code: '',
|
||||||
device_name: '',
|
device_name: '',
|
||||||
is_active: true,
|
is_active: true,
|
||||||
device_location: 'Building A',
|
device_location: '',
|
||||||
device_description: '',
|
device_description: '',
|
||||||
ip_address: '',
|
ip_address: '',
|
||||||
};
|
};
|
||||||
|
|
||||||
const [FormData, setFormData] = useState(defaultData);
|
const [formData, setFormData] = useState(defaultData);
|
||||||
const [nextDeviceCode, setNextDeviceCode] = useState('Auto-fill');
|
|
||||||
|
|
||||||
const [jenisPermit, setJenisPermit] = useState([]);
|
|
||||||
const [checkedList, setCheckedList] = useState([]);
|
|
||||||
|
|
||||||
const onChange = (list) => {
|
|
||||||
setCheckedList(list);
|
|
||||||
};
|
|
||||||
|
|
||||||
const onChangeRadio = (e) => {
|
|
||||||
setFormData({
|
|
||||||
...FormData,
|
|
||||||
type_input: e.target.value,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const getDataJenisPermit = async () => {
|
|
||||||
setCheckedList([]);
|
|
||||||
const result = await getJenisPermit();
|
|
||||||
const data = result.data ?? [];
|
|
||||||
const names = data.map((item) => ({
|
|
||||||
value: item.id_jenis_permit,
|
|
||||||
label: item.nama_jenis_permit,
|
|
||||||
}));
|
|
||||||
setJenisPermit(names);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCancel = () => {
|
const handleCancel = () => {
|
||||||
props.setSelectedData(null);
|
props.setSelectedData(null);
|
||||||
props.setActionMode('list');
|
props.setActionMode('list');
|
||||||
};
|
};
|
||||||
|
|
||||||
const validateIPAddress = (ip) => {
|
|
||||||
const ipRegex =
|
|
||||||
/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
|
|
||||||
return ipRegex.test(ip);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
setConfirmLoading(true);
|
setConfirmLoading(true);
|
||||||
|
|
||||||
// Validasi required fields
|
// Daftar aturan validasi
|
||||||
// if (!FormData.device_code) {
|
const validationRules = [
|
||||||
// NotifOk({
|
{ field: 'device_name', label: 'Device Name', required: true },
|
||||||
// icon: 'warning',
|
{ field: 'ip_address', label: 'Ip Address', required: true, ip: true },
|
||||||
// title: 'Peringatan',
|
];
|
||||||
// message: 'Kolom Device Code Tidak Boleh Kosong',
|
|
||||||
// });
|
|
||||||
// setConfirmLoading(false);
|
|
||||||
// return;
|
|
||||||
// }
|
|
||||||
|
|
||||||
if (!FormData.device_name) {
|
if (
|
||||||
NotifOk({
|
validateRun(formData, validationRules, (errorMessages) => {
|
||||||
icon: 'warning',
|
NotifOk({
|
||||||
title: 'Peringatan',
|
icon: 'warning',
|
||||||
message: 'Kolom Device Name Tidak Boleh Kosong',
|
title: 'Peringatan',
|
||||||
});
|
message: errorMessages,
|
||||||
setConfirmLoading(false);
|
});
|
||||||
|
setConfirmLoading(false);
|
||||||
|
})
|
||||||
|
)
|
||||||
return;
|
return;
|
||||||
}
|
|
||||||
|
|
||||||
if (!FormData.device_location) {
|
|
||||||
NotifOk({
|
|
||||||
icon: 'warning',
|
|
||||||
title: 'Peringatan',
|
|
||||||
message: 'Kolom Device Location Tidak Boleh Kosong',
|
|
||||||
});
|
|
||||||
setConfirmLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!FormData.ip_address) {
|
|
||||||
NotifOk({
|
|
||||||
icon: 'warning',
|
|
||||||
title: 'Peringatan',
|
|
||||||
message: 'Kolom IP Address Tidak Boleh Kosong',
|
|
||||||
});
|
|
||||||
setConfirmLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validasi format IP
|
|
||||||
if (!validateIPAddress(FormData.ip_address)) {
|
|
||||||
NotifOk({
|
|
||||||
icon: 'warning',
|
|
||||||
title: 'Peringatan',
|
|
||||||
message: 'Format IP Address Tidak Valid',
|
|
||||||
});
|
|
||||||
setConfirmLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.permitDefault && checkedList.length === 0) {
|
|
||||||
NotifOk({
|
|
||||||
icon: 'warning',
|
|
||||||
title: 'Peringatan',
|
|
||||||
message: 'Kolom Jenis Permit Tidak Boleh Kosong',
|
|
||||||
});
|
|
||||||
|
|
||||||
setConfirmLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Backend validation schema doesn't include device_code
|
|
||||||
const payload = {
|
|
||||||
device_name: FormData.device_name,
|
|
||||||
is_active: FormData.is_active,
|
|
||||||
device_location: FormData.device_location,
|
|
||||||
ip_address: FormData.ip_address,
|
|
||||||
};
|
|
||||||
|
|
||||||
// For CREATE: device_description is required (cannot be empty)
|
|
||||||
// For UPDATE: device_description is optional
|
|
||||||
if (!FormData.device_id) {
|
|
||||||
// Creating - ensure description is not empty
|
|
||||||
payload.device_description = FormData.device_description || '-';
|
|
||||||
} else {
|
|
||||||
// Updating - include description as-is
|
|
||||||
payload.device_description = FormData.device_description;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('Payload to send:', payload);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
let response;
|
const payload = {
|
||||||
if (!FormData.device_id) {
|
device_name: formData.device_name,
|
||||||
response = await createDevice(payload);
|
is_active: formData.is_active,
|
||||||
} else {
|
device_location: formData.device_location,
|
||||||
response = await updateDevice(FormData.device_id, payload);
|
ip_address: formData.ip_address,
|
||||||
}
|
};
|
||||||
|
|
||||||
console.log('Save Device Response:', response);
|
const response = !formData.device_id
|
||||||
|
? await updateDevice(formData.device_id, payload)
|
||||||
|
: await createDevice(payload);
|
||||||
|
|
||||||
// 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)) {
|
||||||
// Response.data is now a single object (already extracted from array)
|
const deviceName = response.data?.device_name || formData.device_name;
|
||||||
const deviceName = response.data?.device_name || FormData.device_name;
|
|
||||||
|
|
||||||
NotifOk({
|
NotifOk({
|
||||||
icon: 'success',
|
icon: 'success',
|
||||||
title: 'Berhasil',
|
title: 'Berhasil',
|
||||||
message: `Data Device "${deviceName}" berhasil ${
|
message: `Data Device "${deviceName}" berhasil ${
|
||||||
FormData.device_id ? 'diubah' : 'ditambahkan'
|
formData.device_id ? 'diubah' : 'ditambahkan'
|
||||||
}.`,
|
}.`,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -203,7 +95,7 @@ const DetailDevice = (props) => {
|
|||||||
const handleInputChange = (e) => {
|
const handleInputChange = (e) => {
|
||||||
const { name, value } = e.target;
|
const { name, value } = e.target;
|
||||||
setFormData({
|
setFormData({
|
||||||
...FormData,
|
...formData,
|
||||||
[name]: value,
|
[name]: value,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -211,78 +103,22 @@ const DetailDevice = (props) => {
|
|||||||
const handleStatusToggle = (event) => {
|
const handleStatusToggle = (event) => {
|
||||||
const isChecked = event;
|
const isChecked = event;
|
||||||
setFormData({
|
setFormData({
|
||||||
...FormData,
|
...formData,
|
||||||
is_active: isChecked ? true : false,
|
is_active: isChecked ? true : false,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const generateNextDeviceCode = async () => {
|
|
||||||
try {
|
|
||||||
const params = new URLSearchParams({ limit: 10000 });
|
|
||||||
const response = await getAllDevice(params);
|
|
||||||
|
|
||||||
if (response && response.data && response.data.data) {
|
|
||||||
const devices = response.data.data;
|
|
||||||
|
|
||||||
if (devices.length === 0) {
|
|
||||||
setNextDeviceCode('DVC001');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extract numeric part from device codes and find the maximum
|
|
||||||
const deviceNumbers = devices
|
|
||||||
.map((device) => {
|
|
||||||
const match = device.device_code?.match(/dvc(\d+)/i);
|
|
||||||
return match ? parseInt(match[1], 10) : 0;
|
|
||||||
})
|
|
||||||
.filter((num) => !isNaN(num));
|
|
||||||
|
|
||||||
const maxNumber = deviceNumbers.length > 0 ? Math.max(...deviceNumbers) : 0;
|
|
||||||
const nextNumber = maxNumber + 1;
|
|
||||||
|
|
||||||
// Format with leading zeros (DVC001, DVC002, etc.)
|
|
||||||
const nextCode = `DVC${String(nextNumber).padStart(3, '0')}`;
|
|
||||||
setNextDeviceCode(nextCode);
|
|
||||||
} else {
|
|
||||||
setNextDeviceCode('DVC001');
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error generating next device code:', error);
|
|
||||||
setNextDeviceCode('Auto-fill');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const token = localStorage.getItem('token');
|
if (props.selectedData) {
|
||||||
if (token) {
|
setFormData(props.selectedData);
|
||||||
if (props.showModal) {
|
|
||||||
// Only call getDataJenisPermit if permitDefault is enabled
|
|
||||||
if (props.permitDefault) {
|
|
||||||
getDataJenisPermit();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate next device code only for add mode
|
|
||||||
if (props.actionMode === 'add' && !props.selectedData) {
|
|
||||||
generateNextDeviceCode();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.selectedData != null) {
|
|
||||||
setFormData(props.selectedData);
|
|
||||||
if (props.permitDefault && props.selectedData.jenis_permit_default_arr) {
|
|
||||||
setCheckedList(props.selectedData.jenis_permit_default_arr);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
setFormData(defaultData);
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
// navigate('/signin'); // Uncomment if useNavigate is imported
|
setFormData(defaultData);
|
||||||
}
|
}
|
||||||
}, [props.showModal, props.actionMode]);
|
}, [props.showModal, props.selectedData, props.actionMode]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
// title={`${FormData.id_apd === '' ? 'Tambah' : 'Edit'} APD`}
|
// title={`${formData.id_apd === '' ? 'Tambah' : 'Edit'} APD`}
|
||||||
title={`${
|
title={`${
|
||||||
props.actionMode === 'add'
|
props.actionMode === 'add'
|
||||||
? 'Tambah'
|
? 'Tambah'
|
||||||
@@ -337,7 +173,7 @@ const DetailDevice = (props) => {
|
|||||||
</React.Fragment>,
|
</React.Fragment>,
|
||||||
]}
|
]}
|
||||||
>
|
>
|
||||||
{FormData && (
|
{formData && (
|
||||||
<div>
|
<div>
|
||||||
<div>
|
<div>
|
||||||
<div>
|
<div>
|
||||||
@@ -355,14 +191,14 @@ const DetailDevice = (props) => {
|
|||||||
disabled={props.readOnly}
|
disabled={props.readOnly}
|
||||||
style={{
|
style={{
|
||||||
backgroundColor:
|
backgroundColor:
|
||||||
FormData.is_active === true ? '#23A55A' : '#bfbfbf',
|
formData.is_active === true ? '#23A55A' : '#bfbfbf',
|
||||||
}}
|
}}
|
||||||
checked={FormData.is_active === true}
|
checked={formData.is_active === true}
|
||||||
onChange={handleStatusToggle}
|
onChange={handleStatusToggle}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<Text>{FormData.is_active === true ? 'Running' : 'Offline'}</Text>
|
<Text>{formData.is_active === true ? 'Running' : 'Offline'}</Text>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -371,7 +207,7 @@ const DetailDevice = (props) => {
|
|||||||
<Text strong>Device ID</Text>
|
<Text strong>Device ID</Text>
|
||||||
<Input
|
<Input
|
||||||
name="device_id"
|
name="device_id"
|
||||||
value={FormData.device_id}
|
value={formData.device_id}
|
||||||
onChange={handleInputChange}
|
onChange={handleInputChange}
|
||||||
disabled
|
disabled
|
||||||
/>
|
/>
|
||||||
@@ -381,13 +217,13 @@ const DetailDevice = (props) => {
|
|||||||
<Text strong>Device Code</Text>
|
<Text strong>Device Code</Text>
|
||||||
<Input
|
<Input
|
||||||
name="device_code"
|
name="device_code"
|
||||||
value={FormData.device_code || nextDeviceCode}
|
value={formData.device_code}
|
||||||
placeholder={nextDeviceCode}
|
placeholder={'Device Code Auto Fill'}
|
||||||
disabled
|
disabled
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: '#f5f5f5',
|
backgroundColor: '#f5f5f5',
|
||||||
cursor: 'not-allowed',
|
cursor: 'not-allowed',
|
||||||
color: FormData.device_code ? '#000000' : '#bfbfbf'
|
color: formData.device_code ? '#000000' : '#bfbfbf',
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -396,7 +232,7 @@ const DetailDevice = (props) => {
|
|||||||
<Text style={{ color: 'red' }}> *</Text>
|
<Text style={{ color: 'red' }}> *</Text>
|
||||||
<Input
|
<Input
|
||||||
name="device_name"
|
name="device_name"
|
||||||
value={FormData.device_name}
|
value={formData.device_name}
|
||||||
onChange={handleInputChange}
|
onChange={handleInputChange}
|
||||||
placeholder="Enter Device Name"
|
placeholder="Enter Device Name"
|
||||||
readOnly={props.readOnly}
|
readOnly={props.readOnly}
|
||||||
@@ -404,11 +240,10 @@ const DetailDevice = (props) => {
|
|||||||
</div>
|
</div>
|
||||||
<div style={{ marginBottom: 12 }}>
|
<div style={{ marginBottom: 12 }}>
|
||||||
<Text strong>Device Location</Text>
|
<Text strong>Device Location</Text>
|
||||||
<Text style={{ color: 'red' }}> *</Text>
|
|
||||||
<Input
|
<Input
|
||||||
type="text"
|
type="text"
|
||||||
name="device_location"
|
name="device_location"
|
||||||
value={FormData.device_location}
|
value={formData.device_location}
|
||||||
onChange={handleInputChange}
|
onChange={handleInputChange}
|
||||||
placeholder="Enter Device Location"
|
placeholder="Enter Device Location"
|
||||||
readOnly={props.readOnly}
|
readOnly={props.readOnly}
|
||||||
@@ -419,7 +254,7 @@ const DetailDevice = (props) => {
|
|||||||
<Text style={{ color: 'red' }}> *</Text>
|
<Text style={{ color: 'red' }}> *</Text>
|
||||||
<Input
|
<Input
|
||||||
name="ip_address"
|
name="ip_address"
|
||||||
value={FormData.ip_address}
|
value={formData.ip_address}
|
||||||
onChange={handleInputChange}
|
onChange={handleInputChange}
|
||||||
placeholder="e.g. 192.168.1.1"
|
placeholder="e.g. 192.168.1.1"
|
||||||
readOnly={props.readOnly}
|
readOnly={props.readOnly}
|
||||||
@@ -429,26 +264,13 @@ const DetailDevice = (props) => {
|
|||||||
<Text strong>Device Description</Text>
|
<Text strong>Device Description</Text>
|
||||||
<TextArea
|
<TextArea
|
||||||
name="device_description"
|
name="device_description"
|
||||||
value={FormData.device_description}
|
value={formData.device_description}
|
||||||
onChange={handleInputChange}
|
onChange={handleInputChange}
|
||||||
placeholder="Enter Device Description (Optional)"
|
placeholder="Enter Device Description (Optional)"
|
||||||
readOnly={props.readOnly}
|
readOnly={props.readOnly}
|
||||||
rows={4}
|
rows={4}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{props.permitDefault && (
|
|
||||||
<div>
|
|
||||||
<Text strong>Jenis Permit</Text>
|
|
||||||
<Text style={{ color: 'red' }}> *</Text>
|
|
||||||
|
|
||||||
<CheckboxGroup
|
|
||||||
options={jenisPermit}
|
|
||||||
value={checkedList}
|
|
||||||
onChange={onChange}
|
|
||||||
disabled={props.readOnly}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|||||||
@@ -1,15 +1,8 @@
|
|||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import {
|
import { Modal, Input, Typography, Switch, Button, ConfigProvider, Divider } from 'antd';
|
||||||
Modal,
|
|
||||||
Input,
|
|
||||||
Typography,
|
|
||||||
Switch,
|
|
||||||
Button,
|
|
||||||
ConfigProvider,
|
|
||||||
Divider,
|
|
||||||
} from 'antd';
|
|
||||||
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
|
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
|
||||||
import { createPlantSection, updatePlantSection, getAllPlantSection } from '../../../../api/master-plant-section';
|
import { createPlantSection, updatePlantSection } from '../../../../api/master-plant-section';
|
||||||
|
import { validateRun } from '../../../../Utils/validate';
|
||||||
|
|
||||||
const { Text } = Typography;
|
const { Text } = Typography;
|
||||||
|
|
||||||
@@ -23,13 +16,12 @@ const DetailPlantSection = (props) => {
|
|||||||
is_active: true,
|
is_active: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
const [FormData, setFormData] = useState(defaultData);
|
const [formData, setFormData] = useState(defaultData);
|
||||||
const [nextPlantSectionCode, setNextPlantSectionCode] = useState('Auto-fill');
|
|
||||||
|
|
||||||
const handleInputChange = (e) => {
|
const handleInputChange = (e) => {
|
||||||
const { name, value } = e.target;
|
const { name, value } = e.target;
|
||||||
setFormData({
|
setFormData({
|
||||||
...FormData,
|
...formData,
|
||||||
[name]: value,
|
[name]: value,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -42,52 +34,53 @@ const DetailPlantSection = (props) => {
|
|||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
setConfirmLoading(true);
|
setConfirmLoading(true);
|
||||||
|
|
||||||
if (!FormData.sub_section_name) {
|
// Daftar aturan validasi
|
||||||
NotifOk({
|
const validationRules = [
|
||||||
icon: 'warning',
|
{ field: 'sub_section_name', label: 'Plant Sub Section Name', required: true },
|
||||||
title: 'Peringatan',
|
];
|
||||||
message: 'Kolom Plant Sub Section Name Tidak Boleh Kosong',
|
|
||||||
});
|
if (
|
||||||
setConfirmLoading(false);
|
validateRun(formData, validationRules, (errorMessages) => {
|
||||||
|
NotifOk({
|
||||||
|
icon: 'warning',
|
||||||
|
title: 'Peringatan',
|
||||||
|
message: errorMessages,
|
||||||
|
});
|
||||||
|
setConfirmLoading(false);
|
||||||
|
})
|
||||||
|
)
|
||||||
return;
|
return;
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
let response;
|
const payload = {
|
||||||
let payload;
|
is_active: formData.is_active,
|
||||||
|
sub_section_name: formData.sub_section_name,
|
||||||
|
};
|
||||||
|
|
||||||
if (props.actionMode === 'edit') {
|
const response =
|
||||||
payload = {
|
props.actionMode === 'edit'
|
||||||
is_active: FormData.is_active,
|
? await updatePlantSection(formData.sub_section_id, payload)
|
||||||
sub_section_name: FormData.sub_section_name
|
: await createPlantSection(payload);
|
||||||
};
|
|
||||||
response = await updatePlantSection(FormData.sub_section_id, payload);
|
|
||||||
} else {
|
|
||||||
// Backend generates the code, so we only send the name and status
|
|
||||||
payload = {
|
|
||||||
sub_section_name: FormData.sub_section_name,
|
|
||||||
is_active: FormData.is_active,
|
|
||||||
}
|
|
||||||
response = await createPlantSection(payload);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (response && (response.statusCode === 200 || response.statusCode === 201)) {
|
if (response && (response.statusCode === 200 || response.statusCode === 201)) {
|
||||||
const action = props.actionMode === 'edit' ? 'diubah' : 'ditambahkan';
|
const action = props.actionMode === 'edit' ? 'diubah' : 'ditambahkan';
|
||||||
|
|
||||||
NotifOk({
|
NotifOk({
|
||||||
icon: 'success',
|
icon: 'success',
|
||||||
title: 'Berhasil',
|
title: 'Berhasil',
|
||||||
message: `Data Plant Section berhasil ${action}.`,
|
message: `Data Plant Section berhasil ${action}.`,
|
||||||
});
|
});
|
||||||
|
|
||||||
props.setActionMode('list');
|
props.setActionMode('list');
|
||||||
} else {
|
} else {
|
||||||
NotifAlert({
|
NotifOk({
|
||||||
icon: 'error',
|
icon: 'error',
|
||||||
title: 'Gagal',
|
title: 'Gagal',
|
||||||
message: response?.message || 'Terjadi kesalahan saat menyimpan data.',
|
message: response?.message || 'Terjadi kesalahan saat menyimpan data.',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
NotifAlert({
|
NotifOk({
|
||||||
icon: 'error',
|
icon: 'error',
|
||||||
title: 'Error',
|
title: 'Error',
|
||||||
message: error.message || 'Terjadi kesalahan pada server.',
|
message: error.message || 'Terjadi kesalahan pada server.',
|
||||||
@@ -96,58 +89,15 @@ const DetailPlantSection = (props) => {
|
|||||||
setConfirmLoading(false);
|
setConfirmLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleStatusToggle = (checked) => {
|
const handleStatusToggle = (checked) => {
|
||||||
setFormData({
|
setFormData({
|
||||||
...FormData,
|
...formData,
|
||||||
is_active: checked,
|
is_active: checked,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const generateNextPlantSectionCode = async () => {
|
|
||||||
try {
|
|
||||||
const params = new URLSearchParams({ limit: 10000 });
|
|
||||||
const response = await getAllPlantSection(params);
|
|
||||||
|
|
||||||
if (response && response.data && response.data.data) {
|
|
||||||
const sections = response.data.data;
|
|
||||||
|
|
||||||
if (sections.length === 0) {
|
|
||||||
setNextPlantSectionCode('SUB001');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extract numeric part from plant section codes and find the maximum
|
|
||||||
const sectionNumbers = sections
|
|
||||||
.map((section) => {
|
|
||||||
const match = section.sub_section_code?.match(/sub(\d+)/i);
|
|
||||||
return match ? parseInt(match[1], 10) : 0;
|
|
||||||
})
|
|
||||||
.filter((num) => !isNaN(num));
|
|
||||||
|
|
||||||
const maxNumber = sectionNumbers.length > 0 ? Math.max(...sectionNumbers) : 0;
|
|
||||||
const nextNumber = maxNumber + 1;
|
|
||||||
|
|
||||||
// Format with leading zeros (SUB001, SUB002, etc.)
|
|
||||||
const nextCode = `SUB${String(nextNumber).padStart(3, '0')}`;
|
|
||||||
setNextPlantSectionCode(nextCode);
|
|
||||||
} else {
|
|
||||||
setNextPlantSectionCode('SUB001');
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error generating next plant section code:', error);
|
|
||||||
setNextPlantSectionCode('Auto-fill');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (props.showModal) {
|
|
||||||
// Generate next plant section code only for add mode
|
|
||||||
if (props.actionMode === 'add' && !props.selectedData) {
|
|
||||||
generateNextPlantSectionCode();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (props.selectedData) {
|
if (props.selectedData) {
|
||||||
setFormData(props.selectedData);
|
setFormData(props.selectedData);
|
||||||
} else {
|
} else {
|
||||||
@@ -157,7 +107,7 @@ const DetailPlantSection = (props) => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={`${
|
title={`${
|
||||||
props.actionMode === 'add'
|
props.actionMode === 'add'
|
||||||
? 'Tambah'
|
? 'Tambah'
|
||||||
: props.actionMode === 'preview'
|
: props.actionMode === 'preview'
|
||||||
@@ -201,7 +151,7 @@ const DetailPlantSection = (props) => {
|
|||||||
</React.Fragment>,
|
</React.Fragment>,
|
||||||
]}
|
]}
|
||||||
>
|
>
|
||||||
{FormData && (
|
{formData && (
|
||||||
<div>
|
<div>
|
||||||
<div>
|
<div>
|
||||||
<div>
|
<div>
|
||||||
@@ -212,16 +162,14 @@ const DetailPlantSection = (props) => {
|
|||||||
<Switch
|
<Switch
|
||||||
disabled={props.readOnly}
|
disabled={props.readOnly}
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: FormData.is_active ? '#23A55A' : '#bfbfbf',
|
backgroundColor: formData.is_active ? '#23A55A' : '#bfbfbf',
|
||||||
}}
|
}}
|
||||||
checked={FormData.is_active}
|
checked={formData.is_active}
|
||||||
onChange={handleStatusToggle}
|
onChange={handleStatusToggle}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<Text>
|
<Text>{formData.is_active ? 'Active' : 'Inactive'}</Text>
|
||||||
{FormData.is_active ? 'Active' : 'Inactive'}
|
|
||||||
</Text>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -232,13 +180,13 @@ const DetailPlantSection = (props) => {
|
|||||||
<Text strong>Plant Section Code</Text>
|
<Text strong>Plant Section Code</Text>
|
||||||
<Input
|
<Input
|
||||||
name="sub_section_code"
|
name="sub_section_code"
|
||||||
value={FormData.sub_section_code || nextPlantSectionCode}
|
value={formData.sub_section_code || ''}
|
||||||
placeholder={nextPlantSectionCode}
|
placeholder={'Plant Sub Section Code Auto Fill'}
|
||||||
disabled
|
disabled
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: '#f5f5f5',
|
backgroundColor: '#f5f5f5',
|
||||||
cursor: 'not-allowed',
|
cursor: 'not-allowed',
|
||||||
color: FormData.sub_section_code ? '#000000' : '#bfbfbf'
|
color: formData.sub_section_code ? '#000000' : '#bfbfbf',
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -248,7 +196,7 @@ const DetailPlantSection = (props) => {
|
|||||||
<Text style={{ color: 'red' }}> *</Text>
|
<Text style={{ color: 'red' }}> *</Text>
|
||||||
<Input
|
<Input
|
||||||
name="sub_section_name"
|
name="sub_section_name"
|
||||||
value={FormData.sub_section_name}
|
value={formData.sub_section_name}
|
||||||
onChange={handleInputChange}
|
onChange={handleInputChange}
|
||||||
placeholder="Enter Plant Sub Section Name"
|
placeholder="Enter Plant Sub Section Name"
|
||||||
readOnly={props.readOnly}
|
readOnly={props.readOnly}
|
||||||
@@ -260,4 +208,4 @@ const DetailPlantSection = (props) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default DetailPlantSection;
|
export default DetailPlantSection;
|
||||||
|
|||||||
Reference in New Issue
Block a user