- 달력 표시에 일반근무 글자 숨기기(hideRegular). 앱·웹 달력 칸과 위젯 및 근무표 그림에서만 빼고 오늘 카드·날짜 상세·기본 달력 반영·구독은 그대로 - 달력 연동 안내 페이지(/calendar/guide): 구독 주소 · 안드로이드 앱 기본 달력 반영 · 구글 · 삼성 · 아이폰 · 아웃룩 · 파일 · 문제 해결. 글은 관리자에서 고침(guide_text.py 기본값) - 게시판(/calendar/board, board.py): 게시판 종류와 읽기·쓰기·댓글 권한을 관리자에서 만들고 고침, 글·댓글 쓰기·고치기·지우기, 운영진 숨김·고정·되살리기, 하루 한도 - 관리자: 설정 칸에 화면 구분(page)과 숫자·색·긴 글 종류. 색·메뉴·탭 제목·처음 기본값(웹)·게시판 한도 - 홈페이지 위쪽 메뉴 줄, 달력 연동·공유 창과 앱 메뉴에서 안내 페이지로 가는 링크 - 검사: 서버 103개(게시판 9개 새로), 앱 단위 54개, 위젯 기기 검사에 숨기기 확인. 로고 가져오기 시험의 같은 초 기록 순서 흔들림 고침
247 lines
37 KiB
JavaScript
247 lines
37 KiB
JavaScript
'use strict';
|
||
/* 웹과 휴대폰은 같은 일정 구조를 사용한다. 화면은 서버 원본 위에 아직 전송하지 못한
|
||
* 변경을 덧씌워 표시한다. 저장 응답을 놓쳐도 같은 변경 번호를 다시 보내면 중복 적용되지 않는다.
|
||
* 충돌한 내용은 별도로 보관하며 사용자가 선택하기 전에는 서버 값을 덮어쓰지 않는다. */
|
||
const $ = id => document.getElementById(id);
|
||
const labels = {DUTY:'당직',OFF:'비번',REGULAR:'일반근무',DAY:'주간',EVENING:'오후',NIGHT:'야간',REST:'휴무',LEAVE:'연차·휴가',SICK:'병가',TRAINING:'교육',ANNUAL_LEAVE:'연차',MONTHLY_LEAVE:'월차',VACATION:'일반휴가',OFFICIAL_LEAVE:'공가',FAMILY_LEAVE:'경조휴가'};
|
||
// 일반근무는 회원이 정한 이름(달력 표시의 일반근무 이름)으로 보인다. 근무 식별자 REGULAR는 그대로라 근무표와 다른 사람 자료는 바뀌지 않는다.
|
||
const DEFAULT_REGULAR = labels.REGULAR, REGULAR_NAME_MAX = 8;
|
||
let regularShort = '일반';
|
||
function cleanRegularName(value){return String(value??'').trim().split(/\s+/).filter(Boolean).join(' ');}
|
||
function shortRegular(name){const chars=[...name];return chars.length<=3?name:chars.slice(0,2).join('');}
|
||
function applyShiftNames(){const name=cleanRegularName(displaySettings().regularName)||siteRegularName();labels.REGULAR=name||DEFAULT_REGULAR;regularShort=name?shortRegular(name):'일반';for(const node of document.querySelectorAll('.regular-name'))node.textContent=labels.REGULAR;}
|
||
// 고르는 목록에서는 바꾼 이름이 다른 근무 이름과 같을 때 원래 이름을 덧붙여 구분한다(예: 주간 (일반근무)).
|
||
function shiftChoices(){return Object.entries(labels).map(([value,name])=>[value,value==='REGULAR'&&name!==DEFAULT_REGULAR&&Object.entries(labels).some(([other,label])=>other!=='REGULAR'&&label===name)?name+' ('+DEFAULT_REGULAR+')':name]);}
|
||
const classes = {DUTY:'duty',OFF:'off',REGULAR:'regular',DAY:'daytime',EVENING:'evening',NIGHT:'night',REST:'rest',LEAVE:'rest',SICK:'rest',TRAINING:'night',ANNUAL_LEAVE:'rest',MONTHLY_LEAVE:'rest',VACATION:'rest',OFFICIAL_LEAVE:'rest',FAMILY_LEAVE:'rest'};
|
||
const categories = {GENERAL:'개인 일정',WORK:'업무',PARTTIME:'알바·시간근무',LEAVE:'휴가·휴무',BIRTHDAY:'생일',ANNIVERSARY:'기념일'};
|
||
const todayKey = () => new Intl.DateTimeFormat('sv-SE',{timeZone:'Asia/Seoul',year:'numeric',month:'2-digit',day:'2-digit'}).format(new Date());
|
||
const dayDate = key => new Date(key+'T00:00:00Z');
|
||
const dateKey = date => date.toISOString().slice(0,10);
|
||
let member=null, watchGeneration=0, refreshedAt=0;
|
||
const MONTH_MS=30*24*60*60*1000;
|
||
const stateCacheKey=()=> 'duty-calendar-state:'+member.id;
|
||
const personColors={BLUE:'파랑',PURPLE:'보라',ORANGE:'주황',PINK:'분홍',TEAL:'청록',BROWN:'갈색'};
|
||
let selected=todayKey(), month=selected.slice(0,7), model={calendarId:'',revision:0,items:[]}, pending=[], conflicts=[], connected=false, saving=false, editId=null, holidayData={}, lunarData=null;
|
||
const cacheKey=()=> 'duty-calendar:'+model.calendarId;
|
||
// 서버 원본 전체를 브라우저 저장 공간에 복제하지 않는다. 재전송에 필요한 미완료 변경만 보관한다.
|
||
function persist(){if(model.calendarId){localStorage.setItem(cacheKey(),JSON.stringify({pending,conflicts}));if(member){try{localStorage.setItem(stateCacheKey(),JSON.stringify({state:model,refreshedAt}));}catch{localStorage.removeItem(stateCacheKey());}}}}
|
||
function effective(){const result=new Map(model.items.map(item=>[item.id,item]));for(const op of pending)result.set(op.id,{...op,version:op.baseVersion});return [...result.values()].filter(item=>!item.deleted);}
|
||
// 회원이 달력 표시를 직접 저장하기 전에는 관리자 '처음 기본값(웹)'을 쓴다. 저장한 값이 있으면 그 값이 먼저다.
|
||
function siteDefaults(){const s=window.dutySiteSettings||{};return {dutyAsWeekday:s.defaultDutyWeekday===true,showLunar:s.defaultShowLunar===true,offAsHoliday:s.defaultOffRed===true,weekStart:s.defaultWeekStart==='1'?1:0,hideRegular:s.defaultHideRegular===true,regularName:''};}
|
||
function siteRegularName(){return cleanRegularName(window.dutySiteSettings?.defaultRegularName);}
|
||
function displaySettings(){const own=effective().find(item=>item.kind==='preferences')?.data??effective().find(item=>item.kind==='rotation')?.data;return {...siteDefaults(),...(own||{})};}
|
||
document.addEventListener('duty-site',()=>{try{render();}catch{}});
|
||
function rotation(){const base=effective().find(item=>item.kind==='rotation')?.data;return base?{...base,...displaySettings()}:undefined;}
|
||
// 토요일 휴무로 바꾸어도 다음 날의 반복 순서는 그대로 이어진다. 자료에 기준이 없으면 기존 주6일제로 읽는다.
|
||
function shiftFor(data,key){
|
||
return WorkPlan.shift(data,key);
|
||
}
|
||
function shiftOn(key){return shiftFor(rotation(),key);}
|
||
function personalPeople(){return effective().filter(item=>item.kind==='person');}
|
||
function people(){const shared=(model.company?.members||[]).filter(person=>!person.isSelf&&person.rotation).map(person=>({id:'company:'+person.id,kind:'person',shared:true,data:{name:person.name,color:person.color,...person.rotation}}));return [...personalPeople(),...shared].sort((a,b)=>a.data.name.localeCompare(b.data.name));}
|
||
function personShift(item,key){return shiftFor(item.data,key);}
|
||
function eventsOn(key){return effective().filter(item=>item.kind==='event'&&eventOccurrence(item.data,key)!==null).concat(anniversaryOccurrences(key)).sort((a,b)=>Number(b.data.allDay)-Number(a.data.allDay)||a.data.startTime.localeCompare(b.data.startTime)||a.data.title.localeCompare(b.data.title));}
|
||
function holiday(key){return holidayData[key.slice(0,4)]?.[key]?.join(' · ')||'';}
|
||
function text(tag,value,cls){const node=document.createElement(tag);node.textContent=value;if(cls)node.className=cls;return node;}
|
||
function notify(message){$('toast').textContent=message;$('toast').hidden=false;clearTimeout(notify.timer);notify.timer=setTimeout(()=>$('toast').hidden=true,4000);}
|
||
// 브라우저 전체를 막는 기본 확인 창 대신 페이지 안에서 취소와 실행을 선택한다.
|
||
// 취소하거나 뒤로 닫으면 원래 편집 내용은 유지하고 삭제나 연결 해제를 실행하지 않는다.
|
||
function confirmAction(message,label){return new Promise(resolve=>{const dialog=$('confirm-dialog');$('confirm-message').textContent=message;$('confirm-accept').textContent=label;const finish=value=>{dialog.close();resolve(value);};$('confirm-cancel').onclick=()=>finish(false);$('confirm-accept').onclick=()=>finish(true);dialog.oncancel=event=>{event.preventDefault();finish(false);};dialog.showModal();});}
|
||
function updateStatus(message){$('status').textContent=message||(conflicts.length?'수정 내용 확인 필요':pending.length?'기기에 저장 · 전송 대기':'서버 저장 완료 · 변경 시 갱신');$('conflict-notice').hidden=conflicts.length===0;}
|
||
async function api(path,body){const options={headers:{'X-Duty-Request':'1'},cache:'no-store'};if(body!==undefined){options.method='POST';options.headers['Content-Type']='application/json';options.body=JSON.stringify(body);}const response=await fetch('api/'+path,options);const result=await response.json();if(!response.ok){const error=new Error(typeof result.detail==='string'?result.detail:'요청을 처리하지 못했습니다.');error.status=response.status;throw error;}return result;}
|
||
function queue(id,kind,data,deleted=false){const existing=pending.find(op=>op.id===id);const remote=model.items.find(item=>item.id===id);if(deleted&&Object.keys(data).length===0)data=existing?.data&&Object.keys(existing.data).length?existing.data:remote?.data||data;pending=pending.filter(op=>op.id!==id);if(existing)conflicts=conflicts.filter(changeId=>changeId!==existing.changeId);pending.push({id,kind,data,deleted,baseVersion:existing?.baseVersion??remote?.version??0,changeId:crypto.randomUUID()});persist();render();sync();}
|
||
async function sync(force=false){
|
||
if(saving||!connected)return;saving=true;let again=false;
|
||
try{
|
||
// 여러 날짜 복사와 긴 근무 계획은 요청 크기를 나눠 전송한다. 성공한 묶음만 지우며
|
||
// 충돌 항목은 사용자가 선택할 때까지 보관하고 연결 실패 때 자동 재귀하지 않는다.
|
||
let sent=false;
|
||
for(let batch=0;batch<10;batch++){
|
||
const toSend=[];let writeBytes=32;
|
||
for(const op of pending.filter(op=>!conflicts.includes(op.changeId)).slice(0,100)){
|
||
const size=new TextEncoder().encode(JSON.stringify(op)).length+1;
|
||
if(writeBytes+size>220000&&toSend.length)break;toSend.push(op);writeBytes+=size;
|
||
}
|
||
if(!toSend.length)break;
|
||
const result=await api('mutations',{operations:toSend});sent=true;
|
||
model=result.state;refreshedAt=Date.now();
|
||
pending=pending.filter(op=>!result.accepted.includes(op.changeId));
|
||
conflicts=[...new Set([...conflicts,...result.conflicts])].filter(id=>pending.some(op=>op.changeId===id));
|
||
persist();
|
||
if(!result.accepted.length&&!result.conflicts.length)break;
|
||
again=pending.some(op=>!conflicts.includes(op.changeId));
|
||
if(!again)break;
|
||
}
|
||
if(!sent&&(force||!refreshedAt||Date.now()-refreshedAt>=MONTH_MS)){model=await api('state');refreshedAt=Date.now();}
|
||
persist();render();return true;
|
||
}catch(error){again=false;if(error.status===401)showWelcome('다시 로그인해 주세요.');else updateStatus('연결 대기 · 작성 내용 보관 중');if(error.status===400||error.status===429)notify(error.message);return false;}
|
||
finally{saving=false;if(again&&connected)setTimeout(()=>sync(),1000);}
|
||
}
|
||
async function watch(run){while(connected&&run===watchGeneration){try{const result=await api('changes?after='+model.revision+'&company_after='+encodeURIComponent(model.companyVersion||''));if(run!==watchGeneration)break;if(result.revision!==model.revision||(result.companyVersion||'')!==(model.companyVersion||'')||pending.some(op=>!conflicts.includes(op.changeId)))await sync(true);}catch(error){if(run!==watchGeneration)break;updateStatus('연결 대기 · 작성 내용 보관 중');await new Promise(resolve=>setTimeout(resolve,5000));if(error.status===401){showWelcome('다시 로그인해 주세요.');notify('로그인이 만료됐습니다. 다시 로그인해 주세요.');}}}}
|
||
// 공개 화면은 앱 소개와 설치 안내만 제공한다. 회원 자료와 편집 화면은 인증 확인 뒤 연다.
|
||
// 로그인 만료 때도 같은 전환을 사용하므로 이전 회원 화면이 계속 남지 않는다.
|
||
function showWelcome(message='로그인 없이 앱 설치 가능'){
|
||
connected=false;watchGeneration++;
|
||
document.querySelectorAll('dialog[open]').forEach(dialog=>dialog.close());
|
||
$('welcome').hidden=false;$('workspace').hidden=true;$('public-auth').hidden=false;
|
||
for(const id of ['connect','logout','admin-open','company-open','refresh-data'])$(id).hidden=true;
|
||
document.body.classList.remove('with-people','five-day');updateStatus(message);
|
||
}
|
||
async function enter(){
|
||
member=(await api('me')).member;
|
||
$('public-auth').hidden=true;$('connect').hidden=false;$('logout').hidden=false;
|
||
$('admin-open').hidden=member.role!=='admin'||member.mustChangePassword;
|
||
if(member.mustChangePassword){connected=false;$('welcome').hidden=false;$('workspace').hidden=true;$('account-notice').textContent='초기 비밀번호를 변경한 뒤 사용할 수 있습니다.';openPassword();return;}
|
||
$('account-notice').textContent='';
|
||
let stored;try{stored=JSON.parse(localStorage.getItem(stateCacheKey())||'null');}catch{}
|
||
if(stored?.state?.calendarId===member.calendarId&&Array.isArray(stored.state.items)&&stored.refreshedAt<=Date.now()&&Date.now()-stored.refreshedAt<MONTH_MS){model=stored.state;refreshedAt=stored.refreshedAt;}
|
||
else{model=await api('state');refreshedAt=Date.now();}
|
||
let cached;try{cached=JSON.parse(localStorage.getItem(cacheKey())||'null');}catch{}
|
||
pending=Array.isArray(cached?.pending)?cached.pending:[];conflicts=Array.isArray(cached?.conflicts)?cached.conflicts:[];
|
||
connected=true;$('company-open').hidden=false;$('refresh-data').hidden=false;
|
||
$('welcome').hidden=true;$('workspace').hidden=false;
|
||
loadPlannerAssets();render();await sync();watch(++watchGeneration);
|
||
if(location.hash==='#work-team'&&typeof WorkTeam!=='undefined')WorkTeam.open().catch(error=>notify(error.message));
|
||
}
|
||
function render(){
|
||
applyShiftNames();
|
||
if(typeof renderCompany==='function')renderCompany();
|
||
const today=todayKey(),day=dayDate(today),r=rotation(),display=displaySettings(),current=shiftOn(today);
|
||
document.body.classList.toggle('five-day',false);
|
||
$('today-date').textContent=new Intl.DateTimeFormat('ko-KR',{month:'long',day:'numeric',weekday:'long',timeZone:'UTC'}).format(day);
|
||
$('today-duty').textContent=current?'오늘은 '+labels[current]:'근무표를 설정해 주세요';
|
||
$('today-caption').textContent=eventsOn(today).length?`오늘 예정된 일정 ${eventsOn(today).length}개`:'여유 있게 하루를 계획하세요.';
|
||
$('rotation-label').textContent=r?'주'+(WorkPlan.regime(r,today).workWeek||6)+'일제 · '+WorkPlan.regime(r,today).pattern.length+'일 반복 근무':'반복 근무를 등록할 수 있습니다.';
|
||
const days=Array.from({length:new Date(Number(month.slice(0,4)),Number(month.slice(5)),0).getDate()},(_,i)=>month+'-'+String(i+1).padStart(2,'0'));$('month-count').textContent=effective().filter(item=>item.kind==='event'&&days.some(key=>eventOccurrence(item.data,key)!==null)).length+personalAnniversaries().filter(item=>days.some(key=>annualMatches(item.data,key,lunarData))).length;
|
||
$('month').textContent=Number(month.slice(0,4))+'년 '+Number(month.slice(5))+'월';
|
||
const companions=people();document.body.classList.toggle('with-people',companions.length>0);$('grid').replaceChildren();const first=calendarFirstDate(month,display.weekStart);
|
||
$('calendar-weekdays').replaceChildren();for(const day of calendarWeekdays(display.weekStart))$('calendar-weekdays').append(text('span',['일','월','화','수','목','금','토'][day],day===0?'sun':day===6?'sat':''));
|
||
for(let i=0;i<42;i++){const date=new Date(first);date.setUTCDate(first.getUTCDate()+i);const key=dateKey(date),shift=shiftOn(key),name=holiday(key),events=eventsOn(key);const button=document.createElement('button');button.type='button';button.className='day'+(key.slice(0,7)!==month?' outside':'')+(key===selected?' selected':'')+(key===today?' current':'')+(date.getUTCDay()===0?' sun':date.getUTCDay()===6?(r&&WorkPlan.regime(r,key).workWeek===5?' sat holiday':' sat'):'')+(name?' holiday':'')+(display.dutyAsWeekday===true&&shift==='DUTY'?' duty-weekday':'')+(display.offAsHoliday===true&&shift==='OFF'?' off-red':'');button.setAttribute('aria-label',`${key} ${shift?labels[shift]:''} ${name} 일정 ${events.length}개`);button.append(text('span',String(date.getUTCDate()),'day-number'));const lunar=display.showLunar?lunarLabel(key):null;if(lunar){button.classList.add('with-lunar');button.append(text('span',lunar,'lunar-date'));button.setAttribute('aria-label',button.getAttribute('aria-label')+' '+lunar);}if(shift)button.append(text('span',shift==='REGULAR'?regularShort:labels[shift],'shift '+classes[shift]+(shift==='REGULAR'&&display.hideRegular===true?' is-hidden':'')));for(const workName of workNamesOn(key).slice(0,2))button.append(text('span',workName.name,'work-name person-'+workName.color.toLowerCase()));if(name)button.append(text('span',name.includes('대체공휴일')?'대체휴일':name.replace('기독탄신일','성탄절').replace('1월 1일','신정'),'holiday-name'));if(events.length)button.append(text('span','일정 '+events.length+'개','event-count'));const annual=events.find(item=>item.kind==='anniversary');if(annual)button.append(text('span',annual.data.title,'anniversary-badge'));const duties=companions.filter(item=>WorkPlan.working(personShift(item,key)));for(const item of duties.slice(0,2))button.append(text('span',item.data.name,'person-badge person-'+item.data.color.toLowerCase()));if(duties.length>2)button.append(text('span','외 '+(duties.length-2)+'명','event-count'));button.setAttribute('aria-label',button.getAttribute('aria-label')+' '+labels.REGULAR+' 아래 이름 '+workNamesOn(key).map(item=>item.name).join(' ')+' 함께 근무 '+duties.map(item=>item.data.name).join(' '));button.onclick=()=>{selected=key;render();};$('grid').append(button);}
|
||
const selectedDay=dayDate(selected);$('selected-date').textContent=new Intl.DateTimeFormat('ko-KR',{month:'long',day:'numeric',weekday:'short',timeZone:'UTC'}).format(selectedDay);$('day-detail').textContent=[labels[shiftOn(selected)],holiday(selected)].filter(Boolean).join(' · ')||'등록한 일정을 확인하고 새로 추가하세요.';
|
||
$('agenda').replaceChildren();const events=eventsOn(selected);if(!events.length)$('agenda').append(text('div','등록된 일정이 없습니다.\n가벼운 메모부터 시작해 보세요.','empty'));for(const item of events){const node=document.createElement('button');node.className='event-item '+(item.data.category==='PARTTIME'?'parttime':item.data.category==='WORK'?'work':item.data.category==='LEAVE'?'leave':'');node.append(text('strong',item.data.title),text('span',eventTimeSummary(item.data)),text('span',categories[item.data.category]));node.onclick=()=>openEvent(item);$('agenda').append(node);}
|
||
$('people-list').replaceChildren();if(!companions.length)$('people-list').append(text('p','이름과 근무 주기를 등록해 함께 볼 수 있습니다.','small'));for(const item of companions){const node=text('button',item.data.name+' · '+labels[personShift(item,selected)],'person-row person-'+item.data.color.toLowerCase());node.append(text('small','주'+(item.data.workWeek||6)+'일제 · '+WorkPlan.regime(item.data,selected).pattern.length+'일 반복 · '+personColors[item.data.color]));if(item.shared)node.append(text('small','소속 공유 · 본인만 수정 가능'));node.onclick=()=>item.shared?openCompany():openPerson(item);$('people-list').append(node);}
|
||
$('holiday-note').textContent=holidayData[month.slice(0,4)]?(localStorage.getItem('duty-holiday-saved')==='1'?' · 서버에 보관된 정상 자료 사용':''):'이 연도의 공휴일 자료가 아직 없습니다.';updateStatus();
|
||
}
|
||
function eventTimeSummary(d){if(d.allDay)return '하루 종일';const days=(dayDate(d.endDate)-dayDate(d.date))/86400000;return d.startTime+' – '+(days===1?'다음 날 ':days>1?days+'일 뒤 ':'')+d.endTime;}
|
||
function openEvent(item,partTime=false){if(item?.kind==='anniversary'){openAnniversary(item);return;}editId=item?.id??null;const d=item?.data??{title:'',date:selected,endDate:selected,allDay:!partTime,startTime:'09:00',endTime:'10:00',notes:'',category:partTime?'PARTTIME':'GENERAL'};$('event-heading').textContent=item?'일정 수정':'일정 추가';$('event-title').value=d.title;$('event-category').value=d.category;$('event-date').value=d.date;$('event-end').value=d.endDate;$('event-all-day').checked=d.allDay;$('time-fields').hidden=d.allDay;$('event-start-time').value=d.startTime;$('event-end-time').value=d.endTime;$('event-notes').value=d.notes;$('event-repeat').value=d.repeat||'NONE';$('event-repeat-until').value=d.repeatUntil||'';$('event-repeat-until-label').hidden=$('event-repeat').value==='NONE';$('event-reminder').value=String(d.reminderMinutes??-1);$('event-error').textContent='';$('event-delete').hidden=!item;$('event-all-day').disabled=d.category==='PARTTIME';$('event-dialog').showModal();}
|
||
$('parttime-add').onclick=()=>openEvent(null,true);
|
||
$('event-category').onchange=()=>{const timed=$('event-category').value==='PARTTIME';$('event-all-day').disabled=timed;if(timed){$('event-all-day').checked=false;$('time-fields').hidden=false;}};
|
||
$('event-repeat').onchange=()=>$('event-repeat-until-label').hidden=$('event-repeat').value==='NONE';
|
||
$('event-all-day').onchange=()=>$('time-fields').hidden=$('event-all-day').checked;
|
||
$('event-date').onchange=()=>{if($('event-end').value<$('event-date').value)$('event-end').value=$('event-date').value;};
|
||
$('event-form').onsubmit=async event=>{event.preventDefault();const d={title:$('event-title').value.trim(),category:$('event-category').value,date:$('event-date').value,endDate:$('event-end').value,allDay:$('event-all-day').checked,startTime:$('event-start-time').value,endTime:$('event-end-time').value,notes:$('event-notes').value,repeat:$('event-repeat').value,repeatUntil:$('event-repeat').value==='NONE'?'':$('event-repeat-until').value,reminderMinutes:Number($('event-reminder').value)};const duration=(dayDate(d.endDate)-dayDate(d.date))/86400000;if(!d.title||(d.repeatUntil&&d.repeatUntil<d.date)||duration<0||duration>366||(!d.allDay&&d.date+'T'+d.startTime>=d.endDate+'T'+d.endTime)){$('event-error').textContent='제목과 기간을 확인해 주세요. 종료 시간은 시작 이후여야 합니다.';return;}const warnings=WorkManagement.conflicts(d,editId);if(warnings.length&&!await confirmAction(warnings.join('\n')+'\n\n예정된 1년 범위의 참고 안내입니다. 이대로 저장할까요?','그대로 저장'))return;queue(editId??crypto.randomUUID(),'event',d);$('event-dialog').close();notify('일정을 저장했습니다.');};
|
||
$('event-delete').onclick=async()=>{if(await confirmAction('이 일정을 삭제할까요? 연결된 기기에도 반영됩니다.','일정 삭제')){queue(editId,'event',{},true);$('event-dialog').close();notify('일정을 삭제했습니다.');}};
|
||
$('add').onclick=()=>openEvent();$('day-add').onclick=()=>openEvent();
|
||
function moveMonth(step){const d=dayDate(month+'-01');d.setUTCMonth(d.getUTCMonth()+step);month=dateKey(d).slice(0,7);render();}
|
||
$('prev').onclick=()=>moveMonth(-1);$('next').onclick=()=>moveMonth(1);$('today').onclick=()=>{selected=todayKey();month=selected.slice(0,7);render();};
|
||
function drawRotation(pattern){$('rotation-count').value=pattern.length;$('rotation-days').replaceChildren();pattern.forEach((shift,index)=>{const label=text('label',(index+1)+'일째');const select=document.createElement('select');for(const [value,name] of shiftChoices()){const option=text('option',name);option.value=value;select.append(option);}select.value=shift;label.append(select);$('rotation-days').append(label);});}
|
||
$('rotation').onclick=()=>{const r=rotation()??{anchor:todayKey(),pattern:['DUTY','OFF']};$('rotation-anchor').value=r.anchor;$('rotation-work-week').value=String(r.workWeek||6);resetPatternMode('rotation');drawRotation(r.pattern);$('rotation-error').textContent='';$('rotation-dialog').showModal();};
|
||
$('rotation-form').onsubmit=event=>{event.preventDefault();const pattern=[...$('rotation-days').querySelectorAll('select')].map(node=>node.value);if(pattern.length!==Number($('rotation-count').value)){$('rotation-error').textContent='반복 일수를 확인해 주세요.';return;}queue('rotation','rotation',{...rotation(),...displaySettings(),anchor:$('rotation-anchor').value,pattern,workWeek:Number($('rotation-work-week').value)});$('rotation-dialog').close();notify('반복 근무를 저장했습니다.');};
|
||
// 저장 시 최신 근무표에서 표시 항목만 바꾼다. 기초 설정과 옵션이 서로의 값을 되돌리지 않게 한다.
|
||
function openDisplayOptions(){
|
||
const r=displaySettings();
|
||
$('rotation-duty-weekday').checked=r.dutyAsWeekday===true;
|
||
$('rotation-show-lunar').checked=r.showLunar===true;
|
||
$('rotation-off-red').checked=r.offAsHoliday===true;
|
||
$('rotation-week-start').value=String(r.weekStart===1?1:0);
|
||
$('regular-name').value=cleanRegularName(r.regularName);$('regular-name').placeholder=siteRegularName()||DEFAULT_REGULAR;$('regular-hide').checked=r.hideRegular===true;$('options-error').textContent='';
|
||
$('options-dialog').showModal();
|
||
};
|
||
$('options-form').onsubmit=event=>{
|
||
event.preventDefault();const regularName=cleanRegularName($('regular-name').value);
|
||
if([...regularName].length>REGULAR_NAME_MAX){$('options-error').textContent='일반근무 이름은 '+REGULAR_NAME_MAX+'자까지 입력할 수 있습니다.';return;}
|
||
if(/\p{C}/u.test(regularName)){$('options-error').textContent='일반근무 이름에 쓸 수 없는 글자가 있습니다.';return;}
|
||
queue('preferences','preferences',{dutyAsWeekday:$('rotation-duty-weekday').checked,showLunar:$('rotation-show-lunar').checked,offAsHoliday:$('rotation-off-red').checked,weekStart:Number($('rotation-week-start').value),regularName,hideRegular:$('regular-hide').checked});
|
||
$('options-dialog').close();notify('개인 설정을 저장했습니다.');
|
||
};
|
||
let authMode='login', personId=null;
|
||
function openAuth(mode){authMode=mode;$('auth-form').reset();$('auth-error').textContent='';const joining=mode==='register',resetting=mode==='reset';$('auth-heading').textContent=joining?'회원가입':resetting?'비밀번호 복구':'회원 로그인';$('auth-submit').textContent=joining?'가입하고 시작':resetting?'비밀번호 재설정':'로그인';$('auth-help').textContent=joining?'아이디는 영문과 숫자 및 밑줄 3~32자입니다. 비밀번호는 6자 이상으로 입력해 주세요.':resetting?'관리자가 본인 확인 후 발급한 복구 코드를 입력하세요.':'홈페이지와 앱에서 같은 회원으로 로그인하세요.';$('auth-name-label').hidden=!joining;$('auth-name').required=joining;$('auth-code-label').hidden=!resetting;$('auth-code').required=resetting;$('auth-repeat-label').hidden=mode==='login';$('auth-repeat').required=mode!=='login';$('auth-password').minLength=mode==='login'?1:6;$('auth-password').autocomplete=mode==='login'?'current-password':'new-password';$('auth-recovery').hidden=mode!=='login';if(!$('auth-dialog').open)$('auth-dialog').showModal();}
|
||
$('create').onclick=()=>openAuth('register');$('join').onclick=()=>openAuth('login');$('auth-recovery').onclick=()=>openAuth('reset');
|
||
$('auth-dialog').addEventListener('close',()=>{$('auth-password').value='';$('auth-repeat').value='';$('auth-code').value='';});
|
||
$('auth-form').onsubmit=async event=>{event.preventDefault();$('auth-error').textContent='';if(authMode!=='login'&&$('auth-password').value!==$('auth-repeat').value){$('auth-error').textContent='비밀번호 확인이 일치하지 않습니다.';return;}$('auth-submit').disabled=true;try{const data={username:$('auth-username').value.trim().toLowerCase(),password:$('auth-password').value,kind:'web'};if(authMode==='register')data.displayName=$('auth-name').value.trim();if(authMode==='reset')data.code=$('auth-code').value.trim();await api(authMode==='reset'?'reset-password':authMode,data);if(authMode==='reset'){openAuth('login');notify('비밀번호를 바꿨습니다. 새 비밀번호로 로그인하세요.');}else{$('auth-dialog').close();await enter();}}catch(error){$('auth-error').textContent=error.message;}finally{$('auth-submit').disabled=false;}};
|
||
$('connect').onclick=()=>{$('account-description').textContent=member.displayName+' · '+member.username+' · '+(member.role==='admin'?'관리자':'일반 회원');$('account-dialog').showModal();};
|
||
function openPassword(){$('password-form').reset();$('password-error').textContent='';if(!$('password-dialog').open)$('password-dialog').showModal();}
|
||
$('password-open').onclick=()=>{$('account-dialog').close();openPassword();};
|
||
$('password-dialog').addEventListener('close',()=>$('password-form').reset());
|
||
$('password-form').onsubmit=async event=>{event.preventDefault();if($('password-new').value!==$('password-repeat').value){$('password-error').textContent='새 비밀번호 확인이 일치하지 않습니다.';return;}const button=event.submitter;button.disabled=true;try{await api('password',{currentPassword:$('password-current').value,password:$('password-new').value});$('password-dialog').close();watchGeneration++;await enter();notify('비밀번호를 변경했습니다. 다른 기기는 다시 로그인하세요.');}catch(error){$('password-error').textContent=error.message;}finally{button.disabled=false;}};
|
||
// 위쪽 메뉴와 내 정보 창의 로그아웃이 같은 절차를 쓴다. 전송 대기 내용이 있으면 잃지 않도록 먼저 멈춘다.
|
||
async function logoutNow(){if($('account-dialog').open)$('account-dialog').close();if(pending.length){notify('전송 대기 중인 내용이 있습니다. 동기화를 마친 뒤 로그아웃해 주세요.');return;}if(!await confirmAction('이 브라우저에서 로그아웃할까요? 다시 로그인하면 저장한 일정을 볼 수 있습니다.','로그아웃'))return;try{await api('logout',{});connected=false;watchGeneration++;localStorage.removeItem(cacheKey());localStorage.removeItem(stateCacheKey());location.reload();}catch(error){notify(error.message);}}
|
||
$('logout').onclick=logoutNow;$('account-logout').onclick=logoutNow;
|
||
|
||
function drawPerson(pattern){$('person-count').value=pattern.length;$('person-days').replaceChildren();pattern.forEach((shift,index)=>{const label=text('label',(index+1)+'일째'),select=document.createElement('select');for(const [value,name] of shiftChoices()){const option=text('option',name);option.value=value;select.append(option);}select.value=shift;label.append(select);$('person-days').append(label);});}
|
||
function openPerson(item){if(!item&&personalPeople().length>=20){notify('함께 볼 사람은 20명까지 등록할 수 있습니다.');return;}personId=item?.id??null;const d=item?.data??{name:'',color:'BLUE',anchor:selected,pattern:['DUTY','OFF','REGULAR']};$('person-heading').textContent=item?'함께 보는 근무표 수정':'함께 볼 사람 추가';$('person-name').value=d.name;$('person-color').value=d.color;$('person-anchor').value=d.anchor;$('person-work-week').value=String(d.workWeek||6);$('person-duty-weekday').checked=d.dutyAsWeekday===true;resetPatternMode('person');drawPerson(d.pattern);$('person-delete').hidden=!item;$('person-error').textContent='';$('person-dialog').showModal();}
|
||
$('person-add').onclick=()=>openPerson();
|
||
$('person-form').onsubmit=event=>{event.preventDefault();const pattern=[...$('person-days').querySelectorAll('select')].map(node=>node.value),name=$('person-name').value.trim();if(!name||pattern.length!==Number($('person-count').value)){$('person-error').textContent='이름과 반복 일수를 확인해 주세요.';return;}queue(personId??crypto.randomUUID(),'person',{name,color:$('person-color').value,anchor:$('person-anchor').value,pattern,workWeek:Number($('person-work-week').value),dutyAsWeekday:$('person-duty-weekday').checked});$('person-dialog').close();notify('함께 보는 근무표를 저장했습니다.');};
|
||
$('person-delete').onclick=async()=>{if(await confirmAction('이 캘린더에 등록한 사람의 근무표를 삭제할까요?','근무표 삭제')){queue(personId,'person',{},true);$('person-dialog').close();}};
|
||
|
||
// 회원·소속·홈페이지 설정은 관리자 페이지(admin)에서 다룬다. 이 화면에서는 이동 버튼만 둔다.
|
||
$('admin-open').onclick=()=>{location.href='admin';};
|
||
|
||
function describe(item){if(!item||item.deleted)return '삭제된 일정';const d=item.data;if(item.kind==='anniversary')return d.title+'\n'+annualDescription(d)+'\n'+d.notes;if(item.kind==='preferences')return '당직일 평일색: '+(d.dutyAsWeekday?'켜짐':'꺼짐')+'\n비번 빨간색: '+(d.offAsHoliday?'켜짐':'꺼짐')+'\n음력 표시: '+(d.showLunar?'켜짐':'꺼짐')+'\n주 시작: '+(d.weekStart===1?'월요일':'일요일')+'\n일반근무 이름: '+(cleanRegularName(d.regularName)||DEFAULT_REGULAR+' (기본)')+'\n일반근무 숨기기: '+(d.hideRegular?'켜짐':'꺼짐');if(item.kind==='name_rule')return d.name+'\n'+nameRuleDescription(d);if(item.kind==='person')return `${d.name} · ${personColors[d.color]}\n첫째 날: ${d.anchor}\n${d.pattern.map(key=>labels[key]).join(' → ')}`;if(item.kind==='rotation')return `첫째 날: ${d.anchor}\n${d.pattern.map(key=>labels[key]).join(' → ')}`;return `${d.title}\n${d.date} ~ ${d.endDate}\n${d.allDay?'하루 종일':d.startTime+' ~ '+d.endTime}\n${categories[d.category]}\n${d.notes}`;}
|
||
function showConflict(){const op=pending.find(item=>conflicts.includes(item.changeId));if(!op){$('conflict-dialog').close();return;}$('conflict-local').textContent=describe(op);$('conflict-remote').textContent=describe(model.items.find(item=>item.id===op.id));if(!$('conflict-dialog').open)$('conflict-dialog').showModal();}
|
||
$('resolve').onclick=showConflict;
|
||
function resolveConflict(useLocal){const op=pending.find(item=>conflicts.includes(item.changeId));if(!op)return;pending=pending.filter(item=>item.changeId!==op.changeId);conflicts=conflicts.filter(id=>id!==op.changeId);if(useLocal)pending.push({...op,baseVersion:model.items.find(item=>item.id===op.id)?.version??0,changeId:crypto.randomUUID()});persist();render();showConflict();sync();}
|
||
$('use-remote').onclick=()=>resolveConflict(false);$('use-local').onclick=()=>resolveConflict(true);
|
||
document.querySelectorAll('.close').forEach(button=>button.onclick=()=>button.closest('dialog').close());
|
||
window.addEventListener('online',()=>sync());window.addEventListener('beforeunload',event=>{if(pending.length){event.preventDefault();event.returnValue='';}});
|
||
// 공휴일은 서버와 함께 배포한 자료를 읽는다. 서버의 갱신 작업이 원본을 확인한 뒤 파일을 교체한다.
|
||
enter().catch(error=>showWelcome(error.status===401?'로그인 없이 앱 설치 가능':'연결을 확인해 주세요. 앱 설치는 바로 할 수 있습니다.'));
|
||
|
||
// 유형은 앱과 같은 자료에서 읽는다. 기존 자료를 열 때는 직접 설정으로 시작해 원래 순서를 보존한다.
|
||
let workPatterns=[];
|
||
function resetPatternMode(prefix){$(prefix+'-mode').value='custom';$(prefix+'-remainder-label').hidden=true;$(prefix+'-count').min='1';}
|
||
function resizePattern(prefix){
|
||
const duty=$(prefix+'-mode').value==='duty', input=$(prefix+'-count'),count=Number(input.value),minimum=duty?2:1;
|
||
if(!Number.isInteger(count)||count<minimum||count>366){$(prefix+'-error').textContent=`${minimum}~366 사이의 숫자를 입력해 주세요.`;return;}
|
||
$(prefix+'-error').textContent='';
|
||
const old=[...$(prefix+'-days').querySelectorAll('select')].map(node=>node.value);
|
||
const pattern=Array.from({length:count},(_,i)=>duty?(i===0?'DUTY':i===1?'OFF':$(prefix+'-remainder').value):(old[i]??'REGULAR'));
|
||
(prefix==='rotation'?drawRotation:drawPerson)(pattern);
|
||
}
|
||
for(const prefix of ['rotation','person']){
|
||
$(prefix+'-count').addEventListener('input',()=>resizePattern(prefix));
|
||
$(prefix+'-remainder').onchange=()=>resizePattern(prefix);
|
||
$(prefix+'-mode').onchange=()=>{
|
||
const choice=$(prefix+'-mode').value,duty=choice==='duty';
|
||
$(prefix+'-remainder-label').hidden=!duty;$(prefix+'-count').min=duty?'2':'1';
|
||
if(duty){if(Number($(prefix+'-count').value)<2)$(prefix+'-count').value='2';resizePattern(prefix);}
|
||
else if(choice!=='custom'){const pattern=workPatterns.find(item=>item.id===choice)?.pattern;if(pattern)(prefix==='rotation'?drawRotation:drawPerson)(pattern);}
|
||
$(prefix+'-error').textContent='';
|
||
};
|
||
}
|
||
let plannerAssetsStarted=false;
|
||
function loadPlannerAssets(){
|
||
// 소개 화면을 보는 동안에는 달력 자료를 받지 않는다. 로그인 후 필요한 자료만 한 번 준비한다.
|
||
if(plannerAssetsStarted)return;plannerAssetsStarted=true;
|
||
cachedAsset('lunar-months.json').then(data=>{lunarData=data;if(connected)render();}).catch(()=>notify('음력 자료를 불러오지 못했습니다. 연결 후 다시 확인해 주세요.'));
|
||
cachedAsset('holidays.json').then(data=>{holidayData=data;if(connected)render();}).catch(()=>{});
|
||
cachedAsset('work-patterns.json').then(data=>{
|
||
if(!Array.isArray(data)||data.some(item=>!Array.isArray(item.pattern)||!item.pattern.length||item.pattern.length>366||item.pattern.some(key=>!labels[key])))throw new Error();
|
||
workPatterns=data;
|
||
for(const prefix of ['rotation','person'])for(const item of data){const option=text('option',item.name);option.value=item.id;$(prefix+'-mode').append(option);}
|
||
}).catch(()=>notify('근무 유형 예시를 불러오지 못했습니다. 직접 설정은 사용할 수 있습니다.'));
|
||
}
|
||
|
||
// 전체 자료는 최초 연결과 변경 알림 및 월별 갱신과 수동 요청에서만 받는다.
|
||
// 공개 자료도 같은 주기로 보관한다. 인증이 필요한 개인·소속 자료는 회원별 키로 분리하고 로그아웃 때 지운다.
|
||
async function cachedAsset(name,force=false,refreshSource=force){
|
||
const key='duty-public-0.5:'+name;let cached;try{cached=JSON.parse(localStorage.getItem(key)||'null');}catch{}
|
||
if(!force&&cached&&Date.now()-cached.at<MONTH_MS)return cached.data;
|
||
try{const response=await fetch(name==='holidays.json'?'api/holidays'+(refreshSource?'?refresh=true':''):'assets/'+name);if(!response.ok)throw new Error();const data=await response.json();if(name==='holidays.json'){
|
||
if(!data||!Object.values(data).every(days=>days&&typeof days==='object'&&Object.entries(days).every(([day,names])=>/^20\d{2}-\d{2}-\d{2}$/.test(day)&&Array.isArray(names)&&names.length&&names.every(value=>typeof value==='string'))))throw new Error();
|
||
localStorage.setItem('duty-holiday-revision',response.headers.get('X-Holiday-Revision')||'');
|
||
localStorage.setItem('duty-holiday-saved',response.headers.get('X-Holiday-Saved')||'1');
|
||
}localStorage.setItem(key,JSON.stringify({at:Date.now(),data}));return data;}
|
||
catch(error){if(cached)return cached.data;throw error;}
|
||
}
|
||
$('refresh-data').onclick=async()=>{const success=await sync(true);if(success){try{holidayData=await cachedAsset('holidays.json',true);render();}catch{}notify('새로 불러왔습니다.');}else notify('서버에 연결하지 못했습니다. 저장된 자료를 유지합니다.');};
|
||
|
||
// 한국 음력 월 시작일 사이의 날짜 차이를 사용한다. 지원 범위 밖은 추측해 표시하지 않는다.
|
||
function lunarLabel(key){
|
||
if(!lunarData||key<lunarData.start||key>lunarData.end)return null;
|
||
const day=Math.floor(dayDate(key).getTime()/86400000),rows=lunarData.months;
|
||
let low=0,high=rows.length;
|
||
while(low<high){const mid=(low+high)>>>1;if(rows[mid][0]<=day)low=mid+1;else high=mid;}
|
||
if(!low)return null;const row=rows[low-1];return (row[2]?'윤':'음')+row[1]+'.'+(day-row[0]+1);
|
||
}
|