/**
* 페이징 처리
* @param {int} page
* @param {int} size
* @param {string} sort
*/
function goPageable(page, size, sort) {
if (typeof formControl === 'object' && typeof formControl.init === 'function') {
setTimeout(() => {
formControl.goPageable(page, size, sort);
}, 200)
} else {
let uri = new Uri(location.href);
uri.replaceQueryParam('page', page).replaceQueryParam('size', size)
.replaceQueryParam('sort', convertToPageableSortValue(sort));
location.href = uri.toString();
}
}
/**
* UI 단의 sort 를 JPA pageable 이 인식할 수 있는 정렬값으로 변경
* createdId: DESC => createdId,DESC
* @param sort
* @returns {string}
*/
function convertToPageableSortValue(sort) {
sort = sort.replace(',', ':');
const parsedSort = sort.split(':');
return parsedSort[0].trim() + ',' + parsedSort[1].trim();
}
let uiUtil = {
// ISO String 포맷을 YYYY-MM-DD HH:mm:ss 로 변환
isoStrToReadable(isoStr) {
return isoStr.replace(/T/, ' ').substring(0, 19);
},
isoStrToDateOnly(isoStr) {
return isoStr.split('T')[0];
},
// Pagination UI 생성 함수
getPagingUI(curPageNo, size, totalPages, moveHandler) {
curPageNo = parseInt(curPageNo);
const firstPage = 0;
const isFirstPage = curPageNo === 0;
let frag1 =
`
`;
let el = $(frag1 + frag2 + frag3);
el.find('.page-link').on('click', (evt) => {
const $link = $(evt.currentTarget);
if ($link.hasClass('disabled')) {
evt.preventDefault();
return false;
}
let targetPage = $link.data('target-page');
if (targetPage.toString() === 'null') {
return false;
}
moveHandler(targetPage);
});
return el;
},
// 리스트 상단 정렬 notation 및 갱신 기능 적용
addSortNotation(sort, sortHandler) {
let curSortField = sort.split(',')[0],
curSortDir = sort.split(',')[1];
$('.sortNotation').remove();
$('.order-able').each(function (i, el) {
$(el).removeClass('text-dark');
let sortField = $(el).data('sort-field');
// 현재 sort 조건과 동일한 칼럼일 경우
if (sortField === curSortField) {
$(el).parent().append(curSortDir === 'DESC' ?
$('')
:
$(''));
$(el).click(function () {
sortHandler(0,
curSortField + ',' + (curSortDir === 'DESC' ? 'ASC' : 'DESC'));
return false;
});
$(el).addClass('text-dark');
} else {
$(el).click(function () {
sortHandler(0, $(el).data('sort-field') + ',' + 'DESC');
return false;
});
}
});
},
// 파일 참조 URL 생성
getFileReferURL(referType, uploadFile) {
const storageType = uploadFile.type.fileStorageType;
switch (referType) {
case 'inline':
if (storageType === 'S3') {
return `${S3URL}${uploadFile.path}/${uploadFile.name}`;
} else if (storageType === 'LOCAL') {
return `/content-disposition/inline${uploadFile.path}/${uploadFile.name}`;
}
case 'attachment':
return `/content-disposition/attachment/${uploadFile.id}`;
}
},
/**
* 목록 정렬 표기 및 갱신 기능 적용 - .order-able css class 기반으로 동작한다.
* @param pageSize
* @param sort
*/
applyListSortNotation(pageSize, sort) {
let curSortField = sort.split(':')[0],
curSortDir = sort.split(':')[1].trim();
$('.order-able').each(function (i, el) {
let sortField = $(el).data('sort-field');
// 현재 sort 조건과 동일한 칼럼일 경우
if (sortField === curSortField) {
$(el).parent().append(curSortDir === 'DESC' ?
$('') :
$(''));
$(el).click(function () {
goPageable(0, pageSize,
curSortField + ': ' + (curSortDir === 'DESC' ? 'ASC' : 'DESC'));
return false;
});
$(el).css('color', 'black');
} else {
$(el).click(function () {
goPageable(0, pageSize, $(el).data('sort-field') + ': ' + 'DESC');
return false;
});
}
});
},
};
uiUtil.goPageable = goPageable;
uiUtil.convertToPageableSortValue = convertToPageableSortValue;
/**
* 공용 ajax 파일 업로드 함수
* @param fileUploadType FileUploadType name
* @param input file input 객체
*/
uiUtil.uploadFile = (fileUploadType, input) => {
if (!fileUploadType) {
alert('fileUploadType 을 명시해야 uiUtil.uploadFile 메서드를 실행할 수 있습니다.');
return;
}
const inputGroup = $(input).parent().parent().find('.input-group');
if (!inputGroup.length) {
alert(
`${input.name} 앨리먼트의 부모가 input-group 클래스를 가져야 uiUtil.uploadFile 메서드를 실행할 수 있습니다.`);
return;
}
let formData = new FormData();
formData.append('file', input.files[0]);
// fileUploadType 을 formData 에 append 한다.
formData.append('reqVO', new Blob([JSON.stringify({
fileUploadType
})], {type: "application/json"}));
$.ajax({
method: 'POST',
url: '/api/file/create',
data: formData,
contentType: false, // * 중요 *
processData: false, // * 중요 *
enctype: 'multipart/form-data', // * 중요 *
beforeSend: function (xhr) {
xhr.setRequestHeader(
$("meta[name='_csrf_header']").attr("content"),
$("meta[name='_csrf']").attr("content"));
},
success(res) {
console.log(res);
// 에러 메세지가 있었다면 초기화
$(input).removeClass('is-invalid');
inputGroup.find('.invalid-feedback').text('');
// 기존 mappingId 가 있다면 초기화
/* inputGroup.find('input[name=fileMappingId]').remove();*/
/* // 신규 mappingId 추가
inputGroup.append(
``);*/
// 업로드 파일 정보 보이기
uiUtil.showFileInfo(input, res, $(input).attr('accept') === 'image/*');
},
statusCode: {
// 실패 - validation fail
422: (res) => {
const resJson = res.responseJSON;
$(input).parent().find('.invalid-feedback').text(resJson.message);
$(input).addClass('is-invalid');
}
}
});
}
/**
* 업로드 파일정보 보여주기
*
* @param {element} input file input 앨리먼트
* @param {object} uploadFile 업로드 파일 정보
* @param {boolean} showImg 미리보기 이미지 노출 여부
*/
uiUtil.showFileInfo = (input, uploadFile, showImg) => {
const inputGroup = $(input).parent().parent().find('.input-group');
if (!inputGroup.length) {
alert(
`${input.name} 앨리먼트의 부모가 input-group 클래스를 가져야 showFileInfo 메서드를 실행할 수 있습니다.`);
return;
}
/* inputGroup.find('.fileInfo').remove();*/
/* inputGroup.append(`
- 파일명 - ${uploadFile.name}
- 원본 파일명 (${uploadFile.originName})
- ${Math.ceil(uploadFile.fileLength / 1024)}KB
- File ID (${uploadFile.id})삭제
`);*/
inputGroup.append(`
${uploadFile.originName}(${Math.ceil(uploadFile.fileLength / 1024)}KB)
`);
const fileInfo = inputGroup.find('.fileInfo');
/* if (!showImg) {
fileInfo.find('img').remove();
}*/
// 파일 삭제 함수 정의
inputGroup.find('.resetFile').on('click', function () {
const $fileInfo = $(this).closest('.fileInfo');
$fileInfo.fadeOut(function () {
$(this).remove();
});
return false;
});
fileInfo.fadeIn();
}
/**
* Public image source 가져오기
* @param imagePath
* @param imageFilename
* @param isCrop
*/
uiUtil.getPublicImageSrc = function (imagePath, imageFilename, isCrop) {
if (!imagePath) {
return "";
}
if (imagePath.indexOf("/static") === 0) {
return isCrop ? imagePath + '/crop/' + imageFilename : imagePath + '/'
+ imageFilename;
} else {
return isCrop ? '/public' + imagePath + '/crop/' + imageFilename : '/public'
+ imagePath + '/' + imageFilename;
}
}
uiUtil.lineSeparatorToBr = function (contents) {
return contents.replaceAll('\r\n', '
');
}
/**
* HTML escape 처리된 문자열을 unescape 처리 후 반환
*
* @param {string} escapedText (HTML escape 처리된 텍스트)
* @returns {string} unescape 처리된 테스트
*/
uiUtil.unescapeHtml = function (escapedText) {
return unescapeText(escapedText);
}
/**
* 정렬 변경 UI 구성 함수
*/
uiUtil.sortable = function () {
let orderNoRange = [];
let idRange = [];
let updateData = [];
let updateFunc;
function _init(parentSelector, handleSelector, conditionCheckFunc,
initSortFunc, _updateFunc) {
$(parentSelector).sortable({
axis: 'y',
handle: handleSelector,
opacity: 0.5,
start: function (e, ui) {
if (!conditionCheckFunc()) {
if (confirm(
'Sorting 을 하려면 우선 정렬번호 순으로 정렬되어야 합니다. 정렬 조건을 변경하시겠습니까?')) {
initSortFunc();
}
}
ui.placeholder.height(ui.item.height());
ui.placeholder.css({'background': '#eee', 'visibility': 'visible'});
},
update: function (event, ui) {
_order(parentSelector);
}
});
updateFunc = _updateFunc;
}
function _order(parentSelector) {
orderNoRange = [];
idRange = [];
updateData = [];
let children = $(parentSelector).children();
children.each(function (idx, elem) {
orderNoRange.push($(elem).data('order-no'));
idRange.push($(elem).data('id'));
});
$(idRange).each(function (idx, id) {
updateData.push({'id': id, 'orderNo': Math.max(...orderNoRange) - idx});
});
}
function _update() {
if (!updateData || updateData.length === 0) {
alert('저장할 변경내역이 없습니다.');
return;
}
updateFunc(updateData);
}
return {
init: _init,
update: _update
}
}();
const unescapeText = (str) => {
str = str || '';
str = str.replace(/</g, "<");
str = str.replace(/>/g, ">");
str = str.replace(/ /g, " ");
str = str.replace(/"/g, "\"");
str = str.replace(/'/g, "\'");
str = str.replace(/'/g, "\'");
str = str.replace(/’/g, "’");
str = str.replace(/&/g, "&");
return str;
}
const showAudit = (auditItem, createdBy, createdAt, updatedBy, updatedAt) => {
const audit = $('.audit-area');
audit.find('.audit-target').text(unescapeText(auditItem));
audit.find('.createdBy').text(unescapeText(createdBy));
audit.find('.createdAt').text(createdAt);
audit.find('.updatedBy').text(unescapeText(updatedBy));
audit.find('.updatedAt').text(updatedAt);
audit.removeAttr('style');
audit.fadeOut(0);
audit.fadeIn(800);
}
/**
* XSS 방지를 위해 escape 처리되어 DB에 담긴 데이터를 화면에 출력할 때 unescape 처리해서 보여준다.
* - 'unescapeText' css class 를 가진 input 앨리먼트에 적용된다.
*/
(function () {
document.querySelectorAll(".unescapeText").forEach(function (el) {
el.hasAttribute('value') ? el.value = unescapeText(el.value) : '';
//el.textContent ? el.textContent = unescapeText(el.textContent) : '';
})
})();
const ifNullHyphen = (value, fallback = '-') => {
return value !== null && value !== undefined && value !== '' ? value : fallback;
}
const formatNumberWithComma = (value) => {
if (value == null || isNaN(value)) return '-';
return Number(value).toLocaleString();
}