Commit 4cff47ae authored by ardiansyah's avatar ardiansyah

Merge branch 'ENV-DEV' into 'ENV-DEPLOYMENT'

Env dev

See merge request !2386
parents b2c9629a 25e3c70f
...@@ -87,6 +87,16 @@ const create = (type = "") => { ...@@ -87,6 +87,16 @@ const create = (type = "") => {
// console.tron.log(url) // console.tron.log(url)
}) })
api.addResponseTransform(response => {
const msg = response.data?.message || ""
if (msg.includes("Someone Logged In") || msg.includes("Token Expired")) {
localStorage.removeItem(Constant.TOKEN)
window.location.reload()
return
}
})
// ------ // ------
// STEP 2 // STEP 2
// ------ // ------
...@@ -155,6 +165,7 @@ const create = (type = "") => { ...@@ -155,6 +165,7 @@ const create = (type = "") => {
const getApprovedByAM = () => api.get('approval_matrix/get_all_approver') const getApprovedByAM = () => api.get('approval_matrix/get_all_approver')
const getTypeAM = () => api.get('approval_type/get_all_approval_type') const getTypeAM = () => api.get('approval_type/get_all_approval_type')
const getOperatorAM = () => api.get('operator_type/get_all_operator_type') const getOperatorAM = () => api.get('operator_type/get_all_operator_type')
const getMasterReportType = () => api.get('masterreporttype/get_all_master_report_type')
const getDetailAM = (id) => api.get(`approval_matrix/get_approval_matrix_by_id/${id}`) const getDetailAM = (id) => api.get(`approval_matrix/get_approval_matrix_by_id/${id}`)
const searchAM = (body) => api.post('/approval_matrix/search_approval_matrix', body) const searchAM = (body) => api.post('/approval_matrix/search_approval_matrix', body)
const createAM = (body) => api.post('/approval_matrix/create_approval_matrix', body) const createAM = (body) => api.post('/approval_matrix/create_approval_matrix', body)
...@@ -623,6 +634,7 @@ const create = (type = "") => { ...@@ -623,6 +634,7 @@ const create = (type = "") => {
getApprovedByAM, getApprovedByAM,
getTypeAM, getTypeAM,
getOperatorAM, getOperatorAM,
getMasterReportType,
getDetailAM, getDetailAM,
searchAM, searchAM,
createAM, createAM,
......
...@@ -93,7 +93,7 @@ class ReportHistorical extends Component { ...@@ -93,7 +93,7 @@ class ReportHistorical extends Component {
})) }))
} }
showAlert = (message, severity = 'success') => { showAlert = (message, severity = Constant.ALERT_SEVIRITY.SUCCESS) => {
this.setState({ this.setState({
showAlert: true, showAlert: true,
alertMessage: message, alertMessage: message,
...@@ -107,8 +107,12 @@ class ReportHistorical extends Component { ...@@ -107,8 +107,12 @@ class ReportHistorical extends Component {
handleDownload = async () => { handleDownload = async () => {
try { try {
this.setLoading(true)
const { data } = this.state const { data } = this.state
if (!data?.company_id) {
this.showAlert('Data is not complete !', Constant.ALERT_SEVIRITY.WARNING);
return
}
this.setLoading(true)
const payload = { const payload = {
report_id: data.report_id?.id, report_id: data.report_id?.id,
company_id: data.company_id?.map(c => c.id).join(','), company_id: data.company_id?.map(c => c.id).join(','),
...@@ -125,12 +129,12 @@ class ReportHistorical extends Component { ...@@ -125,12 +129,12 @@ class ReportHistorical extends Component {
downloadFileBlob(fileName, blob) downloadFileBlob(fileName, blob)
} }
this.showAlert('Download Berhasil', 'success'); this.showAlert('Download Berhasil');
}) })
} catch (error) { } catch (error) {
// Show error alert // Show error alert
this.showAlert(`Gagal menyimpan: ${error.message}`, 'error'); this.showAlert(`Gagal menyimpan: ${error.message}`, Constant.ALERT_SEVIRITY.ERROR);
} }
}; };
......
...@@ -27,21 +27,29 @@ const AutocompleteField = ({ ...@@ -27,21 +27,29 @@ const AutocompleteField = ({
multiple = false, multiple = false,
showCheckbox = false, showCheckbox = false,
isLoading = false, isLoading = false,
minSizeBox = false,
...props ...props
}) => { }) => {
const defaultRenderInput = (params) => ( const defaultRenderInput = (params) => (
<TextField <TextField
{...params} {...params}
label={label} label={label}
margin={margin} margin={minSizeBox ? 'none' : margin}
style={{ marginTop: 7 }} style={minSizeBox ? {} : { marginTop: 7 }}
disabled={disabled} disabled={disabled}
required={required} required={required}
error={error} error={error}
helperText={helperText} helperText={helperText}
fullWidth fullWidth
InputLabelProps={minSizeBox ? {
style: {
fontSize: 11,
color: '#7e8085'
}
} : {}}
InputProps={{ InputProps={{
...params.InputProps, ...params.InputProps,
style: minSizeBox ? { fontSize: 11 } : {},
endAdornment: ( endAdornment: (
<> <>
{isLoading ? ( {isLoading ? (
...@@ -90,7 +98,7 @@ const AutocompleteField = ({ ...@@ -90,7 +98,7 @@ const AutocompleteField = ({
onChange={onChange} onChange={onChange}
value={multiple ? (value || []) : (value || null)} value={multiple ? (value || []) : (value || null)}
id={id} id={id}
disableClearable={!multiple && disableClearable} disableClearable={disableClearable}
disableCloseOnSelect={multiple} disableCloseOnSelect={multiple}
style={style} style={style}
disabled={disabled} disabled={disabled}
......
...@@ -29,9 +29,7 @@ class ContentContainer extends Component { ...@@ -29,9 +29,7 @@ class ContentContainer extends Component {
{isLoading && ( {isLoading && (
<OverlayLoader isLoading={isLoading} {...loaderProps} /> <OverlayLoader isLoading={isLoading} {...loaderProps} />
)} )}
<Header {title && <Header title={title} />}
title={title}
/>
{children} {children}
</div> </div>
); );
......
...@@ -4,96 +4,88 @@ import AutocompleteField from '../AutocompleteField'; ...@@ -4,96 +4,88 @@ import AutocompleteField from '../AutocompleteField';
import api from '../../api'; import api from '../../api';
class DDLCompany extends Component { class DDLCompany extends Component {
constructor(props) { state = {
super(props); companies: [],
this.state = { selectedValue: this.props.multiple ? [] : null,
selectedValue: props.multiple isLoading: false,
? (props.value || []) };
: (props.value || null),
companies: [],
isLoading: false,
};
}
componentDidMount() { componentDidMount() {
this.getCompanyActive(); this.getCompanyActive();
} }
componentDidUpdate(prevProps, prevState) { componentDidUpdate(prevProps, prevState) {
// Value dikontrol parent // 🔁 value dari parent berubah ATAU companies selesai load
if (prevProps.value !== this.props.value) { if (
this.syncValueWithCompanies(this.props.value); prevProps.value !== this.props.value ||
} prevState.companies !== this.state.companies
) {
// Companies berubah (hasil API)
if (prevState.companies !== this.state.companies) {
this.syncValueWithCompanies(this.props.value); this.syncValueWithCompanies(this.props.value);
} }
} }
setLoading = (isLoading) => { setLoading = (isLoading) => {
this.setState({ isLoading }); this.setState({ isLoading });
} };
getCompanyActive = async () => { getCompanyActive = async () => {
try { try {
this.setLoading(true); this.setLoading(true);
const response = await api.create().getPerusahaanActive(); const res = await api.create().getPerusahaanActive();
const data = response?.data?.data || []; const data = res?.data?.data || [];
const companies = data.map(item => ({ const companies = data.map(item => ({
id: String(item.company_id), id: String(item.company_id),
name: item.company_name, name: item.company_name,
})); }));
this.setState({ companies }); this.setState({ companies }, () => {
} catch (err) { // ⭐ optional auto select index 0
console.error('Failed to load companies', err); if (
this.props.autoSelectFirst &&
!this.props.value &&
companies.length > 0
) {
this.handleChange(null, this.props.multiple ? [companies[0]] : companies[0]);
}
});
} catch (e) {
console.error(e);
this.setState({ companies: [] }); this.setState({ companies: [] });
} finally { } finally {
this.setLoading(false); this.setLoading(false);
} }
}; };
// Sinkron value → referensi object dari companies // 🔑 SINKRON VALUE ↔ OPTIONS (INI KUNCI UTAMA)
syncValueWithCompanies = (value) => { syncValueWithCompanies = (value) => {
const { companies } = this.state; const { companies } = this.state;
const { multiple } = this.props; const { multiple } = this.props;
if (!value || companies.length === 0) { if (!value || companies.length === 0) return;
this.setState({
selectedValue: multiple ? [] : null,
});
return;
}
if (multiple) { if (multiple) {
const synced = value const synced = value
.map(v => .map(v => companies.find(c => c.id === String(v.id)))
companies.find(c => String(c.id) === String(v.id))
)
.filter(Boolean); .filter(Boolean);
this.setState({ selectedValue: synced }); this.setState({ selectedValue: synced });
} else { } else {
const matched = companies.find( const matched = companies.find(c => c.id === String(value.id));
c => String(c.id) === String(value.id)
);
this.setState({ selectedValue: matched || null }); this.setState({ selectedValue: matched || null });
} }
}; };
// 🔁 SELALU KIRIM BALIK KE PARENT
handleChange = (event, newValue) => { handleChange = (event, newValue) => {
const { onChange, onCompanyChange, name, multiple } = this.props; const { onChange, onCompanyChange, name, multiple } = this.props;
this.setState({ selectedValue: newValue }); this.setState({ selectedValue: newValue });
// Standard handler
if (onChange) { if (onChange) {
onChange(event, newValue, name); onChange(event, newValue, name);
} }
// Backward compatibility
if (onCompanyChange) { if (onCompanyChange) {
if (multiple) { if (multiple) {
onCompanyChange(newValue.map(v => v.id)); onCompanyChange(newValue.map(v => v.id));
...@@ -103,29 +95,20 @@ class DDLCompany extends Component { ...@@ -103,29 +95,20 @@ class DDLCompany extends Component {
} }
}; };
getSelectedCompanyValue = () => {
const { selectedValue } = this.state;
const { multiple } = this.props;
return multiple
? selectedValue.map(v => v.id)
: selectedValue?.id || null;
};
render() { render() {
const { const {
label = 'Company', label,
placeholder = 'Select Company', placeholder,
disabled = false, disabled,
required = false, required,
error = false, error,
helperText, helperText,
style = { width: 250 }, style,
margin = 'normal', margin,
multiple, multiple,
} = this.props; } = this.props;
const { selectedValue, companies, isLoading } = this.state; const { companies, selectedValue, isLoading } = this.state;
return ( return (
<AutocompleteField <AutocompleteField
...@@ -142,17 +125,14 @@ class DDLCompany extends Component { ...@@ -142,17 +125,14 @@ class DDLCompany extends Component {
margin={margin} margin={margin}
multiple={multiple} multiple={multiple}
showCheckbox={multiple} showCheckbox={multiple}
isLoading={isLoading} loading={isLoading}
/> />
); );
} }
} }
DDLCompany.propTypes = { DDLCompany.propTypes = {
value: PropTypes.oneOfType([ value: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
PropTypes.object,
PropTypes.array,
]),
onChange: PropTypes.func, onChange: PropTypes.func,
onCompanyChange: PropTypes.func, onCompanyChange: PropTypes.func,
name: PropTypes.string, name: PropTypes.string,
...@@ -168,13 +148,16 @@ DDLCompany.propTypes = { ...@@ -168,13 +148,16 @@ DDLCompany.propTypes = {
helperText: PropTypes.string, helperText: PropTypes.string,
multiple: PropTypes.bool, multiple: PropTypes.bool,
autoSelectFirst: PropTypes.bool,
}; };
DDLCompany.defaultProps = { DDLCompany.defaultProps = {
label: 'Company', label: 'Company',
placeholder: 'Select Company', placeholder: 'Select Company',
style: { width: 250 }, style: { width: 250 },
margin: 'normal',
multiple: false, multiple: false,
autoSelectFirst: false,
}; };
export default DDLCompany; export default DDLCompany;
...@@ -26,4 +26,58 @@ export function downloadFileBlob(fileName, blobData) { ...@@ -26,4 +26,58 @@ export function downloadFileBlob(fileName, blobData) {
a.click() a.click()
a.remove() a.remove()
window.URL.revokeObjectURL(url) window.URL.revokeObjectURL(url)
} }
\ No newline at end of file
/**
* @param {Object} location - Objek location dari props (this.props.location)
* @param {string} paramName - Nama key yang ingin diambil (misal: 'month')
* @param {any} defaultValue - Nilai kembalian jika data null/undefined
*/
export const getStateParam = (location, paramName = null, defaultValue = null) => {
if (!paramName) {
return location?.state ?? defaultValue;
}
return location?.state?.[paramName] ?? defaultValue;
};
export const formatters = {
// Untuk format Infinity
infinity: {
month: (val) => String(val === undefined || val === 'Infinity' || val === '-Infinity'
? "0.0"
: Number(val).toFixed(2)),
totalCY: (val) => String(val === undefined || val === 'Infinity' || val === '-Infinity'
? "0.0"
: Number(val).toFixed(2)),
totalOther: (val) => String(val !== '' && val !== 'Infinity' && val !== '-Infinity'
? Number(val).toFixed(2)
: val)
},
// Untuk format .value property
value: {
month: (val) => String(val?.value === undefined ? val : Number(val.value).toFixed(1)),
total: (val) => String(val !== '' ? Number(val).toFixed(1) : val)
}
};
// ===== HELPER FUNCTIONS =====
export const createMonthData = (item, startIdx, formatFn) => {
const monthNames = ['january', 'february', 'march', 'april', 'may', 'june',
'july', 'august', 'september', 'october', 'november', 'december'];
const months = {};
monthNames.forEach((month, idx) => {
months[month] = formatFn(item[startIdx + idx]);
});
return months;
};
export const convertSelect = (id, name) => {
const obj = id ? {
id,
name,
} : null
return obj
};
\ No newline at end of file
import api from "../api";
import Constant from "../library/Constant";
const handleResponse = (response) => {
// 1. Handling Sukses
if (response.ok && response.data?.status === "success") {
return response.data.data;
}
// 2. Ambil pesan asli
const serverMessage = response.data?.message || response.data?.error || response.problem || "Gagal";
// 3. Masking bahasa teknis backend
let finalMessage = serverMessage;
if (typeof serverMessage === 'string' && (
serverMessage.includes("java.lang") ||
serverMessage.includes("FormatException") ||
serverMessage.includes("sql")
)) {
finalMessage = "Terjadi kesalahan format data pada sistem.";
}
const error = new Error(finalMessage);
error.tipe = (response.status >= 400 && response.status < 500) ? 'warning' : 'error';
error.isApiError = true;
error.originalMessage = serverMessage;
throw error;
};
/**
* Wrapper agar komponen bisa memilih mau pakai data saja atau errornya juga.
* Menghilangkan kebutuhan try-catch di komponen.
*/
const wrapService = (promise) => {
return promise
.then(res => {
return { data: handleResponse(res), error: null };
})
.catch((err) => {
console.error("API_LOG:", err.originalMessage || err.message);
return {
data: null,
error: { message: err.message, tipe: err.tipe }
};
});
};
// --- EXPORTED SERVICES ---
export const fetchMenuPermission = (menuName) => wrapService(api.create().getPermission({ menu: menuName }));
export const fetchDetailRole = (roleId) => wrapService(api.create().getDetailRole(roleId));
export const fetchDetailUser = () => {
const userId = localStorage.getItem(Constant.USER);
return wrapService(api.create().getDetailUser(userId));
};
export const fetchApprover = () => wrapService(api.create().checkApprover());
export const fetchLastPeriod = (companyId) => wrapService(api.create().getLastPeriod(companyId));
export const fetchRevision = (payload) => wrapService(api.create().getRevision(payload));
export const fetchSubmission = (payload) => wrapService(api.create().getSubmission(payload));
export const fetchListApprover = (report, monthlyReportId) => {
return wrapService(api.create().getListApprover(report, monthlyReportId));
}
export const fetchDetailReportCF = (payload) => wrapService(api.create().getDetailReportCF(payload));
export const fetchPLID = (payload) => wrapService(api.create().getPLID(payload));
export const fetchHierarkiCreateReportPLMB = (payload) => wrapService(api.create().getHierarkiCreateReportPLMB(payload));
export const fetchFRID = (payload) => wrapService(api.create().getFRID(payload));
export const fetchDownloadFile = (payload) => wrapService(api.create().createDownloadFile(payload));
export const fetchZipReport = (downloadedFileReportId) => wrapService(api.create().createZipReport(downloadedFileReportId));
export const fetchMasterReportType = () => wrapService(api.create().getMasterReportType());
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment