import { vars } from './variable.js';
//설정창 close 25-08-18 권한 설정 모달 사용 중에 모달이 꺼지는일이 많아 주석처리로 꺼지는 기능을 막음
// document.querySelector('.permission-modal').addEventListener('click', (e) => {
// if (e.target.className.includes('permission-modal')) document.querySelector('.permission-modal').style.display = 'none';
// })
document.querySelector('.permission-modal img[alt="닫기"]').addEventListener('click', () => {
// 이름 검색 결과창 초기화
searchResultInit();
document.querySelector('.permission-modal').style.display = 'none';
})
//설정창 저장
document.getElementById('permission-submit').addEventListener('click', () => {
if(vars.permissionList.changed && Object.keys(vars.permissionList.changed).length > 0){
if (confirm(`${Object.keys(vars.permissionList.changed).length}개의 변경사항을 저장하시겠습니까?`)) {
upsertAuthList();
}
} else {
searchResultInit();
document.querySelector('.permission-modal').style.display = 'none';
}
});
//설정창 취소
document.getElementById('permission-cancel').addEventListener('click', () => {
if (vars.permissionList.changed && Object.keys(vars.permissionList.changed).length > 0) {
if (!confirm(`${Object.keys(vars.permissionList.changed).length}개의 변경사항을 저장하지 않고 취소하시겠습니까?`)) {
return;
}
}
// 이름 검색 결과창 초기화
searchResultInit();
document.querySelector('.permission-modal').style.display = 'none';
});
//tab 변경
document.querySelectorAll('.permission-modal input[type="radio"]').forEach(ele => {
ele.addEventListener('click', (e) => {
document.querySelector('.permission-modal .modal-wrap .left .search-result-container').style.display = 'none';
document.querySelector('.permission-modal .modal-wrap .left ul').style.display = 'block';
let id = e.target.id;
let tab = document.querySelector('.permission-modal .select-list-' + id);
drawUserPermissionList(vars.permissionList, id);
[...tab.parentElement.children].forEach(element => {
if (element.classList.contains('select-list')) element.style.display = 'none';
});
tab.style.display = 'block';
})
});
export async function getList() {
let param = {
// project_id : JSON.parse(localStorage.getItem('data')).id
project_id: vars.project_id
}
let res = await axios.get('/auth/getMemberList', { params: param });
return res.data;
}
// 유저권한설정창
export async function drawUserPermissionList(list, rightId = 'sub-master') {
document.querySelector('.permission-modal .left ul').innerHTML = '';
document.querySelectorAll(`.permission-modal .select-list ul`).forEach(ul => ul.innerHTML = '');
// DB에 저장횐 company-list가 6개 외에 더 있어서 회사 리스트 고정
const companyList = [ '한맥기술', '삼안', '장헌산업', `(주)장헌` , '피티씨' , '한라산업개발', '바론컨설턴트' , '기타'];
// 기존 권한을 가진 인원(key-value)들을 배열화
const permission = Object.values(list.changePermission);
try {
// changePermission에는 user_id - lev만 있기때문에 배열을 DB로 보내 유저 정보를 가져온다
const usersInfoRes = await axios.post('/auth/getPermissionUserInfo', {permission : permission});
const userInfoArr = usersInfoRes.data.result;
const rightUl = document.querySelector(`.permission-modal .select-list.select-list-${rightId} ul`);
userInfoArr.forEach(user => {
if (findPermission(user.user_id, permission) !== rightId) return;
if (rightUl.querySelector(`#_${user.user_id}`)) return;
// 유저 리스트 DOM 생성
const userLi = drawUserList(user, rightId, permission, true);
rightUl.appendChild(userLi);
// 클릭 이벤트
bindUserLiClick(userLi, user, rightId, permission, true);
});
// 유저 수 체크
checkPermissionUserNum(rightId);
} catch (err) {
console.error('getPermissionUserInfo', err);
}
// 회사 리스트 생성
companyList.forEach(company => {
const companyTitle = drawCompanyTitle(company);
const companyToggleImg = companyTitle.querySelector('.company-toggle img');
// 회사 리스트 클릭시 부서명 생성
companyTitle.addEventListener('click', async () => {
let deptTitle = companyTitle.nextElementSibling;
// 부서명 최초 1회 DOM 생성 이후에 토글
if (!deptTitle || !deptTitle.classList.contains('dept-container')) {
companyToggleImg.src = '/main/img/permission/down.svg';
deptTitle = document.createElement('ul');
deptTitle.className = 'dept-container _scrollbar';
deptTitle.dataset.company = company;
companyTitle.insertAdjacentElement('afterend', deptTitle);
try {
// 회사명을 통해 부서리스트 조회
const deptRes = await axios.get('/auth/getDeptList', { params: { company } });
if (deptRes.data.message === '200') {
const deptList = deptRes.data.result;
// 한글 정렬
deptList.sort((a, b) => {
if (!a.dept || !b.dept) return 0;
return a.dept.localeCompare(b.dept, 'ko');
});
// 부서 리스트 생성
for (const depts of deptList) {
if (!depts.dept) continue;
const deptLi = drawDeptTitle(company, depts.dept);
const deptToggleImg = deptLi.querySelector('.dept-toggle img');
const deptCheckBox = deptLi.querySelector('input[type="checkbox"]');
const deptToggelWrap = deptLi.querySelector('.toggle-wrap');
// 부서 개별 체크 박스 change 이벤트
deptCheckBox.addEventListener('change', async (e) => {
const isChecked = deptCheckBox.checked;
const rightUl = document.querySelector(`.permission-modal .right .select-list.select-list-${rightId} ul`);
try {
// 회사명 - 부서를 통해 부서의 유저를 전부 조회
const userRes = await axios.get('/auth/getUserList', { params: { company, dept: depts.dept }});
const userList = userRes.data.result;
// 부서 전체 선택시에 이미 권한이 있어 권한을 부여할 수 없는 인원 수를 체크하는 배열
const diffGroupArr = [];
// 유저 리스트 생성
for (let user of userList) {
const existingRight = rightUl.querySelector(`#_${user.user_id}`);
const existingLeft = document.querySelector(`.permission-modal .left ul li#_${user.user_id} .user-wrap`);
const lev = findPermission(user.user_id, Object.values(vars.permissionList.changePermission));
// 전체 선택시
if (isChecked) {
// 이미 오른쪽(권한이 있던)에 있는 인원과 권한이 다른 인원은 continue로 건너뛰기
if (existingRight) continue;
if (lev && lev !== rightId){
diffGroupArr.push(user);
continue;
}
// 부관리자 10명 제한
if (rightId === 'sub-master' && rightUl.children.length >= 10) {
updateCheckboxState(user.company, user.dept);
return alert('부관리자는 최대 10명까지 선택 가능합니다.');
}
// 전체선택으로 권한 변경된 유저 권한 변경
changePermission(user.user_id, rightId, undefined);
// 오른쪽 리스트에 생성
const copy = drawUserList(user, rightId, permission, true);
rightUl.appendChild(copy);
// 클릭이벤트 추카
bindUserLiClick(copy, user, rightId, permission, true);
// 왼쪽 유저리스트에 권한 뱃지 생성
if (existingLeft) {
const roleDiv = createRoleDiv(rightId);
existingLeft.insertAdjacentHTML('beforeend', roleDiv);
existingLeft.classList.add('selected_' + rightId);
existingLeft.style.display = 'flex';
}
} else {
// 전체 선택해제
if (existingRight) {
// 오른쪽 DOM 삭제와 권한 해제
existingRight.remove();
changePermission(user.user_id, undefined, rightId);
}
// 왼쪽 유저 리스트에 권한 뱃지 삭제
existingLeft?.querySelector(`.user-permission-${rightId}`)?.remove();
existingLeft?.classList.remove(`selected_${rightId}`);
}
}
// 체크 박스 상태 변화 감지
updateCheckboxState(company, depts.dept);
if (diffGroupArr.length > 0){
alert(`이미 권한을 가진 ${diffGroupArr.length}명은 ${{'sub-master' : '부관리자', 'security-worker' : '보안참여자', 'worker' : '일반참여자', 'viewer' : '참관자'}[rightId]} 권한을 부여할 수 없습니다.`);
deptCheckBox.checked = true;
}
} catch (err) {
console.error('getUserList Error (checkbox): ', err);
}
});
// 체크 박스 상태 변화 감지
updateCheckboxState(company, depts.dept);
// 부서명 클릭 이벤트
deptToggelWrap.addEventListener('click', async () => {
let userTitle = deptLi.nextElementSibling;
// 유저 최초 1회 생성 이후에 토글
if (!userTitle || !userTitle.classList.contains('user-container')) {
deptToggleImg.src = '/main/img/permission/down.svg';
userTitle = document.createElement('ul');
userTitle.className = 'user-container _scrollbar';
deptLi.insertAdjacentElement('afterend', userTitle);
// 회사명,부서명으로 유저리스트 조회
const userRes = await axios.get('/auth/getUserList', { params: { company, dept: depts.dept }});
if (userRes.data.message === '200') {
const userList = userRes.data.result;
// 유저리스트 생성
userList.forEach(user => {
// 유저 DOM 생성
const userLi = drawUserList(user, rightId, permission);
userTitle.appendChild(userLi);
// 유저 클릭 이벤트
bindUserLiClick(userLi, user, rightId, permission);
});
}
}
// 유저 토글 처리
userTitle.style.display = userTitle.style.display === 'block' ? 'none' : 'block';
deptToggleImg.src = userTitle.style.display === 'block' ? '/main/img/permission/down.svg' : '/main/img/permission/up.svg';
});
}
}
} catch (error) {
console.error('getDeptList Error', error);
}
}
// 부서 토글처리
deptTitle.style.display = deptTitle.style.display === 'block' ? 'none' : 'block';
companyToggleImg.src = deptTitle.style.display === 'block' ? '/main/img/permission/down.svg' : '/main/img/permission/up.svg';
});
});
}
// 유저 검색 기능 엔터 이벤트
document.getElementById('permission-search').addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
// input 값 추출 이후 DOM 생성
const keyword = e.target.value.trim().toLowerCase();
searchResultUser(keyword);
}
});
// 유저 검색 기능 클릭 이벤트
document.querySelector('.permission-modal .modal-wrap .left .search-box .wrap .search-image').addEventListener('click', () => {
const keyword = document.querySelector('.permission-modal .modal-wrap .left .search-input').value.trim().toLowerCase();
searchResultUser(keyword);
});
// 유저 검색 기능(엔터, 검색바 클릭)
function searchResultUser(keyword) {
// 프로젝트 관리자를 제외하고 검색하기 위해 필터링
const users = vars.permissionList.all.filter(user => user.user_id !== vars.project.user_id);
const searchResult = document.querySelector('.permission-modal .modal-wrap .left .search-result-container');
const permissionLeftUl = document.querySelector('.permission-modal .modal-wrap .left ul');
const permission = Object.values(vars.permissionList.changePermission);
const rightId = document.querySelector('.permission-modal .modal-wrap .tab-input:checked').id;
const positionMap = {'회장': 1, '부회장':2, '사장':3, '상임고문':4, '기술위원':5, '부사장':6, '고문':7, '전무이사':8, '수석연구원':9, '상무이사':10, '이사':11, '책임연구원':12, '부장':13, '차장':14, '선임연구원':15, '과장':16, '연구원':17, '대리':18, '사원':19};
if (keyword !== '') {
// 이름으로 필터링 이후 직급으로 정렬
const result = users.filter(user => user.user_nm?.toLowerCase().includes(keyword)).sort((a,b) => {
const aPosition = positionMap[a.position] ?? 99;
const bPosition = positionMap[b.position] ?? 99;
if(aPosition !== bPosition) return aPosition - bPosition;
return a.user_id.localeCompare(b.user_id);
})
if (result.length === 0) {
searchResult.style.display = 'none';
permissionLeftUl.style.display = 'block';
return alert('일치하는 사용자가 없습니다.');
}
searchResult.innerHTML = '';
// 조회된 유저 있을때
result.forEach(user => {
//유저 DOM 생성
const userLi = drawUserList(user, rightId, permission);
searchResult.appendChild(userLi);
//클릭이벤트
bindUserLiClick(userLi, user, rightId, permission, false);
});
// 검색결과창 띄우기
searchResult.style.display = 'block';
permissionLeftUl.style.display = 'none';
} else {
// 빈 값 입력시 검색결과창 내리기
searchResult.style.display = 'none';
permissionLeftUl.style.display = 'block';
}
}
// 유저 검색결과 초기화(닫기버튼, X버튼 클릭시 실행)
function searchResultInit(){
const searchResult = document.querySelector('.search-result-container');
searchResult.innerHTML = '';
searchResult.style.display = 'none';
document.querySelector('.permission-modal .modal-wrap .left ul').style.display = 'block';
document.querySelector('.permission-modal .left .search-input').value = '';
}
// 회사명 DOM 생성
function drawCompanyTitle(company){
if(company == '(주)장헌') company = '장헌';
if(company == '피티씨') company = 'PTC';
const companyTitle = document.createElement('li');
companyTitle.className = 'company-title';
companyTitle.innerHTML += `