Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3060246e9f | ||
|
|
e678b8520b | ||
|
|
9a5c920705 | ||
|
|
5f2e2f6952 | ||
|
|
2116ef5607 | ||
|
|
1ab3778bb3 | ||
|
|
c057fda86f |
No files matched your search
+32
-1
@@ -1,3 +1,34 @@
|
||||
# 0.16.1 · 웹 2026-12-01.2 · 2026년 12월 1일
|
||||
|
||||
- 앱을 열어 둔 채 날짜가 바뀌거나 며칠 만에 다시 열어도 달력이 지난달에 머물지 않습니다. 보던 달이 그 전 오늘의 달이었으면 이번 달로 넘어가고 고른 날도 오늘로 옮깁니다. 12월 1일인데 11월 달력의 회색 칸에 오늘이 보이던 문제입니다.
|
||||
- 달력 위젯은 지난달에 옮겨 둔 달을 버리고 이번 달을 보입니다. 이번 달로 다시 돌아오면 옮긴 기록을 지워 다음 달이 되면 따라갑니다.
|
||||
- 웹 달력도 열어 둔 채 자정이 지나면 같은 방식으로 이번 달로 넘어갑니다.
|
||||
- 직접 다른 달로 옮겨 둔 화면과 직접 고른 날짜는 그대로 둡니다.
|
||||
|
||||
# 0.16.0 · 웹 2026-12-01.1 · 2026년 12월 1일
|
||||
|
||||
- 관리자 페이지에 **공지** 메뉴를 따로 만들었습니다. 한 화면에서 공지 띠를 켜고 끄며 공지사항 글을 쓰고 고치고 고정합니다.
|
||||
- 공지 띠는 홈페이지 맨 위와 앱 첫 화면 맨 위에 같은 글로 보입니다. 앱은 열 때마다 새 공지를 확인하고 연결이 없을 때는 마지막으로 받은 공지를 보여 줍니다.
|
||||
- 공지 띠 칸은 관리자 **홈페이지** 화면에서 **공지** 화면으로 옮겼습니다. 저장된 공지는 그대로입니다. 공지사항 글은 지금처럼 홈페이지 게시판에 올라갑니다.
|
||||
|
||||
# 관리자 로고 화면 · 2026년 12월 1일
|
||||
|
||||
- 관리자 로고 화면은 그림 올리기와 보관한 그림 고르기만 합니다. 그림을 만드는 칸과 기능은 뺐습니다.
|
||||
- 보관한 그림 아래에는 넣은 날과 넣은 사람만 보입니다. 웹 버전과 앱 APK 및 회원 자료는 바뀌지 않았습니다.
|
||||
|
||||
# 0.15.9 · 웹 2026-11-26.4 · 2026년 11월 26일
|
||||
|
||||
- 앱과 웹 안의 글에서 근무 뒤 괄호 이름을 뺐습니다. '오늘은 비번(이정훈)'이 아니라 '오늘은 비번' 아래 줄에 '당직자 이정훈'으로 보입니다.
|
||||
- 날짜를 눌렀을 때 나오는 창도 제목은 날짜와 근무만 보이고 그 아래 줄에 당직자가 보입니다. 웹의 선택한 날짜 설명도 같습니다.
|
||||
- 위젯은 '오늘 비번 · 당직자 이정훈', '내일 일반근무 · 당직자 강주석'처럼 보입니다. 오늘 위젯은 큰 근무 글자 아래 줄에 당직자가 보입니다.
|
||||
- 달력 칸의 이름 표시와 다른 달력 연동 제목(이름 칸을 켠 경우)은 그대로입니다.
|
||||
|
||||
# 0.15.8 · 웹 2026-11-26.3 · 2026년 11월 26일
|
||||
|
||||
- 다른 달력 연동(구독 주소와 앱의 기본 달력 자동 반영)에 **근무 순서 이름 함께 보내기**를 날 종류마다 체크로 나눴습니다. 당직·근무 날 · 비번 날 · 휴무 날 · 연차·휴가·반차·병가·교육 날을 따로 켭니다.
|
||||
- 연동 달력의 기본은 **이름 표기 없음**입니다. 체크하지 않은 날은 이름 없이 근무 글자만 보냅니다. 이미 만든 구독 주소와 켜 둔 자동 반영도 새 칸을 켜기 전까지는 이름 없이 보냅니다. 앱 자동 반영의 일반근무 아래 이름도 따로 체크합니다(기본 꺼짐).
|
||||
- 주5일제 토요일은 날짜만 빨간색으로 보입니다. 당직이 아닌 날을 휴무로 바꾸던 것을 없애 토요일도 일요일처럼 원래 근무 순서대로 보입니다.
|
||||
|
||||
# 0.15.7 · 웹 2026-11-26.2 · 2026년 11월 26일
|
||||
|
||||
- 휴가(연차·휴가 · 연차 · 월차 · 일반휴가 · 공가 · 경조휴가)와 병가를 쓴 날은 달력과 위젯의 날짜 숫자가 빨간색으로 보입니다.
|
||||
@@ -77,7 +108,7 @@
|
||||
|
||||
# 관리자 로고 메뉴 · 2026년 11월 24일
|
||||
|
||||
- 관리자 페이지에서 로고 그림을 올리거나 제미나이로 후보를 만들어 홈페이지 로고와 브라우저 탭 및 홈 화면 아이콘을 바꿀 수 있습니다.
|
||||
- 관리자 페이지에서 로고 그림을 올리거나 보관한 그림에서 골라 홈페이지 로고와 브라우저 탭 및 홈 화면 아이콘을 바꿀 수 있습니다.
|
||||
- 기본 로고로 언제든 되돌릴 수 있습니다. 앱 설치 정보는 서비스 이름과 바꾼 아이콘을 따라갑니다.
|
||||
- 웹 버전과 앱 APK 및 회원 자료는 바뀌지 않았습니다.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 당직근무
|
||||
|
||||
제작자 블리어 (이창현) · 미리보기 0.15.7 · Android 8.0 이상
|
||||
제작자 블리어 (이창현) · 미리보기 0.16.1 · Android 8.0 이상
|
||||
|
||||
당직과 교대근무를 달력으로 확인하고 홈 화면에 계속 놓아두는 앱입니다. 본인의 근무표는 로그인 없이 사용할 수 있습니다. 서버가 잠시 멈춰도 기기에 저장한 근무와 일정 및 기념일은 그대로 사용합니다.
|
||||
|
||||
@@ -117,6 +117,10 @@ JDK 21과 Android SDK 36을 설치한 뒤 프로젝트를 Android Studio에서
|
||||
|
||||
기존 위젯과 휴대폰 달력 자동 반영 및 서버 달력 구독도 날짜별 변경과 근무제 이력을 사용합니다. 기존 회원 자료와 월요일 시작 등 표시 설정은 보존합니다. 새 기능을 사용하기 전에 앱을 0.14.0 이상으로 업데이트해 주세요. 스토어 등록은 장기 목표로만 고려하며 현재 포럼 배포 방식을 유지합니다.
|
||||
|
||||
## 0.15.8 연동 달력 이름 선택과 토요일
|
||||
|
||||
다른 달력 연동(구독 주소와 앱의 기본 달력 자동 반영)에서 근무 순서 이름은 **당직·근무 날 · 비번 날 · 휴무 날 · 연차·휴가·반차·병가·교육 날**마다 따로 체크합니다. 기본은 이름 표기 없음이라 체크하지 않은 날은 근무 글자만 보냅니다. 주5일제 토요일은 날짜만 빨간색으로 보이고 근무는 원래 순서대로 보입니다(휴무로 바꾸지 않음).
|
||||
|
||||
## 0.15.0 근무 순서 이름
|
||||
|
||||
**옵션 → 근무 순서 이름**에서 당직 다음 날(비번)부터 순서대로 그날 당직 서는 사람 이름을 적습니다. 달력에는 이름 줄마다 고른 대로 둘 다·이름만·근무만으로 보입니다(0.15.4부터 줄마다 따로 고름). 근무 순서와 날짜는 바뀌지 않습니다. 연차·반차·휴가·병가·교육·휴무로 바꾼 날에도 그날 이름이 같이 보이고(0.15.6부터) 당직 같은 다른 근무로 바꾼 날은 근무만 보입니다.
|
||||
|
||||
@@ -12,8 +12,8 @@ android {
|
||||
applicationId = "kr.co.itosm.dutycalendar"
|
||||
minSdk = 26
|
||||
targetSdk = 36
|
||||
versionCode = 31
|
||||
versionName = "0.15.7"
|
||||
versionCode = 35
|
||||
versionName = "0.16.1"
|
||||
testInstrumentationRunner = "kr.co.itosm.dutycalendar.StorageSyncCheck"
|
||||
}
|
||||
buildTypes {
|
||||
|
||||
@@ -45,7 +45,7 @@ object CalendarBridgeCheck {
|
||||
val today=LocalDate.now();ScheduleStore.save(app,Schedule(today,listOf(Shift.DUTY,Shift.OFF,Shift.REGULAR),5),fromSync=true)
|
||||
val id=UUID.randomUUID().toString();val event=JSONObject().put("title","야간 검증").put("notes","검증 메모").put("category","PARTTIME").put("date",today.toString()).put("endDate",today.plusDays(1).toString()).put("allDay",false).put("startTime","22:00").put("endTime","06:00").put("repeat","WEEKLY").put("repeatUntil",today.plusDays(14).toString()).put("reminderMinutes",-1)
|
||||
PlannerStore.put(app,id,"event",event)
|
||||
CalendarMirror.configure(app,calendarId,"검증 달력",true,true,false)
|
||||
CalendarMirror.configure(app,calendarId,"검증 달력",true,true,false,false,MirrorNames())
|
||||
fun rows():Map<Long,String>{val result=mutableMapOf<Long,String>();app.contentResolver.query(CalendarContract.Events.CONTENT_URI,arrayOf("_id","title"),"calendar_id=? AND deleted=0",arrayOf(calendarId.toString()),null)!!.use{while(it.moveToNext())result[it.getLong(0)]=it.getString(1)};return result}
|
||||
stage="등록과 재실행 중복 방지";waitFor{CalendarMirror.run(app,it)};val initial=rows();check(initial.size==401){"예상 401개 실제 ${initial.size}"};waitFor{CalendarMirror.run(app,it)};check(rows()==initial)
|
||||
stage="제목 변경과 원본 보존";event.put("title","변경한 야간 검증");PlannerStore.put(app,id,"event",event);waitFor{CalendarMirror.run(app,it)}
|
||||
@@ -63,11 +63,17 @@ object CalendarBridgeCheck {
|
||||
ScheduleStore.saveDisplay(app,plan.dutyAsWeekday,plan.showLunar,plan.offAsHoliday,plan.weekStart,fromSync=true,hideRegular=false)
|
||||
// 0.15.6: 연차로 바꾼 날에도 그날 자리 이름이 남고 이름만 고른 줄도 연차 글자를 같이 보낸다. 당직으로 바꾼 날은 이름을 비운다.
|
||||
stage="연차 날 이름";val leave=today.plusDays(2)
|
||||
// 0.15.8: 이름은 날 종류마다 고른다(기본 꺼짐). 이 단계는 모두 켜고 본다.
|
||||
CalendarMirror.configure(app,calendarId,"검증 달력",true,true,false,false,MirrorNames(work=true,off=true,rest=true,away=true))
|
||||
fun titleOn():String?{var title:String?=null;val start=leave.atStartOfDay(java.time.ZoneOffset.UTC).toInstant().toEpochMilli();app.contentResolver.query(CalendarContract.Events.CONTENT_URI,arrayOf("title"),"calendar_id=? AND deleted=0 AND allDay=1 AND dtstart=?",arrayOf(calendarId.toString(),start.toString()),null)!!.use{while(it.moveToNext())title=it.getString(0)};return title}
|
||||
for(mode in listOf("both","name","shift"))for((shift,expectedTitle) in listOf(Shift.LEAVE to "연차·휴가",Shift.ANNUAL_LEAVE to "연차",Shift.DUTY to "당직")){
|
||||
ScheduleStore.save(app,plan.copy(names=listOf("","김철수","이영희"),nameModes=listOf("",mode,mode),workPlan=WorkPlan(overrides=mapOf(leave to DayOverride(shift)))),fromSync=true);waitFor{CalendarMirror.run(app,it)}
|
||||
val wanted=if(shift==Shift.DUTY||mode=="shift")expectedTitle else "$expectedTitle(이영희)";val actual=titleOn();check(actual==wanted){"$mode $shift: $actual (기대 $wanted)"}
|
||||
}
|
||||
// 0.15.8: 이름 칸을 모두 끄면(기본) 연차 날에도 이름 없이 근무 글자만 보낸다.
|
||||
stage="이름 기본 꺼짐";CalendarMirror.configure(app,calendarId,"검증 달력",true,true,false,false,MirrorNames())
|
||||
ScheduleStore.save(app,plan.copy(names=listOf("","김철수","이영희"),nameModes=listOf("","both","name"),workPlan=WorkPlan(overrides=mapOf(leave to DayOverride(Shift.ANNUAL_LEAVE)))),fromSync=true);waitFor{CalendarMirror.run(app,it)}
|
||||
check(titleOn()=="연차"){"이름 기본 꺼짐: ${titleOn()}"};check(rows().values.none{it.contains("김철수")||it.contains("이영희")}){"이름이 남음"}
|
||||
ScheduleStore.save(app,plan,fromSync=true);waitFor{CalendarMirror.run(app,it)};check(rows().size==398){"연차 해제: ${rows().size}개"}
|
||||
stage="앱 사본만 삭제";waitFor{CalendarMirror.stop(app,true,it)};check(rows()==mapOf(unrelated to "외부 원본 보존"))
|
||||
passed=true
|
||||
|
||||
@@ -51,14 +51,15 @@ class StorageSyncCheck : Instrumentation() {
|
||||
var result = ""
|
||||
var ok = false
|
||||
try {
|
||||
val trial = Schedule(LocalDate.of(2026, 11, 20), listOf(Shift.DUTY, Shift.REGULAR, Shift.NIGHT), 5, true, true, true)
|
||||
// 0.14.0부터 저장된 근무표는 늘 근무 계획(workPlan)을 갖는다. 비교가 기기에 남은 날짜별 변경에 흔들리지 않게 빈 계획으로 저장한다.
|
||||
val trial = Schedule(LocalDate.of(2026, 11, 20), listOf(Shift.DUTY, Shift.REGULAR, Shift.NIGHT), 5, true, true, true, workPlan = WorkPlan())
|
||||
ScheduleStore.save(app, trial)
|
||||
check(ScheduleStore.load(app) == trial && !SyncClient.connected(app))
|
||||
check(LunarDates.label(app, LocalDate.of(2026, 2, 17)) == "음1.1")
|
||||
check(LunarDates.label(app, LocalDate.of(2026, 9, 25)) == "음8.15")
|
||||
check(LunarDates.label(app, LocalDate.of(2025, 7, 25)) == "윤6.1")
|
||||
check(LunarDates.label(app, LocalDate.of(2051, 1, 1)) == null)
|
||||
check(ScheduleStore.load(app).shiftOn(LocalDate.of(2026, 11, 21)) == Shift.REST)
|
||||
check(ScheduleStore.load(app).shiftOn(LocalDate.of(2026, 11, 21)) == Shift.REGULAR)
|
||||
// 이전 버전에서 로그인 없이 등록한 사람을 흉내 낸다. 기록은 보관하되 회원 연결 전에는 표시하지 않는다.
|
||||
PlannerStore.put(app, java.util.UUID.randomUUID().toString(), "person", JSONObject()
|
||||
.put("name", "보관 검증").put("color", "TEAL").put("anchor", "2026-11-20")
|
||||
@@ -70,7 +71,7 @@ class StorageSyncCheck : Instrumentation() {
|
||||
DutyWidget.updateAll(app)
|
||||
done { SyncClient.sync(app, complete = it) }
|
||||
check(PlannerStore.refreshedAt(app) == 0L && PlannerStore.pendingCount(app) > 0)
|
||||
result = "로그인 없는 본인 근무 저장과 토요일 휴무 및 공휴일과 위젯 갱신 확인. 회원용 근무표 숨김과 원본 보관 확인"
|
||||
result = "로그인 없는 본인 근무 저장과 주5일제 토요일 원래 근무 및 공휴일과 위젯 갱신 확인. 회원용 근무표 숨김과 원본 보관 확인"
|
||||
if (credentials.isFile) {
|
||||
val account = JSONObject(credentials.readText())
|
||||
check(account.getString("username").startsWith("qa06_"))
|
||||
|
||||
@@ -184,7 +184,7 @@ object WidgetAppearanceCheck {
|
||||
ScheduleStore.saveDisplay(app,current.dutyAsWeekday,current.showLunar,current.offAsHoliday,start,fromSync=true)
|
||||
for(dimensions in listOf(kind.width to kind.height,320 to 440)) {
|
||||
val (width,height)=dimensions
|
||||
positions.edit().putString("month_99004","2026-08").commit()
|
||||
positions.edit().putString("month_99004","2026-08").putString("monthBase_99004",java.time.YearMonth.now().toString()).commit()
|
||||
WidgetStyle.save(app,99004,WidgetStyle(monthFit=true,scale=scale,transparency=50))
|
||||
val options=Bundle().apply {
|
||||
putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH,width);putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH,width)
|
||||
@@ -235,15 +235,25 @@ object WidgetAppearanceCheck {
|
||||
for(kind in WidgetKind.entries) {
|
||||
val id=manager.getAppWidgetIds(kind.component(app)).firstOrNull()?:continue
|
||||
WidgetStyle.save(app,id,WidgetStyle(monthFit=true))
|
||||
positions.edit().putString("month_$id","2026-12").putInt("offset_$id",14).commit()
|
||||
val now=java.time.YearMonth.now()
|
||||
positions.edit().putString("month_$id",now.plusMonths(3).toString()).putString("monthBase_$id",now.toString()).putInt("offset_$id",14).commit()
|
||||
val receiver=kind.receiver.getDeclaredConstructor().newInstance()
|
||||
receiver.onReceive(app,android.content.Intent(DutyWidget.NEXT).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,id))
|
||||
check(positions.getString("month_$id",null)=="2027-01")
|
||||
check(positions.getString("month_$id",null)==now.plusMonths(4).toString()&&positions.getString("monthBase_$id",null)==now.toString())
|
||||
check(positions.getInt("offset_$id",0)==14)
|
||||
receiver.onReceive(app,android.content.Intent(DutyWidget.PREVIOUS).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,id))
|
||||
check(positions.getString("month_$id",null)=="2026-12")
|
||||
check(positions.getString("month_$id",null)==now.plusMonths(3).toString())
|
||||
// 지금 달로 돌아오면 저장을 지워 다음 달이 되면 위젯도 따라간다.
|
||||
positions.edit().putString("month_$id",now.plusMonths(1).toString()).commit()
|
||||
receiver.onReceive(app,android.content.Intent(DutyWidget.PREVIOUS).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,id))
|
||||
check(!positions.contains("month_$id")&&!positions.contains("monthBase_$id")&&DutyWidget.selectedMonth(app,id)==now){"지금 달로 돌아온 위젯 저장"}
|
||||
// 지난달에 옮겨 둔 달은 버리고 지금 달을 보인다(2026-12-01: 12월 1일인데 11월 달력이 보이던 문제).
|
||||
positions.edit().putString("month_$id",now.minusMonths(1).toString()).putString("monthBase_$id",now.minusMonths(1).toString()).commit()
|
||||
check(DutyWidget.selectedMonth(app,id)==now){"지난달에 옮겨 둔 위젯 달"}
|
||||
positions.edit().putString("month_$id",now.minusMonths(1).toString()).remove("monthBase_$id").commit()
|
||||
check(DutyWidget.selectedMonth(app,id)==now){"옛 버전이 저장한 위젯 달"}
|
||||
receiver.onReceive(app,android.content.Intent(DutyWidget.TODAY).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,id))
|
||||
check(!positions.contains("month_$id")&&!positions.contains("offset_$id"))
|
||||
check(!positions.contains("month_$id")&&!positions.contains("monthBase_$id")&&!positions.contains("offset_$id"))
|
||||
WidgetStyle.save(app,id,WidgetStyle())
|
||||
}
|
||||
// 실제 홈 화면에 배치된 새 종류는 자신의 날짜 범위만 이동하고 오늘로 돌아와야 한다.
|
||||
@@ -260,7 +270,7 @@ object WidgetAppearanceCheck {
|
||||
}
|
||||
failure?.let{throw it}
|
||||
success=true
|
||||
message="근무 순서 이름 세 가지 표시와 줄마다 표시 및 옛 일반근무 이름 무시와 일반근무 글자 숨기기 확인. 네 종류의 기본 배치와 한 달 전체 선택 확인. 월·일 시작과 80·100·120% 및 최소·확장 크기에서 42칸과 모든 날짜 및 마지막 주의 글자 높이와 생략 없음 확인. 날짜 옆 + 없음과 연차 빨강·반차 파랑 숫자 확인. 월 이동과 연말 넘김 및 오늘 복귀와 개별 저장 및 구버전 설정 보존 확인."
|
||||
message="근무 순서 이름 세 가지 표시와 줄마다 표시 및 옛 일반근무 이름 무시와 일반근무 글자 숨기기 확인. 네 종류의 기본 배치와 한 달 전체 선택 확인. 월·일 시작과 80·100·120% 및 최소·확장 크기에서 42칸과 모든 날짜 및 마지막 주의 글자 높이와 생략 없음 확인. 날짜 옆 + 없음과 연차 빨강·반차 파랑 숫자 확인. 월 이동과 연말 넘김 및 오늘 복귀와 개별 저장 및 구버전 설정 보존 확인. 지난달에 옮겨 둔 위젯 달은 지금 달로 돌아옴 확인."
|
||||
} catch(error:Throwable) {message=error.stackTraceToString()}
|
||||
finally {
|
||||
val scheduleRestore=schedulePrefs.edit()
|
||||
|
||||
@@ -24,6 +24,20 @@ import java.util.concurrent.TimeUnit
|
||||
|
||||
data class MirroredEvent(val key:String,val title:String,val notes:String,val start:Long,val end:Long,val allDay:Boolean)
|
||||
|
||||
/**
|
||||
* 다른 달력에 이름을 함께 보낼지. 기본은 모두 꺼짐이라 이름 없이 근무 글자만 간다(2026-11-26 사용자 지시: 연동 달력은 이름 표기 없음이 기본).
|
||||
* rules는 일반근무 아래 이름(이름 규칙), 나머지는 근무 순서 이름을 날 종류마다 고른다. 서버 구독의 names · nameWork · nameOff · nameRest · nameAway와 같다.
|
||||
*/
|
||||
data class MirrorNames(val rules:Boolean=false,val work:Boolean=false,val off:Boolean=false,val rest:Boolean=false,val away:Boolean=false) {
|
||||
/** 그날 근무에 근무 순서 이름을 붙일지: 비번 · 휴무 · 연차·휴가·반차·병가·교육 · 그 밖의 근무(당직·일반근무·주간·오후·야간). */
|
||||
fun slot(shift:Shift)=when{shift==Shift.OFF->off;shift==Shift.REST->rest;shift.away->away;else->work}
|
||||
companion object {
|
||||
val KEYS=listOf("nameRules","nameWork","nameOff","nameRest","nameAway")
|
||||
fun read(settings:android.content.SharedPreferences)=MirrorNames(settings.getBoolean("nameRules",false),settings.getBoolean("nameWork",false),settings.getBoolean("nameOff",false),settings.getBoolean("nameRest",false),settings.getBoolean("nameAway",false))
|
||||
}
|
||||
fun values()=listOf(rules,work,off,rest,away)
|
||||
}
|
||||
|
||||
/** 휴대폰 달력은 이 앱 자료의 읽기용 사본이다. 원본 편집은 당직근무에서 하고 변경된 사본만 갱신한다.
|
||||
* 앱 전용 표식이 정확히 일치하는 행만 수정한다. 다른 앱 일정과 수동으로 만든 일정은 건드리지 않는다.
|
||||
* 전체 출력 목록을 만든 뒤 쓰기 때문에 자료 변환 실패가 기존 달력의 일괄 삭제로 이어지지 않는다.
|
||||
@@ -64,10 +78,10 @@ object CalendarMirror {
|
||||
if(scheduler.getPendingJob(JOB)?.intervalMillis!=period)scheduler.schedule(JobInfo.Builder(JOB,ComponentName(context,CalendarMirrorService::class.java)).setPersisted(true).setPeriodic(period).build())
|
||||
}
|
||||
fun run(context:Context,finished:(Boolean)->Unit) { executor.execute{finished(refresh(context.applicationContext))} }
|
||||
@Synchronized fun configure(context:Context,calendar:Long,title:String,rotation:Boolean,events:Boolean,anniversaries:Boolean,skipRegular:Boolean=prefs(context).getBoolean("skipRegular",false)) {
|
||||
@Synchronized fun configure(context:Context,calendar:Long,title:String,rotation:Boolean,events:Boolean,anniversaries:Boolean,skipRegular:Boolean=prefs(context).getBoolean("skipRegular",false),names:MirrorNames=MirrorNames.read(prefs(context))) {
|
||||
require(!enabled(context)||prefs(context).getLong("calendar",-1)==calendar){"대상 달력을 바꾸려면 기존 자동 반영을 먼저 해제해 주세요."}
|
||||
require(rotation||events||anniversaries){"반영할 항목을 하나 이상 선택해 주세요."}
|
||||
check(prefs(context).edit().putLong("calendar",calendar).putString("owner",owner(context)).putString("title",title).putBoolean("rotation",rotation).putBoolean("events",events).putBoolean("anniversaries",anniversaries).putBoolean("skipRegular",skipRegular).putBoolean("enabled",true).commit())
|
||||
check(prefs(context).edit().putLong("calendar",calendar).putString("owner",owner(context)).putString("title",title).putBoolean("rotation",rotation).putBoolean("events",events).putBoolean("anniversaries",anniversaries).putBoolean("skipRegular",skipRegular).apply{MirrorNames.KEYS.zip(names.values()).forEach{(key,on)->putBoolean(key,on)}}.putBoolean("enabled",true).commit())
|
||||
request(context)
|
||||
}
|
||||
fun stop(context:Context,remove:Boolean,done:(Boolean)->Unit) {
|
||||
@@ -106,7 +120,7 @@ object CalendarMirror {
|
||||
val settings=prefs(context);val calendar=settings.getLong("calendar",-1)
|
||||
val access=context.contentResolver.query(CalendarContract.Calendars.CONTENT_URI,arrayOf("calendar_access_level"),"_id=?",arrayOf(calendar.toString()),null)?.use{it.moveToFirst()&&it.getInt(0)>=CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR}?:false
|
||||
check(access){"선택한 달력이 없거나 쓰기 권한이 없습니다. 달력 연동 설정을 확인해 주세요."}
|
||||
val desired=projection(context,LocalDate.now(),settings.getBoolean("rotation",true),settings.getBoolean("events",false),settings.getBoolean("anniversaries",false),settings.getBoolean("skipRegular",false))
|
||||
val desired=projection(context,LocalDate.now(),settings.getBoolean("rotation",true),settings.getBoolean("events",false),settings.getBoolean("anniversaries",false),settings.getBoolean("skipRegular",false),MirrorNames.read(settings))
|
||||
val existing=owned(context,calendar).groupBy{it.event.key};val prefix="dutycalendar://mirror/${owner(context)}/"
|
||||
for(event in desired){
|
||||
val rows=existing[event.key].orEmpty();val old=rows.firstOrNull();val marker=prefix+event.key
|
||||
@@ -119,7 +133,7 @@ object CalendarMirror {
|
||||
settings.edit().putString("status","${desired.size}개 반영 완료").putLong("last",System.currentTimeMillis()).commit()
|
||||
}.onFailure{prefs(context).edit().putString("status",it.message?:"달력 반영을 완료하지 못했습니다. 다시 반영을 눌러 주세요.").commit()}.isSuccess
|
||||
}
|
||||
internal fun projection(context:Context,today:LocalDate,rotation:Boolean,events:Boolean,anniversaries:Boolean,skipRegular:Boolean=false):List<MirroredEvent> {
|
||||
internal fun projection(context:Context,today:LocalDate,rotation:Boolean,events:Boolean,anniversaries:Boolean,skipRegular:Boolean=false,choice:MirrorNames=MirrorNames()):List<MirroredEvent> {
|
||||
val first=today.minusDays(30);val last=today.plusDays(366);val schedule=ScheduleStore.load(context)
|
||||
val output=linkedMapOf<String,MirroredEvent>();val items=PlannerStore.items(context).filter{it.getString("kind")=="event"}
|
||||
val snapshot=CalendarSnapshot.load(context);val configured=ScheduleStore.isConfigured(context)
|
||||
@@ -128,8 +142,9 @@ object CalendarMirror {
|
||||
val day=first.plusDays(offset)
|
||||
// 일반근무 빼기를 켜면 일반근무 날은 이름까지 통째로 보내지 않는다. 끄면 앱 달력과 같게(externalTitle) 보낸다.
|
||||
if(rotation&&configured&&!(skipRegular&&schedule.shiftOn(day)==Shift.REGULAR)){
|
||||
val names=snapshot.workNames(day,schedule).joinToString(" · "){it.name}
|
||||
val text=listOf(ShiftNames.externalTitle(schedule,day),names).filter{it.isNotBlank()}.joinToString(" · ")
|
||||
// 이름은 고른 칸만 보낸다. 기본은 이름 없이 근무 글자만이다.
|
||||
val names=if(choice.rules)snapshot.workNames(day,schedule).joinToString(" · "){it.name} else ""
|
||||
val text=listOf(ShiftNames.externalTitle(schedule,day,choice.slot(schedule.shiftOn(day))),names).filter{it.isNotBlank()}.joinToString(" · ")
|
||||
if(text.isNotEmpty())add(allDay("rotation:$day",text,"당직근무에서 수정하면 자동으로 반영됩니다.",day))
|
||||
}
|
||||
if(anniversaries)for(item in snapshot.anniversariesOn(day)){val d=item.getJSONObject("data");add(allDay("anniversary:${item.getString("id")}:$day",d.getString("title"),d.getString("notes"),day))}
|
||||
|
||||
@@ -48,13 +48,17 @@ class CalendarMirrorDialogs(private val activity:Activity) {
|
||||
val settings=CalendarMirror.prefs(activity);val form=LinearLayout(activity).apply{orientation=LinearLayout.VERTICAL;val gap=(20*resources.displayMetrics.density).toInt();setPadding(gap,gap,gap,gap)}
|
||||
form.addView(TextView(activity).apply{text="$title\n\n지난 30일부터 앞으로 1년까지 자동 반영합니다. 앱에서 저장하거나 새 자료를 받으면 갱신합니다. 같은 계정 달력에는 한 기기에서만 켜 주세요."})
|
||||
fun check(label:String,key:String,default:Boolean)=CheckBox(activity).apply{text=label;isChecked=settings.getBoolean(key,default);form.addView(this)}
|
||||
val rotation=check("나의 근무표와 이름 표시","rotation",true);val skipRegular=check("일반근무 날 빼기","skipRegular",false)
|
||||
form.addView(TextView(activity).apply{text="일반근무 날 빼기를 켜면 일반근무 날은 이름까지 통째로 보내지 않습니다. 끄면 앱 달력과 같게 보냅니다.";textSize=12f})
|
||||
val rotation=check("나의 근무표","rotation",true);val skipRegular=check("일반근무 날 빼기","skipRegular",false)
|
||||
form.addView(TextView(activity).apply{text="일반근무 날 빼기를 켜면 일반근무 날은 통째로 보내지 않습니다. 끄면 앱 달력과 같게 보냅니다.";textSize=12f})
|
||||
// 2026-11-26 사용자 지시: 이름은 날 종류마다 체크로 고르고 기본은 이름 없음이다.
|
||||
form.addView(TextView(activity).apply{text="\n근무 순서 이름 함께 보내기\n체크한 날에만 이름이 붙습니다. 체크하지 않으면 이름 없이 근무 글자만 보냅니다."})
|
||||
val nameWork=check("당직·근무 날","nameWork",false);val nameOff=check("비번 날","nameOff",false);val nameRest=check("휴무 날","nameRest",false);val nameAway=check("연차·휴가·반차·병가·교육 날","nameAway",false)
|
||||
val nameRules=check("${Shift.REGULAR.title} 아래 이름 포함","nameRules",false)
|
||||
val events=check("개인 일정과 알바 · 메모 포함","events",false);val annual=check("개인 생일·기념일 · 메모 포함","anniversaries",false)
|
||||
form.addView(TextView(activity).apply{text="선택한 달력이 Google 등 계정 달력이면 그 계정의 공유 설정에 따라 다른 기기와 사람에게도 보일 수 있습니다. 알림은 당직근무 앱의 설정을 사용합니다.";textSize=12f})
|
||||
val dialog=AlertDialog.Builder(activity).setTitle("반영할 항목 선택").setView(form).setNegativeButton("취소",null).setPositiveButton("자동 반영 켜기",null).create()
|
||||
val dialog=AlertDialog.Builder(activity).setTitle("반영할 항목 선택").setView(android.widget.ScrollView(activity).apply{addView(form)}).setNegativeButton("취소",null).setPositiveButton("자동 반영 켜기",null).create()
|
||||
dialog.setOnShowListener{dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener{
|
||||
runCatching{CalendarMirror.configure(activity,calendar,title,rotation.isChecked,events.isChecked,annual.isChecked,skipRegular.isChecked)}.onSuccess{dialog.dismiss();toast("자동 반영을 시작했습니다. 기본 달력 앱에서 대상 달력을 표시해 주세요.")}.onFailure{toast(it.message?:"항목을 확인해 주세요.")}
|
||||
runCatching{CalendarMirror.configure(activity,calendar,title,rotation.isChecked,events.isChecked,annual.isChecked,skipRegular.isChecked,MirrorNames(nameRules.isChecked,nameWork.isChecked,nameOff.isChecked,nameRest.isChecked,nameAway.isChecked))}.onSuccess{dialog.dismiss();toast("자동 반영을 시작했습니다. 기본 달력 앱에서 대상 달력을 표시해 주세요.")}.onFailure{toast(it.message?:"항목을 확인해 주세요.")}
|
||||
}};dialog.show()
|
||||
}
|
||||
private fun stop(){AlertDialog.Builder(activity).setTitle("자동 반영 해제").setMessage("당직근무가 등록한 사본을 함께 지울 수 있습니다. 다른 앱에서 만든 일정은 유지합니다.")
|
||||
|
||||
@@ -51,16 +51,17 @@ object CompactWidgetViews {
|
||||
if(kind==WidgetKind.TODAY) {
|
||||
val configured=ScheduleStore.isConfigured(context)
|
||||
views.setTextViewText(R.id.compact_title,today.format(DateTimeFormatter.ofPattern("M.d E",Locale.KOREAN)))
|
||||
views.setTextViewText(R.id.compact_shift,if(configured)ShiftNames.slotTitle(schedule,today) else "설정 필요")
|
||||
views.setTextViewText(R.id.compact_shift,if(configured)schedule.shiftOn(today).title else "설정 필요")
|
||||
views.setTextColor(R.id.compact_shift,style.color(schedule.shiftColor(today)))
|
||||
val scale=style.scale/100f
|
||||
views.setTextViewTextSize(R.id.compact_shift,TypedValue.COMPLEX_UNIT_SP,(minOf((width-16)/5.3f,(height-64)/1.35f)).coerceIn(15f,26f)*scale)
|
||||
views.setInt(R.id.compact_shift,"setBackgroundColor",if(style.today)(if(style.dark)0x334A6D96 else 0x22A7B5CB) else 0)
|
||||
views.setTextViewText(R.id.compact_tomorrow,"내일 ${ShiftNames.slotTitle(schedule,today.plusDays(1))}")
|
||||
views.setTextViewText(R.id.compact_tomorrow,"내일 "+listOf(schedule.shiftOn(today.plusDays(1)).title,ShiftNames.dutyLine(schedule,today.plusDays(1))).filter{it.isNotEmpty()}.joinToString(" · "))
|
||||
views.setTextColor(R.id.compact_tomorrow,style.ink)
|
||||
views.setTextViewTextSize(R.id.compact_tomorrow,TypedValue.COMPLEX_UNIT_SP,11f*scale)
|
||||
views.setOnClickPendingIntent(R.id.compact_tomorrow,dateIntent(context,id,today.plusDays(1)))
|
||||
val details=detail(context,today,schedule,style,snapshot)
|
||||
// 당직자는 큰 근무 글자 아래 줄(상세 줄 맨 앞)에 보인다(2026-11-26 사용자 지시: 괄호로 붙이지 않기).
|
||||
val details=listOf(if(configured)ShiftNames.dutyLine(schedule,today) else "",detail(context,today,schedule,style,snapshot)).filter{it.isNotBlank()}.joinToString(" · ")
|
||||
views.setTextViewText(R.id.compact_detail,details.ifBlank{"당직근무"})
|
||||
views.setTextColor(R.id.compact_detail,style.muted)
|
||||
views.setContentDescription(R.id.compact_shift,"${today} ${schedule.shiftOn(today).title}. $details")
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import java.time.LocalDate
|
||||
import java.time.YearMonth
|
||||
|
||||
/**
|
||||
* 날짜가 바뀐 뒤 앱 첫 화면과 달력 위젯이 지난달에 머물지 않게 한다.
|
||||
* (2026-12-01 사용자 지적: 12월 1일인데 11월 달력의 회색 칸에 오늘이 표시됐다.)
|
||||
*
|
||||
* 앱 첫 화면: 보던 달과 고른 날이 그 전 '오늘'이었으면 새 오늘로 옮긴다. 사용자가 일부러 옮겨 둔 다른 달과 날짜는 그대로 둔다.
|
||||
* 달력 위젯: 달을 옮긴 때의 달(base)과 지금 달이 다르면 옮겨 둔 달을 버리고 지금 달을 보인다.
|
||||
*/
|
||||
object DayRollover {
|
||||
data class View(val month: YearMonth, val selected: LocalDate, val shownDay: LocalDate)
|
||||
|
||||
fun follow(view: View, today: LocalDate): View {
|
||||
if (today == view.shownDay) return view
|
||||
val month = if (view.month == YearMonth.from(view.shownDay)) YearMonth.from(today) else view.month
|
||||
val selected = if (view.selected == view.shownDay) today else view.selected
|
||||
return View(month, selected, today)
|
||||
}
|
||||
|
||||
/** 위젯에 저장한 달. 저장한 달이 없거나 읽지 못하거나 옮긴 때의 달이 지금 달과 다르면 지금 달이다. */
|
||||
fun widgetMonth(stored: String?, base: String?, now: YearMonth): YearMonth {
|
||||
val month = stored?.let { runCatching { YearMonth.parse(it) }.getOrNull() } ?: return now
|
||||
val from = base?.let { runCatching { YearMonth.parse(it) }.getOrNull() } ?: return now
|
||||
return if (from == now) month else now
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ open class DutyWidget : AppWidgetProvider() {
|
||||
override fun onAppWidgetOptionsChanged(context: Context, manager: AppWidgetManager, id: Int, options: Bundle) { update(context, manager, id) }
|
||||
override fun onDeleted(context: Context, ids: IntArray) {
|
||||
val editor = context.getSharedPreferences("widget", Context.MODE_PRIVATE).edit()
|
||||
ids.forEach { editor.remove("month_$it");editor.remove("offset_$it") }
|
||||
ids.forEach { editor.remove("month_$it");editor.remove("monthBase_$it");editor.remove("offset_$it") }
|
||||
editor.apply()
|
||||
context.getSharedPreferences("widget_style",0).edit().apply { ids.forEach { remove("style_$it") } }.apply()
|
||||
}
|
||||
@@ -47,8 +47,14 @@ open class DutyWidget : AppWidgetProvider() {
|
||||
val kind=WidgetKind.of(context,id)
|
||||
val prefs = context.getSharedPreferences("widget", Context.MODE_PRIVATE)
|
||||
val editor = prefs.edit()
|
||||
if (action == TODAY) { editor.remove("month_$id");editor.remove("offset_$id") }
|
||||
else if(kind==WidgetKind.MONTH||WidgetStyle.load(context,id).monthFit)editor.putString("month_$id", selectedMonth(context, id).plusMonths(if (action == NEXT) 1 else -1).toString())
|
||||
if (action == TODAY) { editor.remove("month_$id");editor.remove("monthBase_$id");editor.remove("offset_$id") }
|
||||
else if(kind==WidgetKind.MONTH||WidgetStyle.load(context,id).monthFit) {
|
||||
// 옮긴 때의 달(monthBase)을 같이 둔다. 지금 달로 돌아오면 저장을 지워 다음 달이 되면 따라가게 한다.
|
||||
val now=YearMonth.now()
|
||||
val next=selectedMonth(context, id).plusMonths(if (action == NEXT) 1 else -1)
|
||||
if(next==now){editor.remove("month_$id");editor.remove("monthBase_$id")}
|
||||
else{editor.putString("month_$id", next.toString());editor.putString("monthBase_$id", now.toString())}
|
||||
}
|
||||
else {
|
||||
val step=if(kind==WidgetKind.WIDE)14 else 7
|
||||
editor.putInt("offset_$id",(prefs.getInt("offset_$id",0)+(if(action==NEXT)step else -step)).coerceIn(-36500,36500))
|
||||
@@ -76,10 +82,11 @@ open class DutyWidget : AppWidgetProvider() {
|
||||
R.id.day_28, R.id.day_29, R.id.day_30, R.id.day_31, R.id.day_32, R.id.day_33, R.id.day_34,
|
||||
R.id.day_35, R.id.day_36, R.id.day_37, R.id.day_38, R.id.day_39, R.id.day_40, R.id.day_41
|
||||
)
|
||||
// 저장된 월을 읽지 못해도 위젯을 비워 두지 않는다. 현재 달로 복구해 정상적인 표시를 유지한다.
|
||||
internal fun selectedMonth(context: Context, id: Int): YearMonth = runCatching {
|
||||
YearMonth.parse(context.getSharedPreferences("widget", Context.MODE_PRIVATE).getString("month_$id", YearMonth.now().toString()))
|
||||
}.getOrDefault(YearMonth.now())
|
||||
// 저장된 월을 읽지 못하거나 옮긴 때의 달이 지났으면 지금 달을 보인다(DayRollover.widgetMonth).
|
||||
internal fun selectedMonth(context: Context, id: Int): YearMonth {
|
||||
val prefs=context.getSharedPreferences("widget", Context.MODE_PRIVATE)
|
||||
return DayRollover.widgetMonth(prefs.getString("month_$id", null), prefs.getString("monthBase_$id", null), YearMonth.now())
|
||||
}
|
||||
|
||||
fun updateAll(context: Context) {
|
||||
val manager = AppWidgetManager.getInstance(context)
|
||||
@@ -137,7 +144,7 @@ open class DutyWidget : AppWidgetProvider() {
|
||||
val customize=AppNavigation.widgetStyle(context,id)
|
||||
view.setOnClickPendingIntent(R.id.widget_customize,PendingIntent.getActivity(context,id,customize,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE))
|
||||
view.setTextViewText(R.id.widget_title, "${month.year}년 ${month.monthValue}월")
|
||||
view.setTextViewText(R.id.widget_subtitle, if (configured) "오늘 ${ShiftNames.slotTitle(schedule, today)} · ${(schedule.workPlan?.regime(today)?.pattern?:schedule.pattern).size}일 반복" else "앱에서 근무 시작 날짜를 설정해 주세요")
|
||||
view.setTextViewText(R.id.widget_subtitle, if (configured) "오늘 ${listOf(schedule.shiftOn(today).title, ShiftNames.dutyLine(schedule, today)).filter { it.isNotEmpty() }.joinToString(" · ")} · ${(schedule.workPlan?.regime(today)?.pattern?:schedule.pattern).size}일 반복" else "앱에서 근무 시작 날짜를 설정해 주세요")
|
||||
view.setTextViewText(R.id.widget_footer, if (month.year in Holidays.years(context)) "제작자 블리어 (이창현)" else "${month.year}년 공휴일 자료 확인 필요")
|
||||
val open = PendingIntent.getActivity(context, 0, AppNavigation.main(context), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
|
||||
view.setOnClickPendingIntent(R.id.widget_root, open)
|
||||
|
||||
@@ -24,6 +24,12 @@ import java.util.Locale
|
||||
class MainActivity : Activity() {
|
||||
private var month = YearMonth.now()
|
||||
private var selectedDate = LocalDate.now()
|
||||
// 이 화면이 '오늘'로 삼은 날. 날짜가 바뀌면 DayRollover로 달과 고른 날을 새 오늘로 옮긴다.
|
||||
private var shownDay = LocalDate.now()
|
||||
private var watchingDay = false
|
||||
private val dayWatcher = object : android.content.BroadcastReceiver() {
|
||||
override fun onReceive(context: android.content.Context, intent: android.content.Intent) { if (followToday()) render() }
|
||||
}
|
||||
private val planner by lazy { PlannerDialogs(this) { render() } }
|
||||
private val peopleEditor by lazy { PeopleDialogs(this) { render() } }
|
||||
private val anniversaries by lazy { AnniversaryDialogs(this) { render() } }
|
||||
@@ -66,6 +72,7 @@ class MainActivity : Activity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
savedInstanceState?.getString("month")?.let { month = YearMonth.parse(it) }
|
||||
savedInstanceState?.getString("selectedDate")?.let { selectedDate = LocalDate.parse(it) }
|
||||
savedInstanceState?.getString("shownDay")?.let { shownDay = LocalDate.parse(it) }
|
||||
PlannerStore.migrate(this)
|
||||
if(savedInstanceState==null) receiveNavigation(intent)
|
||||
}
|
||||
@@ -80,9 +87,10 @@ class MainActivity : Activity() {
|
||||
setIntent(incoming);receiveNavigation(incoming)
|
||||
}
|
||||
override fun onDestroy() { WidgetStyleDialog.dismiss(this);super.onDestroy() }
|
||||
override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState); outState.putString("month", month.toString()); outState.putString("selectedDate", selectedDate.toString()) }
|
||||
override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState); outState.putString("month", month.toString()); outState.putString("selectedDate", selectedDate.toString()); outState.putString("shownDay", shownDay.toString()) }
|
||||
override fun onResume() {
|
||||
super.onResume(); render(); DutyWidget.updateAll(this); Reminders.reschedule(this)
|
||||
super.onResume(); followToday(); render(); DutyWidget.updateAll(this); Reminders.reschedule(this)
|
||||
watchDay(true)
|
||||
CalendarMirror.request(this)
|
||||
Holidays.schedule(this)
|
||||
val holidayRevision=Holidays.revision(this)
|
||||
@@ -91,7 +99,26 @@ class MainActivity : Activity() {
|
||||
SyncClient.foreground(this) { runOnUiThread { if (!isFinishing && !isDestroyed) render() } }
|
||||
UpdateChecker.check(this, fresh = true)
|
||||
}
|
||||
override fun onPause() { SyncClient.background(); super.onPause() }
|
||||
override fun onPause() { watchDay(false); SyncClient.background(); super.onPause() }
|
||||
/** 날짜가 바뀌었으면 true. 보던 달과 고른 날이 그 전 오늘이었으면 새 오늘로 옮긴다. */
|
||||
private fun followToday(): Boolean {
|
||||
val today = LocalDate.now()
|
||||
if (today == shownDay) return false
|
||||
val next = DayRollover.follow(DayRollover.View(month, selectedDate, shownDay), today)
|
||||
month = next.month; selectedDate = next.selected; shownDay = next.shownDay
|
||||
return true
|
||||
}
|
||||
// 화면을 켜 둔 채 자정을 넘기거나 시간대·시계를 바꿔도 달력이 지난날에 머물지 않게 한다. 화면이 보일 때만 듣는다.
|
||||
private fun watchDay(on: Boolean) {
|
||||
if (on == watchingDay) return
|
||||
watchingDay = on
|
||||
if (!on) { runCatching { unregisterReceiver(dayWatcher) }; return }
|
||||
val filter = android.content.IntentFilter().apply {
|
||||
addAction(android.content.Intent.ACTION_TIME_TICK); addAction(android.content.Intent.ACTION_DATE_CHANGED)
|
||||
addAction(android.content.Intent.ACTION_TIME_CHANGED); addAction(android.content.Intent.ACTION_TIMEZONE_CHANGED)
|
||||
}
|
||||
if (android.os.Build.VERSION.SDK_INT >= 33) registerReceiver(dayWatcher, filter, RECEIVER_NOT_EXPORTED) else registerReceiver(dayWatcher, filter)
|
||||
}
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
// 첫 실행에서는 onResume보다 창 표시가 늦을 수 있다. 저장된 새 버전도 창이 준비된 뒤 안내한다.
|
||||
@@ -138,10 +165,27 @@ class MainActivity : Activity() {
|
||||
space(content, 8)
|
||||
content.addView(label(if (SyncClient.connected(this)) SyncClient.message else "나의 근무 기록 · 이 기기에 저장", 12f, muted))
|
||||
space(content, 20)
|
||||
// 관리자 '공지'에서 켠 공지 띠를 홈페이지와 같은 색으로 맨 위에 보인다(0.16.0).
|
||||
val notice = Notice.load(this)
|
||||
if (notice.shown) {
|
||||
val bar = row().apply {
|
||||
background = background(if (notice.warn) 0xFFF8ECE5.toInt() else 0xFFE9EEF5.toInt(), 5, if (notice.warn) 0xFFE8CBBB.toInt() else 0xFFCFD8E3.toInt())
|
||||
setPadding(dp(14), dp(11), dp(14), dp(11))
|
||||
contentDescription = "공지 " + notice.text
|
||||
}
|
||||
bar.addView(View(this).apply { background = GradientDrawable().apply { shape = GradientDrawable.OVAL; setColor(if (notice.warn) 0xFFB65B3C.toInt() else 0xFF365FAD.toInt()) } },
|
||||
LinearLayout.LayoutParams(dp(8), dp(8)).apply { marginEnd = dp(10) })
|
||||
bar.addView(label(notice.text, 14f, ink), LinearLayout.LayoutParams(0, -2, 1f))
|
||||
content.addView(bar, LinearLayout.LayoutParams(-1, -2))
|
||||
space(content, 12)
|
||||
}
|
||||
val todayCard = card(content, 0xFFFFFEFA.toInt())
|
||||
todayCard.addView(label(today.format(DateTimeFormatter.ofPattern("M월 d일 EEEE", Locale.KOREAN)), 12f, muted))
|
||||
space(todayCard, 6)
|
||||
todayCard.addView(label(if (configured) "오늘은 ${ShiftNames.slotTitle(schedule, today)}" else "근무표를 설정해 주세요", 22f, if (configured) schedule.shiftColor(today) else ink, true))
|
||||
todayCard.addView(label(if (configured) "오늘은 ${schedule.shiftOn(today).title}" else "근무표를 설정해 주세요", 22f, if (configured) schedule.shiftColor(today) else ink, true))
|
||||
// 그날 당직자는 근무 글자 뒤 괄호가 아니라 아래 줄에 따로 보인다(2026-11-26 사용자 지시).
|
||||
val todayDuty = if (configured) ShiftNames.dutyLine(schedule, today) else ""
|
||||
if (todayDuty.isNotEmpty()) { space(todayCard, 2); todayCard.addView(label(todayDuty, 15f, ink, true)) }
|
||||
space(todayCard, 6)
|
||||
todayCard.addView(label(if (configured) "${(schedule.workPlan?.regime(today)?.pattern?:schedule.pattern).size}일 반복 · 다음 날 ${schedule.shiftOn(today.plusDays(1)).title}" else "여기를 눌러 근무표를 설정하세요. 아래는 예시입니다.", 13f, muted))
|
||||
if (!configured) {
|
||||
@@ -210,17 +254,22 @@ class MainActivity : Activity() {
|
||||
if (colleagues.size > 2) addView(label("외 ${colleagues.size - 2}명", 9f, muted).apply { gravity = Gravity.CENTER })
|
||||
// 좁은 칸에서 공휴일 이름이 생략돼도 날짜를 누르면 전체 이름을 확인할 수 있다.
|
||||
// 화면 읽기 기능에도 날짜와 전체 근무 이름 및 공휴일을 함께 전달한다.
|
||||
contentDescription = "${date.monthValue}월 ${date.dayOfMonth}일 ${ShiftNames.slotTitle(schedule, date)} ${lunar.orEmpty()} ${holiday.orEmpty()} 일정 ${events.size}개. ${Shift.REGULAR.title} 아래 이름: ${workNames.joinToString { it.name }}. 기념일: ${personalDays.joinToString { it.getJSONObject("data").getString("title") }}. 함께 당직: ${colleagues.joinToString { it.name }}"
|
||||
contentDescription = "${date.monthValue}월 ${date.dayOfMonth}일 ${schedule.shiftOn(date).title} ${ShiftNames.dutyLine(schedule, date)} ${lunar.orEmpty()} ${holiday.orEmpty()} 일정 ${events.size}개. ${Shift.REGULAR.title} 아래 이름: ${workNames.joinToString { it.name }}. 기념일: ${personalDays.joinToString { it.getJSONObject("data").getString("title") }}. 함께 당직: ${colleagues.joinToString { it.name }}"
|
||||
isFocusable = true
|
||||
setOnClickListener {
|
||||
selectedDate = date
|
||||
render()
|
||||
val titles = (events.map { it.getJSONObject("data").getString("title") } + personalDays.map { "기념일 · " + it.getJSONObject("data").getString("title") }).toTypedArray()
|
||||
AlertDialog.Builder(this@MainActivity).setTitle("${date.monthValue}월 ${date.dayOfMonth}일 ${ShiftNames.slotTitle(schedule, date)}")
|
||||
// 제목은 날짜와 근무, 그 아래 줄에 당직자(있을 때만).
|
||||
val dutyLine = ShiftNames.dutyLine(schedule, date)
|
||||
val heading = LinearLayout(this@MainActivity).apply { orientation = LinearLayout.VERTICAL; setPadding(dp(24), dp(20), dp(24), dp(4))
|
||||
addView(label("${date.monthValue}월 ${date.dayOfMonth}일 ${schedule.shiftOn(date).title}", 20f, ink, true))
|
||||
if (dutyLine.isNotEmpty()) addView(label(dutyLine, 15f, muted)) }
|
||||
AlertDialog.Builder(this@MainActivity).setCustomTitle(heading)
|
||||
.setItems(titles) { _, index -> if (index < events.size) planner.event(date, events[index]) else anniversaries.edit(personalDays[index - events.size]) }
|
||||
.setPositiveButton("일정 추가") { _, _ -> planner.event(date) }
|
||||
.setNeutralButton("날짜 상세") { _, _ ->
|
||||
AlertDialog.Builder(this@MainActivity).setTitle(date.toString()).setMessage("나: ${ShiftNames.slotTitle(schedule, date)}\n${workNames.joinToString { it.name }}\n${holiday ?: "공휴일이 아닙니다."}\n일정 ${events.size}개\n\n" + people.joinToString("\n") { "${it.name}: ${it.schedule.shiftOn(date).title}" }).setPositiveButton("확인", null).show()
|
||||
AlertDialog.Builder(this@MainActivity).setTitle(date.toString()).setMessage("나: ${schedule.shiftOn(date).title}\n${ShiftNames.dutyLine(schedule, date).let { if (it.isEmpty()) "" else it + "\n" }}${workNames.joinToString { it.name }}\n${holiday ?: "공휴일이 아닙니다."}\n일정 ${events.size}개\n\n" + people.joinToString("\n") { "${it.name}: ${it.schedule.shiftOn(date).title}" }).setPositiveButton("확인", null).show()
|
||||
}.setNegativeButton("닫기", null).show()
|
||||
}
|
||||
}
|
||||
@@ -306,7 +355,7 @@ class MainActivity : Activity() {
|
||||
val settings = card(content)
|
||||
settings.addView(label("나의 반복 근무", 18f, ink, true))
|
||||
space(settings, 8)
|
||||
settings.addView(label("주${schedule.workWeek}일제 · 토요일 ${if (schedule.workWeek == 5) "당직 외 휴무" else "기존 근무"}", 12f, muted))
|
||||
settings.addView(label("주${schedule.workWeek}일제 · 토요일 ${if (schedule.workWeek == 5) "빨간 날짜" else "파란 날짜"}", 12f, muted))
|
||||
settings.addView(label(schedule.pattern.joinToString(" → ") { it.title }, 14f, muted))
|
||||
space(settings, 4)
|
||||
settings.addView(label(if (configured) "첫째 날: ${schedule.anchor}" else "시작 날짜를 저장하면 위젯에도 반영됩니다.", 12f, muted))
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.content.Context
|
||||
|
||||
/**
|
||||
* 관리자 '공지'에서 켠 공지 띠. 홈페이지 맨 위와 같은 글을 앱 첫 화면 맨 위에 한 줄로 보인다.
|
||||
* 서버는 버전 확인(api/version)에 notice를 함께 준다. 마지막으로 받은 공지를 기기에 두어 연결이 없어도 보인다.
|
||||
* 예전 서버처럼 notice가 없는 응답이면 보관한 공지를 바꾸지 않는다. 회원 정보는 보내지 않는다.
|
||||
*/
|
||||
data class Notice(val text: String, val warn: Boolean) {
|
||||
val shown: Boolean get() = text.isNotEmpty()
|
||||
|
||||
companion object {
|
||||
const val MAX = 200
|
||||
private const val PREFS = "site_notice"
|
||||
val NONE = Notice("", false)
|
||||
|
||||
/** 서버 값을 화면에 쓸 모양으로 정리한다. 줄바꿈·제어 문자는 빈칸 하나로 바꾸고 200자까지 쓴다. */
|
||||
fun of(text: String?, tone: String?): Notice {
|
||||
val clean = text.orEmpty().replace(Regex("[\\p{Cc}\\s]+"), " ").trim().take(MAX)
|
||||
return if (clean.isEmpty()) NONE else Notice(clean, tone == "warn")
|
||||
}
|
||||
|
||||
fun load(context: Context): Notice {
|
||||
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
return of(prefs.getString("text", ""), if (prefs.getBoolean("warn", false)) "warn" else "info")
|
||||
}
|
||||
|
||||
/** 보관한 공지와 다를 때만 저장하고 true를 돌려준다. */
|
||||
fun save(context: Context, notice: Notice): Boolean {
|
||||
if (load(context) == notice) return false
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString("text", notice.text).putBoolean("warn", notice.warn).apply()
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,10 +60,9 @@ data class Schedule(val anchor: LocalDate, val pattern: List<Shift>, val workWee
|
||||
workPlan?.let{return it.shift(date,anchor,pattern,workWeek)}
|
||||
// 기준일 이전 날짜도 같은 반복에 속한다. 음수 나머지를 그대로 쓰면 배열 범위를 벗어난다.
|
||||
val index = Math.floorMod(ChronoUnit.DAYS.between(anchor, date), pattern.size.toLong()).toInt()
|
||||
val planned = pattern[index]
|
||||
// 토요일 휴무는 해당 날짜의 표시와 근무 여부만 바꾼다. 다음 날의 반복 위치를 미루지 않는다.
|
||||
// 주5일제여도 당직은 유지한다. 기존 자료는 주6일제로 읽어 저장한 근무 순서를 보존한다.
|
||||
return if (workWeek == 5 && date.dayOfWeek.value == 6 && planned != Shift.DUTY) Shift.REST else planned
|
||||
// 주5일제는 토요일 날짜만 빨간색으로 보인다(dateColor). 근무는 일요일처럼 원래 순서를 그대로 따른다.
|
||||
// 2026-11-26 사용자 지시: 토요일은 그냥 빨강, 휴무 글자를 넣지 않는다(0.6.0~0.15.7은 당직 외 근무를 휴무로 바꿨다).
|
||||
return pattern[index]
|
||||
}
|
||||
/**
|
||||
* 근무 순서 자리마다 넣은 이름(보통 그날 당직 서는 사람). 휴가·반차·병가·교육·휴무로 바꾼 날은 원래 자리 이름을 그대로 쓴다.
|
||||
|
||||
@@ -27,7 +27,18 @@ object ShiftNames {
|
||||
if (name.isNotEmpty() && mode == "name") return SlotView("", name, true)
|
||||
return SlotView(cellLabel(shift), if (mode == "both") name else "", false)
|
||||
}
|
||||
/** 오늘 카드·날짜 상세 같은 글 줄: 비번(김철수). 근무만 고르면 근무 이름만(웹 slotTitle과 같다). */
|
||||
/**
|
||||
* 그날 당직자 이름(근무 순서 이름)을 글 줄에 따로 붙일 때 쓴다. 근무만 고른 줄이나 이름이 없으면 빈 글자.
|
||||
* 2026-11-26 사용자 지시: 앱 안의 글(오늘 카드·날짜 창·위젯)은 '오늘은 비번(이정훈)'처럼 괄호로 붙이지 않고
|
||||
* '오늘은 비번' 아래에 '당직자 이정훈'으로 보인다. 웹 dutyName과 같다.
|
||||
*/
|
||||
fun dutyName(schedule: Schedule, date: java.time.LocalDate): String {
|
||||
val name = schedule.nameOn(date)
|
||||
return if (name.isEmpty() || schedule.nameModeOn(date) == "shift") "" else name
|
||||
}
|
||||
/** 당직자 줄: 당직자 이정훈. 이름이 없으면 빈 글자. */
|
||||
fun dutyLine(schedule: Schedule, date: java.time.LocalDate): String = dutyName(schedule, date).let { if (it.isEmpty()) "" else "당직자 $it" }
|
||||
/** 다른 달력(구독·기본 달력 반영) 제목에만 쓰는 한 줄: 비번(김철수). 근무만 고르면 근무 이름만. 앱 안의 글에는 쓰지 않는다(dutyLine). */
|
||||
fun slotTitle(schedule: Schedule, date: java.time.LocalDate): String {
|
||||
val title = schedule.shiftOn(date).title
|
||||
val name = schedule.nameOn(date)
|
||||
@@ -56,12 +67,13 @@ object ShiftNames {
|
||||
* 다른 달력(구글 등)으로 보내는 근무 제목. 기본은 앱 달력과 같게 보낸다(2026-11-25 사용자 지시).
|
||||
* 일반근무 글자 숨기기를 켜면 일반근무 날은 근무 글자를 빼고 이름만 보내며 이름도 없으면 빈 글자(보내지 않음)다. 서버 구독 제목과 같다.
|
||||
*/
|
||||
fun externalTitle(schedule: Schedule, date: java.time.LocalDate): String {
|
||||
fun externalTitle(schedule: Schedule, date: java.time.LocalDate, withName: Boolean = true): String {
|
||||
// withName이 거짓이면(연동 이름 칸을 켜지 않은 날) 이름만 고른 줄도 근무 글자만 보낸다.
|
||||
val name = if (withName) schedule.nameOn(date) else ""
|
||||
if (hideRegular && schedule.shiftOn(date) == Shift.REGULAR) {
|
||||
val name = schedule.nameOn(date)
|
||||
return if (name.isNotEmpty() && schedule.nameModeOn(date) != "shift") name else ""
|
||||
}
|
||||
return calendarTitle(schedule, date)
|
||||
return if (withName) calendarTitle(schedule, date) else schedule.shiftOn(date).title
|
||||
}
|
||||
/** 근무 순서 자리 이름 정리: 빈칸 정리, 10자까지, 제어 문자 거부. 모두 비면 빈 목록. */
|
||||
fun cleanSlotNames(raw: List<String>): List<String> {
|
||||
|
||||
@@ -36,11 +36,11 @@ class ShiftPatternEditor(context: Context, initial: List<Shift>, initialWorkWeek
|
||||
orientation = VERTICAL
|
||||
addView(caption("토요일 근무제"))
|
||||
workWeek.adapter = ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item,
|
||||
listOf("주5일제 · 토요일 당직만 근무", "주6일제 · 토요일 기존 근무"))
|
||||
listOf("주5일제 · 토요일 빨간 날짜", "주6일제 · 토요일 파란 날짜"))
|
||||
workWeek.contentDescription = "토요일 근무제"
|
||||
workWeek.setSelection(if (initialWorkWeek == 5) 0 else 1, false)
|
||||
addView(workWeek)
|
||||
addView(caption("주5일제는 토요일을 빨간색으로 표시하며 당직이 아니면 휴무입니다. 주6일제는 파란색으로 표시하고 원래 근무를 따릅니다."))
|
||||
addView(caption("주5일제는 토요일 날짜를 빨간색으로, 주6일제는 파란색으로 표시합니다. 근무는 두 방식 모두 원래 순서를 따릅니다."))
|
||||
addView(caption("근무 유형"))
|
||||
mode.adapter = ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item,
|
||||
listOf("직접 설정", "일당직 · 숫자로 입력") + (0 until templates.length()).map { templates.getJSONObject(it).getString("name") })
|
||||
|
||||
@@ -17,6 +17,7 @@ import javax.net.ssl.HttpsURLConnection
|
||||
* 홈페이지에 공개된 버전 정보를 읽고 새 앱이 있으면 설치 파일을 받을지 묻는다.
|
||||
* 회원 인증값과 개인 자료를 보내지 않는다. 동의하면 앱 안에서 내려받아 검증한다. 적용과 필요한 사용자 확인은 설치 관리자가 담당한다.
|
||||
* 창을 띄울 수 없는 상태에서는 공개 정보만 보관했다가 다음 실행 때 다시 확인한다.
|
||||
* 같은 응답의 공지 띠(notice)를 보관하고 바뀌면 첫 화면을 다시 그린다(0.16.0).
|
||||
*/
|
||||
object UpdateChecker {
|
||||
private val executor = Executors.newSingleThreadExecutor()
|
||||
@@ -58,6 +59,11 @@ object UpdateChecker {
|
||||
if (holidayRevision.isNotBlank() && holidayRevision != Holidays.revision(app)) {
|
||||
Holidays.refresh(app, force = true, changedOnly = true) { reference.get()?.let { screen -> screen.runOnUiThread { if (screen is MainActivity && !screen.isDestroyed) screen.render() } } }
|
||||
}
|
||||
result.optJSONObject("notice")?.let { item ->
|
||||
if (Notice.save(app, Notice.of(item.optString("text"), item.optString("tone")))) {
|
||||
reference.get()?.let { screen -> screen.runOnUiThread { if (screen is MainActivity && !screen.isDestroyed) screen.render() } }
|
||||
}
|
||||
}
|
||||
prefs.edit().putString("release", result.toString()).putLong("checkedAt", System.currentTimeMillis()).apply()
|
||||
reference.get()?.let { screen -> screen.runOnUiThread { if (force) prefs.edit().remove("deferred").remove("deferredUntil").apply(); prompt(screen, result); if (force && result.optLong("appVersionCode") <= AppUpdate.installed(app)) android.widget.Toast.makeText(screen, "현재 최신 버전입니다.", android.widget.Toast.LENGTH_SHORT).show() } }
|
||||
} catch (_: Exception) {
|
||||
|
||||
@@ -26,7 +26,8 @@ data class WorkPlan(val changes:List<Regime> = emptyList(),val overrides:Map<Loc
|
||||
overrides[date]?.let{return it.shift}
|
||||
val regime=regime(date);val days=regime?.pattern?:pattern;val base=regime?.anchor?:anchor
|
||||
val planned=days[Math.floorMod(ChronoUnit.DAYS.between(base,date),days.size.toLong()).toInt()]
|
||||
return if((regime?.workWeek?:workWeek)==5 && date.dayOfWeek.value==6 && planned!=Shift.DUTY)Shift.REST else planned
|
||||
// 주5일제는 토요일 날짜 색만 바꾼다. 근무는 원래 순서 그대로다(2026-11-26 사용자 지시).
|
||||
return planned
|
||||
}
|
||||
fun timing(shift:Shift):ShiftHours? = if(!shift.working)null else hours[shift]?:when(shift) {
|
||||
Shift.DUTY->ShiftHours(LocalTime.of(9,0),1440)
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import java.time.LocalDate
|
||||
import java.time.YearMonth
|
||||
|
||||
class DayRolloverTest {
|
||||
private val nov30 = LocalDate.of(2026, 11, 30)
|
||||
private val dec1 = LocalDate.of(2026, 12, 1)
|
||||
|
||||
@Test
|
||||
fun monthAndSelectedDayFollowNewToday() {
|
||||
val after = DayRollover.follow(DayRollover.View(YearMonth.of(2026, 11), nov30, nov30), dec1)
|
||||
assertEquals(DayRollover.View(YearMonth.of(2026, 12), dec1, dec1), after)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun openedLongAgoStillMovesToThisMonth() {
|
||||
val nov26 = LocalDate.of(2026, 11, 26)
|
||||
val after = DayRollover.follow(DayRollover.View(YearMonth.of(2026, 11), nov26, nov26), dec1)
|
||||
assertEquals(YearMonth.of(2026, 12), after.month)
|
||||
assertEquals(dec1, after.selected)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun movedMonthAndPickedDayStay() {
|
||||
val picked = LocalDate.of(2027, 1, 15)
|
||||
val after = DayRollover.follow(DayRollover.View(YearMonth.of(2027, 1), picked, nov30), dec1)
|
||||
assertEquals(YearMonth.of(2027, 1), after.month)
|
||||
assertEquals(picked, after.selected)
|
||||
assertEquals(dec1, after.shownDay)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sameDayChangesNothing() {
|
||||
val view = DayRollover.View(YearMonth.of(2026, 10), LocalDate.of(2026, 10, 3), dec1)
|
||||
assertEquals(view, DayRollover.follow(view, dec1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun widgetMonthDropsOldNavigation() {
|
||||
val dec = YearMonth.of(2026, 12)
|
||||
assertEquals(dec, DayRollover.widgetMonth(null, null, dec))
|
||||
assertEquals(dec, DayRollover.widgetMonth("2026-11", null, dec))
|
||||
assertEquals(dec, DayRollover.widgetMonth("2026-11", "2026-11", dec))
|
||||
assertEquals(dec, DayRollover.widgetMonth("2027-02", "2026-11", dec))
|
||||
assertEquals(YearMonth.of(2027, 2), DayRollover.widgetMonth("2027-02", "2026-12", dec))
|
||||
assertEquals(dec, DayRollover.widgetMonth("망가진 값", "2026-12", dec))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class NoticeTest {
|
||||
@Test
|
||||
fun emptyOrBlankMeansNoNotice() {
|
||||
assertFalse(Notice.of(null, "warn").shown)
|
||||
assertFalse(Notice.of(" \n\t ", "info").shown)
|
||||
assertEquals(Notice.NONE, Notice.of("", "warn"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun toneAndTextAreCleaned() {
|
||||
val notice = Notice.of(" 12월 3일 점검\n안내\u0007 ", "warn")
|
||||
assertTrue(notice.shown)
|
||||
assertTrue(notice.warn)
|
||||
assertEquals("12월 3일 점검 안내", notice.text)
|
||||
assertFalse(Notice.of("안내", "info").warn)
|
||||
assertFalse(Notice.of("안내", "red").warn)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun longTextIsCut() {
|
||||
assertEquals(Notice.MAX, Notice.of("가".repeat(500), "info").text.length)
|
||||
}
|
||||
}
|
||||
@@ -87,16 +87,16 @@ class ScheduleTest {
|
||||
assertTrue(Shift.EVENING.working)
|
||||
}
|
||||
@Test(expected = IllegalArgumentException::class) fun oversizedCycleRejected() { Schedule(anchor, List(367) { Shift.DAY }) }
|
||||
@Test fun fiveDaySaturdayKeepsDutyAndRestsOtherShifts() {
|
||||
@Test fun fiveDaySaturdayKeepsOriginalShift() {
|
||||
// 2026-11-26 사용자 지시: 주5일제 토요일은 날짜만 빨간색이고 휴무로 바꾸지 않는다.
|
||||
val saturday = LocalDate.of(2026, 11, 21)
|
||||
Shift.entries.forEach { shift ->
|
||||
assertEquals(if (shift == Shift.DUTY) Shift.DUTY else Shift.REST,
|
||||
Schedule(saturday, listOf(shift), 5).shiftOn(saturday))
|
||||
assertEquals(shift, Schedule(saturday, listOf(shift), 5).shiftOn(saturday))
|
||||
}
|
||||
}
|
||||
@Test fun saturdayRestDoesNotMoveFollowingRotation() {
|
||||
@Test fun fiveDaySaturdayDoesNotMoveFollowingRotation() {
|
||||
val schedule = Schedule(anchor, listOf(Shift.DUTY, Shift.REGULAR, Shift.NIGHT), 5)
|
||||
assertEquals(Shift.REST, schedule.shiftOn(anchor.plusDays(1)))
|
||||
assertEquals(Shift.REGULAR, schedule.shiftOn(anchor.plusDays(1)))
|
||||
assertEquals(Shift.NIGHT, schedule.shiftOn(anchor.plusDays(2)))
|
||||
assertEquals(Shift.DUTY, schedule.shiftOn(anchor.plusDays(3)))
|
||||
}
|
||||
|
||||
@@ -71,6 +71,41 @@ class SlotNamesTest {
|
||||
assertEquals("", ShiftNames.externalTitle(base.copy(names = emptyList()), regular))
|
||||
}
|
||||
|
||||
@Test fun dutyLineIsSeparateFromShift() {
|
||||
// 2026-11-26 사용자 지시: 앱 안의 글은 '오늘은 비번(이정훈)'이 아니라 '오늘은 비번' 아래에 '당직자 이정훈'.
|
||||
val off = LocalDate.of(2026, 11, 21); val duty = LocalDate.of(2026, 11, 20); val leave = LocalDate.of(2026, 11, 22)
|
||||
assertEquals("김철수", ShiftNames.dutyName(base, off))
|
||||
assertEquals("당직자 김철수", ShiftNames.dutyLine(base, off))
|
||||
assertEquals("", ShiftNames.dutyLine(base, duty))
|
||||
assertEquals("당직자 이영희", ShiftNames.dutyLine(base, leave))
|
||||
ShiftNames.nameDisplay = "name"
|
||||
assertEquals("당직자 김철수", ShiftNames.dutyLine(base, off))
|
||||
ShiftNames.nameDisplay = "shift"
|
||||
assertEquals("", ShiftNames.dutyLine(base, off))
|
||||
assertEquals("", ShiftNames.dutyLine(base.copy(names = emptyList()), off))
|
||||
}
|
||||
|
||||
@Test fun externalNamesOffByDefaultAndPerKind() {
|
||||
// 2026-11-26 사용자 지시: 연동 달력은 기본이 이름 표기 없음이고 비번·휴무·연차 등 날 종류마다 체크로 켠다.
|
||||
val rows = base.copy(names = listOf("", "김철수", "이영희"), nameModes = listOf("", "both", "name"))
|
||||
val regular = LocalDate.of(2026, 11, 19); val off = LocalDate.of(2026, 11, 21); val leave = LocalDate.of(2026, 11, 22)
|
||||
assertEquals("비번", ShiftNames.externalTitle(rows, off, false))
|
||||
assertEquals("일반근무", ShiftNames.externalTitle(rows, regular, false))
|
||||
assertEquals("연차·휴가", ShiftNames.externalTitle(rows, leave, false))
|
||||
assertEquals("비번(김철수)", ShiftNames.externalTitle(rows, off, true))
|
||||
assertEquals("이영희", ShiftNames.externalTitle(rows, regular, true))
|
||||
ShiftNames.hideRegular = true
|
||||
assertEquals("", ShiftNames.externalTitle(rows, regular, false))
|
||||
// 날 종류마다 따로 켠다. 기본은 모두 꺼짐.
|
||||
val none = MirrorNames()
|
||||
assertFalse(Shift.entries.any { none.slot(it) } || none.rules)
|
||||
val offOnly = MirrorNames(off = true)
|
||||
assertEquals(listOf(Shift.OFF), Shift.entries.filter { offOnly.slot(it) })
|
||||
assertEquals(listOf(Shift.REST), Shift.entries.filter { MirrorNames(rest = true).slot(it) })
|
||||
assertEquals(Shift.entries.filter { it.away && it != Shift.REST }, Shift.entries.filter { MirrorNames(away = true).slot(it) })
|
||||
assertEquals(listOf(Shift.DUTY, Shift.REGULAR, Shift.DAY, Shift.EVENING, Shift.NIGHT), Shift.entries.filter { MirrorNames(work = true).slot(it) })
|
||||
}
|
||||
|
||||
@Test fun leaveDaysKeepTheSlotName() {
|
||||
// 2026-11-26 사용자 지시: 연차를 써도 그날 당직자는 그대로라 이름이 보여야 한다.
|
||||
val day = LocalDate.of(2026, 11, 22)
|
||||
|
||||
@@ -15,7 +15,7 @@ class WorkPlanTest {
|
||||
}
|
||||
@Test fun overrideWinsEvenOnFiveDaySaturday(){
|
||||
val schedule=Schedule(date("2026-12-05"),listOf(Shift.REGULAR),5,workPlan=WorkPlan(overrides=mapOf(date("2026-12-05") to DayOverride(Shift.TRAINING))))
|
||||
assertEquals(Shift.TRAINING,schedule.shiftOn(date("2026-12-05")));assertEquals(Shift.REST,schedule.shiftOn(date("2026-12-12")))
|
||||
assertEquals(Shift.TRAINING,schedule.shiftOn(date("2026-12-05")));assertEquals(Shift.REGULAR,schedule.shiftOn(date("2026-12-12")))
|
||||
}
|
||||
@Test fun overnightAndBreaksHaveDistinctMeaning(){
|
||||
val plan=WorkPlan(hours=mapOf(Shift.NIGHT to ShiftHours(LocalTime.of(22,0),540,60)))
|
||||
|
||||
+19
-1
@@ -72,6 +72,10 @@
|
||||
|
||||
다른 달력 연동의 `skipRegular`(0.15.5)는 일반근무 날을 이름까지 통째로 보내지 않는 선택이다. 구독은 `calendar_feeds.options`에 두고(없으면 끔) `action: update`로 주소를 바꾸지 않고 항목만 고친다. 앱 기본 달력 반영은 기기 설정(`calendar_mirror`의 `skipRegular`)이다.
|
||||
|
||||
근무 순서 이름을 다른 달력에 보낼지는 0.15.8부터 날 종류마다 고른다(사용자 지시 2026-11-26: 연동 달력은 이름 표기 없음이 기본). 구독 항목 `nameWork` · `nameOff` · `nameRest` · `nameAway`(값이 없으면 끔)와 앱 `calendar_mirror`의 같은 이름 키 및 `nameRules`(일반근무 아래 이름, 구독의 `names`와 같은 뜻)다. 날의 종류는 그날 근무로 정한다(`calendar_export.name_kind` · `MirrorNames.slot`): 비번 · 휴무 · 휴가·반차·병가·교육(`AWAY`에서 휴무를 뺀 것) · 그 밖의 근무(당직·일반근무·주간·오후·야간). 끈 날은 이름만 고른 줄도 근무 글자로 보낸다(`ShiftNames.externalTitle(…, withName=false)`).
|
||||
|
||||
주5일제(`workWeek` 5)는 0.15.8부터 토요일 날짜 색만 바꾼다(`dateColor`). 0.6.0~0.15.7은 토요일에 당직이 아닌 근무를 휴무(`REST`)로 바꿨는데 사용자가 지시한 적 없는 동작이라 뺐다(사용자 지시 2026-11-26: 토요일은 그냥 빨강). 서버 `work_plan.shift` · 웹 `WorkPlan.shift` · 앱 `Schedule.shiftOn` · `WorkPlan.shift`가 같다.
|
||||
|
||||
구버전 앱과 열려 있던 옛 웹은 이 두 필드 없이 개인 설정을 저장한다. 필드가 없으면 서버가 저장된 값을 보존한다(`preserve_regular_name`). 반복 근무 항목으로 복제하지 않으며 소속 공유 목록에도 넣지 않는다.
|
||||
|
||||
앱의 `ShiftNames.regular`와 `Shift.title`에 있는 이름 바꾸기 장치는 남아 있지만 `ScheduleStore.load`가 늘 빈 값으로 맞춰 기본 이름을 쓴다. 웹의 `applyShiftNames`도 빈 이름으로 기본 이름(일반근무)을 쓴다. 관리자 기본값 `defaultRegularName`은 뺐고 이미 저장된 값은 읽지 않는다.
|
||||
@@ -80,7 +84,7 @@
|
||||
|
||||
근무표(`rotation`)의 `names`는 순서(`pattern`)와 같은 길이의 문자열 목록이다. 자리마다 그날 당직 서는 사람 이름을 넣고 당직 자리와 빈 자리는 빈 글자다. 모두 비면 빈 목록으로 저장한다. 서버는 길이와 10자 및 제어 문자를 검사한다(`validate_rotation_names`). 구버전 앱이 이름 없이 근무표를 저장하면 순서 길이가 같을 때 이름을 보존하고 다르면 버린다(`preserve_rotation_names`). 소속 공유(`shared_rotation`)에는 넣지 않는다.
|
||||
|
||||
날짜의 이름은 `name_on`(서버) · `WorkPlan.nameOn`(웹) · `Schedule.nameOn`(앱)이 같은 규칙으로 구한다. 날짜별 변경이 휴가·반차·병가·교육·휴무(`AWAY` · `WorkPlan.awayOn` · `Shift.away`)면 원래 자리 이름을 그대로 쓰고 표시가 이름만(name)이어도 둘 다(both)로 바꿔 근무 글자를 같이 보인다(0.15.6, 사용자 지시 2026-11-26: 연차를 써도 그날 당직자는 그대로다). 당직·비번·일반근무·주간·오후·야간으로 바꾼 날은 그날 당직자가 달라질 수 있어 빈 값이다. 근무제 변경이 적용되는 날은 그 제도의 순서가 기본 순서와 같을 때만 기본 순서의 이름을 쓴다. 표시 방법은 0.15.4부터 이름 줄마다 고른다. 근무표의 `nameModes`가 순서와 같은 길이의 목록이고 값은 both · name · shift 또는 빈 글자다. 이름이 모두 비거나 값이 모두 빈 글자면 빈 목록으로 저장한다(`validate_rotation_name_modes`). 빈 글자나 목록이 없으면 예전 공통 선택인 개인 설정의 `nameDisplay`(없으면 both)를 쓴다. 날짜의 표시는 `name_mode_on`(서버) · `WorkPlan.nameModeOn`(웹) · `Schedule.nameModeOn`(앱)이 이름과 같은 자리 계산(`slot_index` · `slotIndex`)으로 구한다. 0.15.0~0.15.3 앱은 `nameModes` 없이 근무표를 저장하므로 이름이 있고 순서 길이가 같으면 서버가 저장된 값을 보존한다(`preserve_rotation_names`). 소속 공유에는 넣지 않는다. 사용자가 공통 선택 하나가 아니라 이름 줄마다 고르라고 지시했다(2026-11-25). 칸은 `slotView`, 글 줄은 `slotTitle`(이름이 있으면 근무(이름)), 다른 달력 제목은 `calendarTitle`(이름만이면 이름만)을 쓴다. 입력은 당직 기초 설정과 따로 된 **근무 순서 이름** 창에서만 받는다. 창의 줄 이름은 내 당직 기준 상대 위치(`relativeLabel`: 당직 다음 날부터 +1 · +2 …)다. 다음 당직 전날의 (-1) 표시는 헷갈려서 넣지 않는다.
|
||||
날짜의 이름은 `name_on`(서버) · `WorkPlan.nameOn`(웹) · `Schedule.nameOn`(앱)이 같은 규칙으로 구한다. 날짜별 변경이 휴가·반차·병가·교육·휴무(`AWAY` · `WorkPlan.awayOn` · `Shift.away`)면 원래 자리 이름을 그대로 쓰고 표시가 이름만(name)이어도 둘 다(both)로 바꿔 근무 글자를 같이 보인다(0.15.6, 사용자 지시 2026-11-26: 연차를 써도 그날 당직자는 그대로다). 당직·비번·일반근무·주간·오후·야간으로 바꾼 날은 그날 당직자가 달라질 수 있어 빈 값이다. 근무제 변경이 적용되는 날은 그 제도의 순서가 기본 순서와 같을 때만 기본 순서의 이름을 쓴다. 표시 방법은 0.15.4부터 이름 줄마다 고른다. 근무표의 `nameModes`가 순서와 같은 길이의 목록이고 값은 both · name · shift 또는 빈 글자다. 이름이 모두 비거나 값이 모두 빈 글자면 빈 목록으로 저장한다(`validate_rotation_name_modes`). 빈 글자나 목록이 없으면 예전 공통 선택인 개인 설정의 `nameDisplay`(없으면 both)를 쓴다. 날짜의 표시는 `name_mode_on`(서버) · `WorkPlan.nameModeOn`(웹) · `Schedule.nameModeOn`(앱)이 이름과 같은 자리 계산(`slot_index` · `slotIndex`)으로 구한다. 0.15.0~0.15.3 앱은 `nameModes` 없이 근무표를 저장하므로 이름이 있고 순서 길이가 같으면 서버가 저장된 값을 보존한다(`preserve_rotation_names`). 소속 공유에는 넣지 않는다. 사용자가 공통 선택 하나가 아니라 이름 줄마다 고르라고 지시했다(2026-11-25). 칸은 `slotView`를 쓴다. 앱·웹 안의 글 줄(오늘 카드·날짜 창·위젯)은 근무 글자와 당직자 줄(`ShiftNames.dutyLine` · 웹 `dutyLine`: 당직자 김철수)을 따로 보인다(0.15.9, 사용자 지시 2026-11-26: '오늘은 비번(이정훈)'처럼 괄호로 붙이지 말고 아래에 당직자 이름). 괄호 모양 `slotTitle`(비번(김철수))은 다른 달력 제목 `calendarTitle`(이름만이면 이름만)에만 남는다. 입력은 당직 기초 설정과 따로 된 **근무 순서 이름** 창에서만 받는다. 창의 줄 이름은 내 당직 기준 상대 위치(`relativeLabel`: 당직 다음 날부터 +1 · +2 …)다. 다음 당직 전날의 (-1) 표시는 헷갈려서 넣지 않는다.
|
||||
|
||||
## 이름 표시와 기본 달력 및 구독
|
||||
|
||||
@@ -113,3 +117,17 @@ PlanExportActivity는 출력 전용 사본을 만들고 시스템 문서 선택
|
||||
ANNUAL_LEAVE와 MONTHLY_LEAVE 및 VACATION과 OFFICIAL_LEAVE 및 FAMILY_LEAVE를 새 근무 값으로 추가했다. 기존 LEAVE는 그대로 읽고 쓴다. Shift.working과 웹 WorkPlan.working 및 서버 WORKING에서 휴가를 근무시간 합계와 시간 겹침 및 근무 중인 소속 회원 표시에서 제외한다. 날짜별 override가 주5일제 토요일보다 우선하는 기존 규칙을 유지한다. calendar_export의 표시 이름도 함께 확장했다. DB 구조 변경과 기존 항목 일괄 변환은 없다.
|
||||
|
||||
설치 결과 STATUS_FAILURE_BLOCKED는 blocked 상태로 처리한다. 설치 완료로 표시하지 않고 같은 파일을 자동 재시도하지 않는다. 이 분기는 보안 검사나 기기 정책의 차단을 알리는 것이며 구체적인 Play 프로텍트 탐지 이유를 알아내거나 차단을 해제하지 않는다. 기존 PackageInstaller 사용과 동의한 업데이트 다운로드 및 해시·서명 검증은 유지한다.
|
||||
|
||||
## 공지 띠 · 0.16.0
|
||||
|
||||
공지 띠는 홈페이지 설정의 `noticeOn`·`noticeTone`·`noticeText`다. 서버 `site_admin.notice`가 켜진 공지의 글과 종류(info·warn)를 만들고 `GET /calendar/api/version`의 `notice`로 준다. 꺼져 있거나 글이 없으면 `text`가 빈 글자다. 웹 홈페이지는 지금처럼 `GET /calendar/api/site`로 그린다.
|
||||
|
||||
앱은 첫 화면을 열 때마다 하는 버전 확인(`UpdateChecker`) 응답에서 `notice`를 읽어 `Notice`로 정리하고 `site_notice` 기기 설정에 둔다. 바뀌었을 때만 첫 화면을 다시 그린다. 응답에 `notice`가 없으면(예전 서버) 보관한 공지를 그대로 둔다. 회원 인증값이나 개인 자료는 보내지 않는다.
|
||||
|
||||
## 날짜 넘김 · 0.16.1
|
||||
|
||||
앱 첫 화면은 보던 달(`month`)과 고른 날(`selectedDate`) 및 그 화면이 오늘로 삼은 날(`shownDay`)을 함께 둔다. 화면이 다시 보일 때와 화면이 보이는 동안의 시간 알림(1분마다·날짜·시각·시간대 변경)에서 날짜가 바뀌었으면 `DayRollover.follow`로 보던 달이 그 전 오늘의 달일 때만 이번 달로 옮기고 고른 날이 그 전 오늘일 때만 오늘로 옮긴다. 화면 상태를 복원할 때도 `shownDay`를 함께 저장한다.
|
||||
|
||||
달력 위젯은 달을 옮길 때 옮긴 달(`month_위젯번호`)과 옮긴 때의 달(`monthBase_위젯번호`)을 같이 둔다. 이번 달로 돌아오면 둘 다 지운다. `DayRollover.widgetMonth`는 옮긴 때의 달이 지금 달과 다르거나 없으면(예전 버전 저장) 지금 달을 보인다.
|
||||
|
||||
웹(`app.js`)은 `shownDay`를 두고 30초마다와 화면이 다시 보일 때 같은 규칙으로 옮긴다.
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# 새 버전 배포와 복구
|
||||
|
||||
제작자 블리어 (이창현) · 0.15.7
|
||||
제작자 블리어 (이창현) · 0.16.1
|
||||
|
||||
## 배포 위치
|
||||
|
||||
|
||||
+11
-5
@@ -1,6 +1,6 @@
|
||||
# 당직근무 설치와 사용법
|
||||
|
||||
제작자 블리어 (이창현) · 0.15.7
|
||||
제작자 블리어 (이창현) · 0.16.1
|
||||
|
||||
## 설치와 처음 설정
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
2당직은 당직·비번을 반복합니다. 3당직의 기본값은 당직·비번·일반근무입니다. 2~366의 숫자를 입력할 수 있고 나머지 날의 근무를 수정할 수 있습니다. 주간 상근과 여러 조의 주야 교대 예시도 제공합니다. 회사별 근무 규칙이 다르므로 예시를 고른 뒤 실제 날짜와 대조하세요.
|
||||
|
||||
주 5일제를 고르면 토요일의 일반근무는 휴무로 계산합니다. 주 6일제의 토요일은 기존 근무 규칙을 따릅니다. 당직 날짜는 유지합니다. 옵션의 **당직일 평일색**은 주말과 공휴일에 걸린 당직 날짜 숫자를 평일색으로 보여 줍니다. **비번 빨간색**은 비번 날짜를 빨간색으로 표시합니다. 두 옵션은 달력 색상에 대한 설정이며 실제 반복 순서를 바꾸지 않습니다.
|
||||
주 5일제를 고르면 토요일 날짜가 빨간색, 주 6일제는 파란색으로 보입니다. 근무는 두 방식 모두 원래 순서를 그대로 따르며 토요일에 휴무 글자를 따로 넣지 않습니다. 옵션의 **당직일 평일색**은 주말과 공휴일에 걸린 당직 날짜 숫자를 평일색으로 보여 줍니다. **비번 빨간색**은 비번 날짜를 빨간색으로 표시합니다. 두 옵션은 달력 색상에 대한 설정이며 실제 반복 순서를 바꾸지 않습니다.
|
||||
|
||||
## 주 시작 요일
|
||||
|
||||
@@ -104,7 +104,9 @@
|
||||
|
||||
근무표와 개인 일정 및 기념일 중 반영할 항목을 고릅니다. 처음에는 근무표만 선택합니다. 개인 일정과 기념일을 고르면 메모도 포함됩니다. Google 등 계정 달력은 해당 계정의 공유 설정이 적용됩니다. 같은 계정 달력에는 한 휴대폰에서만 자동 반영을 켜야 기기별 사본이 중복되지 않습니다.
|
||||
|
||||
**일반근무 날 빼기**(0.15.5부터)를 켜면 일반근무 날은 이름까지 통째로 보내지 않습니다. 끄면 앱 달력과 같게 보냅니다(근무 순서 이름 줄마다 고른 표시와 일반근무 글자 숨기기를 따름). 이미 켜 둔 자동 반영은 **반영 항목 변경**에서 바꿉니다.
|
||||
**일반근무 날 빼기**(0.15.5부터)를 켜면 일반근무 날은 통째로 보내지 않습니다. 끄면 앱 달력과 같게 보냅니다(일반근무 글자 숨기기를 따름). 이미 켜 둔 자동 반영은 **반영 항목 변경**에서 바꿉니다.
|
||||
|
||||
**근무 순서 이름 함께 보내기**(0.15.8부터)는 날 종류마다 체크합니다. 당직·근무 날 · 비번 날 · 휴무 날 · 연차·휴가·반차·병가·교육 날 가운데 체크한 날에만 비번(김철수)처럼 이름이 붙습니다. 기본은 모두 꺼짐이라 이름 없이 근무 글자만 보냅니다. 일반근무 아래 이름도 따로 체크합니다(기본 꺼짐).
|
||||
|
||||
지난 30일부터 앞으로 366일까지 반영합니다. 앱에서 저장하거나 서버 변경을 받으면 사본을 갱신하며 하루마다 표시 기간도 갱신합니다. 휴대폰 절전 설정에 따라 예약 작업은 늦어질 수 있습니다. 바로 맞추려면 **지금 다시 반영**을 누르세요. 시간 일정은 한국 시간 기준입니다.
|
||||
|
||||
@@ -114,7 +116,7 @@
|
||||
|
||||
## 다른 달력과 구독 주소 공유
|
||||
|
||||
웹에서 로그인하고 **옵션 → 달력 연동·공유**를 엽니다. 근무표와 이름 표시 및 개인 일정과 기념일 및 메모 중 공유할 항목을 고른 뒤 **구독 주소 만들기**를 누릅니다. 기본 선택은 근무표뿐입니다. 이 주소를 아는 사람은 선택한 항목을 읽을 수 있으므로 필요한 범위만 선택하세요. **일반근무 날 빼기**를 켜면 일반근무 날은 이름까지 보내지 않고 끄면 앱 달력과 같게 보냅니다. 이미 만든 주소는 **항목만 바꾸기(주소 그대로)**로 주소를 바꾸지 않고 항목만 고칠 수 있습니다.
|
||||
웹에서 로그인하고 **옵션 → 달력 연동·공유**를 엽니다. 근무표와 이름 표시 및 개인 일정과 기념일 및 메모 중 공유할 항목을 고른 뒤 **구독 주소 만들기**를 누릅니다. 기본 선택은 근무표뿐입니다. 이 주소를 아는 사람은 선택한 항목을 읽을 수 있으므로 필요한 범위만 선택하세요. **일반근무 날 빼기**를 켜면 일반근무 날은 보내지 않고 끄면 앱 달력과 같게 보냅니다. **근무 순서 이름 함께 보내기**는 날 종류마다 체크하며 기본은 이름 없음입니다(0.15.8부터). 이미 만든 주소는 **항목만 바꾸기(주소 그대로)**로 주소를 바꾸지 않고 항목만 고칠 수 있습니다.
|
||||
|
||||
발급된 주소를 외부 달력의 **URL로 추가** 또는 **웹에서 구독**에 붙여 넣습니다. 외부 달력의 자동 갱신 간격은 그 서비스가 결정하며 즉시 반영을 보장하지 않습니다. 구글 캘린더는 보통 하루에 몇 번만 주소를 다시 읽어서 당직근무에서 바꾼 내용이 몇 시간에서 하루쯤 늦게 보일 수 있습니다. 바로 반영되어야 하면 앱의 **기본 달력 자동 반영**으로 구글 계정 달력을 고르세요(구독 주소와 함께 쓰면 같은 일정이 두 번 보입니다). [Outlook의 웹 구독 안내](https://support.microsoft.com/en-us/outlook/import-or-subscribe-to-a-calendar-in-outlook-com-or-outlook-on-the-web)를 참고할 수 있습니다. 앱에서는 달력 연동 메뉴의 구독 주소 항목으로 홈페이지를 열 수 있습니다.
|
||||
|
||||
@@ -127,7 +129,7 @@
|
||||
|
||||
**옵션 → 근무 순서 이름**(웹은 **옵션 → 근무 순서 이름**)을 열면 당직이 아닌 순서 자리가 차례로 나옵니다(내 당직 기준 예: +1 · 비번, +2 · 일반근무, +3 · 일반근무). 각 자리에 그날 당직 서는 사람 이름을 10자까지 적습니다. 근무 종류는 글자로만 보이고 여기서는 바뀌지 않습니다. 근무 종류와 반복 일수는 **당직 기초 설정**에서 고칩니다.
|
||||
|
||||
이름 칸 옆에서 그 이름을 달력에 어떻게 보일지 줄마다 따로 고릅니다(0.15.4부터). **둘 다**면 근무 아래에 이름이 한 줄 더 보이고 **이름만**이면 근무 자리에 이름이 보이며 **근무만**이면 이름을 넣어 두어도 근무만 보입니다. 예를 들어 +1 · 비번 줄은 이름만, +2 · 일반근무 줄은 둘 다로 고를 수 있습니다. 오늘 카드와 날짜 상세에는 근무만이 아니면 "비번(김철수)"처럼 함께 보입니다. 이름이 없는 날은 근무가 보입니다. 연차·반차·휴가·병가·교육·휴무로 바꾼 날에도 그날 이름이 "연차(김철수)"처럼 같이 보이고(0.15.6부터) 이름만 고른 줄도 이런 날은 근무 글자를 같이 보입니다. 당직이나 일반근무처럼 다른 근무로 바꾼 날은 그날 당직자가 달라질 수 있어 근무만 보입니다. 당직 기초 설정에서 반복 일수를 바꾸면 자리가 달라지므로 이름을 다시 적어야 합니다. 근무 종류만 바꾸면 이름은 남습니다.
|
||||
이름 칸 옆에서 그 이름을 달력에 어떻게 보일지 줄마다 따로 고릅니다(0.15.4부터). **둘 다**면 근무 아래에 이름이 한 줄 더 보이고 **이름만**이면 근무 자리에 이름이 보이며 **근무만**이면 이름을 넣어 두어도 근무만 보입니다. 예를 들어 +1 · 비번 줄은 이름만, +2 · 일반근무 줄은 둘 다로 고를 수 있습니다. 오늘 카드와 날짜 창 및 위젯의 글에는 근무만이 아니면 근무 아래 줄(위젯은 같은 줄 뒤)에 "당직자 김철수"처럼 따로 보입니다(0.15.9부터, 괄호로 붙이지 않음). 이름이 없는 날은 근무가 보입니다. 연차·반차·휴가·병가·교육·휴무로 바꾼 날에도 그날 이름이 "연차(김철수)"처럼 같이 보이고(0.15.6부터) 이름만 고른 줄도 이런 날은 근무 글자를 같이 보입니다. 당직이나 일반근무처럼 다른 근무로 바꾼 날은 그날 당직자가 달라질 수 있어 근무만 보입니다. 당직 기초 설정에서 반복 일수를 바꾸면 자리가 달라지므로 이름을 다시 적어야 합니다. 근무 종류만 바꾸면 이름은 남습니다.
|
||||
|
||||
회원 연결 중이면 이름과 줄마다 고른 표시는 근무표와 함께 서버에 보관되고 소속 사람들에게는 나가지 않습니다. 웹은 로그인하지 않아도 이 기기에서 고를 수 있습니다. 다른 달력 반영과 구독 제목도 줄마다 고른 방법을 따릅니다. 앱은 0.15.0부터 이름을 쓰고 0.15.4부터 줄마다 고릅니다. 0.15.0~0.15.3에서 고른 공통 선택은 줄마다 다시 고르기 전까지 그대로 쓰입니다.
|
||||
|
||||
@@ -135,6 +137,10 @@
|
||||
|
||||
홈페이지 위쪽 메뉴의 **달력 연동 안내**(https://duty.itosm.co.kr/calendar/guide)에 구독 주소 만들기와 안드로이드 앱의 기본 달력 반영 및 구글 캘린더·삼성 캘린더·아이폰·아웃룩·파일로 넣기를 차례로 적었습니다. 앱에서는 **옵션 → 달력 연동·공유 → 구글·삼성·아이폰 연동 방법 보기**로 같은 페이지를 엽니다. 삼성 캘린더는 구독 주소를 직접 넣는 메뉴가 없어서 앱의 기본 달력 반영이나 구글 캘린더를 거쳐 씁니다.
|
||||
|
||||
## 공지
|
||||
|
||||
운영진이 공지 띠를 켜면 홈페이지 맨 위와 앱 첫 화면 맨 위(0.16.0부터)에 한 줄로 보입니다. 파란 점은 안내이고 주황 점은 주의입니다. 앱은 열 때마다 새 공지를 확인하고 연결이 없을 때는 마지막으로 받은 공지를 보여 줍니다. 운영진이 공지 띠를 끄면 다음에 앱을 열 때 사라집니다. 긴 소식은 게시판의 공지사항에 올라갑니다.
|
||||
|
||||
## 게시판
|
||||
|
||||
홈페이지 위쪽 메뉴의 **게시판**에 공지사항과 자유게시판 및 질문·건의가 있습니다. 글은 누구나 읽고 회원 로그인 후 글과 댓글을 씁니다. 공지사항은 운영진만 씁니다. 내가 쓴 글과 댓글은 고치거나 지울 수 있습니다. 글자만 올릴 수 있고 https:// 주소는 누르면 열리는 링크가 됩니다. 개인 연락처나 다른 사람의 근무표는 올리지 마세요.
|
||||
|
||||
+9
-1
@@ -1,6 +1,6 @@
|
||||
# Android Studio로 당직근무 만들기
|
||||
|
||||
제작자 블리어 (이창현) · 0.15.7
|
||||
제작자 블리어 (이창현) · 0.16.1
|
||||
|
||||
## 준비할 환경
|
||||
|
||||
@@ -197,3 +197,11 @@ PlanExportActivity는 출력 전용 사본을 만들고 시스템 문서 선택
|
||||
ANNUAL_LEAVE와 MONTHLY_LEAVE 및 VACATION과 OFFICIAL_LEAVE 및 FAMILY_LEAVE를 새 근무 값으로 추가했다. 기존 LEAVE는 그대로 읽고 쓴다. Shift.working과 웹 WorkPlan.working 및 서버 WORKING에서 휴가를 근무시간 합계와 시간 겹침 및 근무 중인 소속 회원 표시에서 제외한다. 날짜별 override가 주5일제 토요일보다 우선하는 기존 규칙을 유지한다. calendar_export의 표시 이름도 함께 확장했다. DB 구조 변경과 기존 항목 일괄 변환은 없다.
|
||||
|
||||
설치 결과 STATUS_FAILURE_BLOCKED는 blocked 상태로 처리한다. 설치 완료로 표시하지 않고 같은 파일을 자동 재시도하지 않는다. 이 분기는 보안 검사나 기기 정책의 차단을 알리는 것이며 구체적인 Play 프로텍트 탐지 이유를 알아내거나 차단을 해제하지 않는다. 기존 PackageInstaller 사용과 동의한 업데이트 다운로드 및 해시·서명 검증은 유지한다.
|
||||
|
||||
## 0.16.0 공지 띠
|
||||
|
||||
`Notice.kt`가 서버 공지를 화면용으로 정리한다(줄바꿈·제어 문자는 빈칸, 200자까지, tone이 warn일 때만 주의). `UpdateChecker`는 `api/version` 응답의 `notice`를 `Notice.save`로 보관하고 바뀌면 `MainActivity.render`를 다시 부른다. 첫 화면은 상태 줄 아래와 오늘 카드 위에 홈페이지 공지 띠와 같은 색(안내 #E9EEF5 · 주의 #F8ECE5)으로 그린다. 단위 시험은 `NoticeTest`다.
|
||||
|
||||
## 0.16.1 날짜 넘김
|
||||
|
||||
`DayRollover.kt`가 날짜가 바뀐 뒤의 달과 고른 날 규칙을 맡는다. `MainActivity`는 `onResume`에서 `followToday()`를 부르고 화면이 보이는 동안 `ACTION_TIME_TICK`·`ACTION_DATE_CHANGED`·`ACTION_TIME_CHANGED`·`ACTION_TIMEZONE_CHANGED`를 동적 수신기로 듣는다(API 33 이상은 `RECEIVER_NOT_EXPORTED`). 위젯은 `DutyWidget.selectedMonth`가 `DayRollover.widgetMonth`로 저장한 달을 읽는다. 단위 시험은 `DayRolloverTest`이고 위젯 기기 시험(widgetCheck)은 지난달에 옮겨 둔 달과 예전 버전 저장이 지금 달로 돌아오는지 확인한다.
|
||||
+13
-5
@@ -157,19 +157,19 @@ ANNUAL_LEAVE와 MONTHLY_LEAVE 및 VACATION과 OFFICIAL_LEAVE 및 FAMILY_LEAVE를
|
||||
|
||||
## 관리자 로고 메뉴 · 2026년 11월 24일
|
||||
|
||||
관리자 페이지의 **로고**에서 홈페이지 로고와 브라우저 탭 및 홈 화면 아이콘을 바꿉니다. 그림을 올리거나 제미나이로 후보를 만든 뒤 고릅니다. 관리자 브라우저가 가운데를 정사각형으로 잘라 512·192·180·64px와 둥근 홈 화면용 512px PNG를 만들어 보내고 서버는 PNG 서명과 크기만 확인해 데이터 폴더의 `brand/`에 둡니다. 여백과 홈 화면 배경색을 고를 수 있습니다. 바꾼 그림이 없으면 기본 로고(`web/icon.svg` 등)를 쓰고 **기본 로고로 되돌리기**로 언제든 돌아갑니다.
|
||||
관리자 페이지의 **로고**에서 홈페이지 로고와 브라우저 탭 및 홈 화면 아이콘을 바꿉니다. 그림을 올리거나 보관한 그림에서 고릅니다. 관리자 브라우저가 가운데를 정사각형으로 잘라 512·192·180·64px와 둥근 홈 화면용 512px PNG를 만들어 보내고 서버는 PNG 서명과 크기만 확인해 데이터 폴더의 `brand/`에 둡니다. 여백과 홈 화면 배경색을 고를 수 있습니다. 바꾼 그림이 없으면 기본 로고(`web/icon.svg` 등)를 쓰고 **기본 로고로 되돌리기**로 언제든 돌아갑니다.
|
||||
|
||||
공개 주소는 `brand/logo`·`brand/favicon`·`brand/apple-touch`·`brand/icon-192`·`brand/icon-512`·`brand/icon-maskable`입니다. 앱 설치 정보 `manifest.webmanifest`는 서버가 서비스 이름과 이 주소로 만들어 줍니다. 홈페이지와 관리자 페이지는 이 주소만 씁니다.
|
||||
|
||||
제미나이 후보는 관리자가 쓴 설명과 모델 이름으로 한 번에 1~4장을 만듭니다. 서버가 뒤에서 만들고 화면은 3초마다 진행을 확인합니다. 후보는 최근 40장까지 보관합니다. 키는 root만 읽는 파일로 두고 서비스 drop-in에 `LoadCredential=gemini:<키 파일>`을 넣어 서비스에만 건넵니다. 키 값은 응답과 기록에 남기지 않습니다. 키가 없으면 화면에 안내만 나오고 다른 기능은 그대로 됩니다. 다른 서버에서 시험할 때는 `DUTY_GEMINI_KEY_FILE`과 `DUTY_GEMINI_URL`로 키 파일과 주소를 바꿀 수 있습니다.
|
||||
보관한 그림은 운영 도구로 넣고 관리자 화면에서 고르거나 지웁니다. 목록에는 넣은 날과 넣은 사람만 보입니다.
|
||||
|
||||
로고 업로드 `POST /calendar/api/admin/brand-logo`만 요청 한도가 6MB입니다. 앱과 nginx 두 곳에서 같은 주소만 올렸고 다른 요청은 256KB를 지킵니다. 사이트 보안 정책이 blob: 그림을 막아서 올린 파일은 data: 주소로 읽습니다.
|
||||
|
||||
검사: `test_site_admin`의 로고 시험은 가짜 제미나이 서버를 띄워 키가 머리글로만 전달되는지와 후보 저장·삭제 및 모델 이름 오류 안내를 확인합니다.
|
||||
검사: `test_site_admin`의 로고 시험은 그림 올리기와 크기 검사 및 기본 로고로 되돌리기를 확인하고 운영 도구로 넣은 그림의 보관과 적용 및 지우기를 확인합니다.
|
||||
|
||||
### 서버 밖에서 만든 그림 넣기
|
||||
### 운영 도구로 그림 넣기
|
||||
|
||||
운영 서버는 그림마다 비용이 드는 제미나이 API 키를 쓰지 않습니다. 메인 서버의 제미나이 구독(Antigravity CLI)으로 한 장씩 만든 그림을 `brand_import.py`로 넣습니다. `add-candidate`는 그림을 후보 목록에 넣고 `apply`는 미리 만든 크기별 PNG 다섯 장으로 로고를 바꿉니다. 둘 다 서비스 계정으로 실행하고 관리 작업 기록에 남습니다. 사용법은 파일 머리 설명에 있습니다.
|
||||
`brand_import.py`의 `add-candidate`는 그림을 보관한 그림에 넣고 `apply`는 미리 준비한 크기별 PNG 다섯 장으로 로고를 바꿉니다. 둘 다 서비스 계정으로 실행하고 관리 작업 기록에 남습니다. 사용법은 파일 머리 설명에 있습니다.
|
||||
|
||||
관리자 화면은 둥근 사각형 바깥 모서리가 흰 그림을 알아보고 16% 확대해 잘라 내며 배경색을 가장자리 색에 맞춥니다. **확대** 조절로 직접 바꿀 수 있습니다.
|
||||
|
||||
@@ -182,3 +182,11 @@ ANNUAL_LEAVE와 MONTHLY_LEAVE 및 VACATION과 OFFICIAL_LEAVE 및 FAMILY_LEAVE를
|
||||
- 게시판: `board.py`가 `boards`·`board_posts`·`board_comments` 세 표를 새로 만든다(기존 표는 바꾸지 않음). 처음에 공지사항(관리자만 쓰기)과 자유게시판 및 질문·건의를 넣는다. 게시판마다 읽기(누구나·회원만)와 글쓰기(회원·관리자만) 및 댓글(회원·관리자만·없음)과 순서·사용을 관리자에서 정한다. 글과 댓글은 지우지 않고 상태(open·hidden·deleted)만 바꿔 되살릴 수 있다. 글자 수와 하루 한도 및 쪽당 글 수는 게시판 설정 칸이다. 관리자 작업은 작업 기록의 **게시판** 구분에 남는다. 화면은 `/calendar/board`(board.html·board.js).
|
||||
|
||||
검사: `python -m unittest test_board`(권한·하루 한도·숨김과 되살리기·글자 처리·게시판 만들기와 쉬게 하기·새 설정 종류). Starlette 시험 클라이언트에는 `requirements-dev.txt`의 httpx2가 필요하다.
|
||||
|
||||
## 관리자 공지 메뉴 · 웹 2026-12-01.1
|
||||
|
||||
관리자 페이지에 **공지**(`view-notice`) 화면을 더했다. 공지 띠 세 칸은 `SITE_FIELDS`에서 `page: "notice"`로 옮겨 이 화면에 그린다(저장 값과 공개 `api/site`는 그대로). 미리보기는 홈페이지 공지 띠와 같은 색이다. 공지사항 글은 게시판 `notice`에 쓰고 기존 게시판 API(`POST /api/boards/notice/posts`·`POST /api/posts/{id}`·`POST /api/admin/board-post/{id}`)를 그대로 쓴다. 고치기와 고정·숨기기·지우기·되살리기를 한 목록에서 한다.
|
||||
|
||||
`site_admin.notice(db)`가 켜진 공지의 글과 종류를 돌려주고 `GET /calendar/api/version`에 `notice`로 넣는다. 앱 0.16.0이 이 값으로 첫 화면 맨 위에 공지 띠를 그린다.
|
||||
|
||||
검사: `test_site_admin`의 공개 설정 시험이 공지 띠를 켜고 끌 때 `api/version`의 `notice`와 칸의 `page`를 확인한다. `test_app`은 기본값(빈 공지)을 확인한다.
|
||||
+3
-2
@@ -36,7 +36,7 @@ DATA = Path(os.environ.get("DUTY_DATA", ROOT / "data"))
|
||||
DATA.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
ORIGIN = os.environ.get("DUTY_ORIGIN", "https://duty.itosm.co.kr").rstrip("/")
|
||||
PREFIX = "/calendar"
|
||||
SERVER_VERSION = "0.15.7"
|
||||
SERVER_VERSION = "0.16.1"
|
||||
COOKIE = "__Secure-duty_session"
|
||||
pepper_file = DATA / "pairing.key"
|
||||
if not pepper_file.exists():
|
||||
@@ -673,7 +673,8 @@ def release_info():
|
||||
@app.get(PREFIX + "/api/version")
|
||||
async def version():
|
||||
release = release_info()
|
||||
return {**{key: release[key] for key in ("appVersion", "appVersionCode", "webVersion", "notes", "apkBytes", "apkSha256")}, "holidayRevision": holidays.read()[1]["revision"]}
|
||||
return {**{key: release[key] for key in ("appVersion", "appVersionCode", "webVersion", "notes", "apkBytes", "apkSha256")}, "holidayRevision": holidays.read()[1]["revision"],
|
||||
"notice": site_admin.notice(db)}
|
||||
|
||||
|
||||
@app.get(PREFIX + "/")
|
||||
|
||||
+11
-148
@@ -1,40 +1,25 @@
|
||||
"""로고 그림 관리(관리자 페이지 '로고' 메뉴).
|
||||
|
||||
관리자가 올린 그림이나 제미나이로 만든 후보를 골라 홈페이지 로고와 파비콘 및 홈 화면 아이콘을 바꾼다.
|
||||
관리자가 올린 그림이나 보관한 그림을 골라 홈페이지 로고와 파비콘 및 홈 화면 아이콘을 바꾼다.
|
||||
크기별 PNG는 관리자 브라우저가 만들어 보내고 서버는 PNG 형식과 크기만 확인해 데이터 폴더에 둔다.
|
||||
바꾼 그림이 없으면 web 폴더의 기본 로고를 그대로 준다. 새 파이썬 패키지는 쓰지 않는다.
|
||||
|
||||
제미나이 키는 systemd LoadCredential(gemini)로만 받는다. 키 값은 응답·기록·화면 어디에도 내보내지 않는다.
|
||||
키 넣기: 보조 서버에서 ~/bin/duty-gemini-key.sh (사용자가 직접 실행)
|
||||
바꾼 그림이 없으면 web 폴더의 기본 로고를 그대로 준다. 보관한 그림은 운영 도구(brand_import.py)로 넣는다.
|
||||
새 파이썬 패키지는 쓰지 않는다.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
from pathlib import Path
|
||||
from urllib.request import Request as UrlRequest, urlopen
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
from fastapi.responses import FileResponse, JSONResponse, Response
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
|
||||
import site_admin
|
||||
|
||||
# 관리자 브라우저가 만들어 보내는 그림. 이름: (가로·세로 픽셀)
|
||||
SIZES = {"512": 512, "192": 192, "180": 180, "64": 64, "maskable": 512}
|
||||
MAX_IMAGE = 1_500_000
|
||||
MAX_CANDIDATES = 40
|
||||
GEMINI_URL = os.environ.get("DUTY_GEMINI_URL", "https://generativelanguage.googleapis.com").rstrip("/")
|
||||
DEFAULT_MODEL = "gemini-2.5-flash-image"
|
||||
DEFAULT_PROMPT = ("Minimal modern app icon for a Korean duty-shift calendar app named '당직근무'. "
|
||||
"A clean calendar page with a small crescent moon for night duty, flat vector style, "
|
||||
"deep navy #26364d and terracotta #b65b3c on warm off-white #fffdf8, centered, "
|
||||
"simple geometric shapes, no text, no letters, rounded square background, crisp edges, high contrast.")
|
||||
# 공개 주소 → (바꾼 그림 파일, 기본 그림 파일, 형식)
|
||||
PUBLIC = {
|
||||
"logo": ("logo-192.png", "icon.svg"),
|
||||
@@ -64,65 +49,11 @@ def image_kind(raw):
|
||||
return None, None
|
||||
|
||||
|
||||
def gemini_key():
|
||||
folder = os.environ.get("CREDENTIALS_DIRECTORY")
|
||||
path = Path(folder) / "gemini" if folder else Path(os.environ.get("DUTY_GEMINI_KEY_FILE", "/nonexistent"))
|
||||
try:
|
||||
key = path.read_text(encoding="utf8").strip()
|
||||
except OSError:
|
||||
return ""
|
||||
return key if re.fullmatch(r"[A-Za-z0-9_\-]{20,200}", key) else ""
|
||||
|
||||
|
||||
def gemini_image(key, model, prompt):
|
||||
"""제미나이에 그림 한 장을 요청한다. 모델이 그림 설정을 모르면 더 단순한 요청으로 한 번 더 시도한다."""
|
||||
url = GEMINI_URL + "/v1beta/models/" + urllib.parse.quote(model, safe="-._") + ":generateContent"
|
||||
attempts = [
|
||||
{"responseModalities": ["IMAGE"], "imageConfig": {"aspectRatio": "1:1"}},
|
||||
{"responseModalities": ["TEXT", "IMAGE"]},
|
||||
]
|
||||
last = "그림을 받지 못했습니다."
|
||||
for index, config in enumerate(attempts):
|
||||
body = json.dumps({"contents": [{"parts": [{"text": prompt}]}], "generationConfig": config}).encode()
|
||||
request = UrlRequest(url, data=body, method="POST", headers={"Content-Type": "application/json", "x-goog-api-key": key})
|
||||
try:
|
||||
with urlopen(request, timeout=120) as response:
|
||||
data = json.loads(response.read(30_000_000))
|
||||
except urllib.error.HTTPError as error:
|
||||
try:
|
||||
detail = json.loads(error.read(20000)).get("error", {}).get("message", "")
|
||||
except ValueError:
|
||||
detail = ""
|
||||
error.close()
|
||||
names = {400: "요청 형식 또는 모델", 401: "키", 403: "키 권한", 404: "모델 이름", 429: "사용 한도"}
|
||||
last = "제미나이 오류 " + str(error.code) + " (" + names.get(error.code, "서버") + "): " + detail[:200]
|
||||
if error.code == 400 and index == 0:
|
||||
continue
|
||||
raise RuntimeError(last)
|
||||
except (urllib.error.URLError, TimeoutError, ValueError) as error:
|
||||
raise RuntimeError("제미나이에 연결하지 못했습니다: " + str(error)[:150])
|
||||
texts = []
|
||||
for candidate in data.get("candidates", []):
|
||||
for part in candidate.get("content", {}).get("parts", []):
|
||||
inline = part.get("inlineData") or part.get("inline_data")
|
||||
if inline and inline.get("data"):
|
||||
return base64.b64decode(inline["data"])
|
||||
if part.get("text"):
|
||||
texts.append(part["text"])
|
||||
reason = data.get("promptFeedback", {}).get("blockReason") or (data.get("candidates") or [{}])[0].get("finishReason", "")
|
||||
last = "그림 없이 답이 왔습니다" + (" (" + reason + ")" if reason else "") + (": " + " ".join(texts)[:150] if texts else "")
|
||||
if index == 0:
|
||||
continue
|
||||
raise RuntimeError(last)
|
||||
|
||||
|
||||
def setup(app, prefix, root, data_dir, db, administrator, payload, throttle):
|
||||
web = Path(root) / "web"
|
||||
brand = Path(data_dir) / "brand"
|
||||
candidates = brand / "candidates"
|
||||
candidates.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
jobs = {}
|
||||
job_lock = threading.Lock()
|
||||
with db() as conn:
|
||||
conn.execute("""CREATE TABLE IF NOT EXISTS brand_candidates(id TEXT PRIMARY KEY, created INTEGER NOT NULL,
|
||||
prompt TEXT NOT NULL, model TEXT NOT NULL, ext TEXT NOT NULL, actor TEXT NOT NULL)""")
|
||||
@@ -174,11 +105,8 @@ def setup(app, prefix, root, data_dir, db, administrator, payload, throttle):
|
||||
administrator(request)
|
||||
with db() as conn:
|
||||
rows = [dict(row) for row in conn.execute(
|
||||
"SELECT c.id,c.created,c.prompt,c.model,m.display_name AS actor FROM brand_candidates c LEFT JOIN members m ON m.id=c.actor ORDER BY c.created DESC")]
|
||||
with job_lock:
|
||||
running = [dict(id=key, **value) for key, value in jobs.items() if value["state"] == "running"]
|
||||
return {"custom": custom(), "candidates": rows, "gemini": bool(gemini_key()),
|
||||
"defaultPrompt": DEFAULT_PROMPT, "defaultModel": DEFAULT_MODEL, "running": running}
|
||||
"SELECT c.id,c.created,m.display_name AS actor FROM brand_candidates c LEFT JOIN members m ON m.id=c.actor ORDER BY c.created DESC")]
|
||||
return {"custom": custom(), "candidates": rows}
|
||||
|
||||
@app.post(prefix + "/api/admin/brand-logo")
|
||||
async def brand_logo(request: Request):
|
||||
@@ -202,7 +130,7 @@ def setup(app, prefix, root, data_dir, db, administrator, payload, throttle):
|
||||
decoded[name] = raw
|
||||
candidate = data.get("candidate") if source == "candidate" else None
|
||||
if candidate is not None and not re.fullmatch(r"[a-f0-9]{16}", str(candidate)):
|
||||
raise HTTPException(400, "후보를 확인해 주세요.")
|
||||
raise HTTPException(400, "보관한 그림을 확인해 주세요.")
|
||||
# 파일마다 임시 이름으로 쓴 뒤 바꿔 끼워 반쯤 바뀐 상태가 보이지 않게 한다.
|
||||
(brand / "logo.json").unlink(missing_ok=True)
|
||||
for name, raw in decoded.items():
|
||||
@@ -213,7 +141,7 @@ def setup(app, prefix, root, data_dir, db, administrator, payload, throttle):
|
||||
temp = brand / "logo.json.tmp"
|
||||
temp.write_text(json.dumps(meta, ensure_ascii=False))
|
||||
temp.replace(brand / "logo.json")
|
||||
log(actor["member"], "logo", "올린 그림" if source == "upload" else "제미나이 후보 " + str(candidate))
|
||||
log(actor["member"], "logo", "올린 그림" if source == "upload" else "보관한 그림 " + str(candidate))
|
||||
return {"custom": meta}
|
||||
|
||||
@app.post(prefix + "/api/admin/brand-logo-reset")
|
||||
@@ -226,72 +154,7 @@ def setup(app, prefix, root, data_dir, db, administrator, payload, throttle):
|
||||
log(actor["member"], "logo-reset", "기본 로고")
|
||||
return {"custom": None}
|
||||
|
||||
# ---------------------------------------------------------------- 관리자: 제미나이 후보
|
||||
def run_job(job_id, actor, model, prompt, count):
|
||||
key = gemini_key()
|
||||
made, errors = 0, []
|
||||
for _ in range(count):
|
||||
try:
|
||||
raw = gemini_image(key, model, prompt)
|
||||
mime, ext = image_kind(raw)
|
||||
if not mime or len(raw) > 20_000_000:
|
||||
raise RuntimeError("그림 형식을 알 수 없습니다.")
|
||||
cid = secrets.token_hex(8)
|
||||
(candidates / (cid + "." + ext)).write_bytes(raw)
|
||||
with db() as conn:
|
||||
conn.execute("INSERT INTO brand_candidates(id,created,prompt,model,ext,actor) VALUES(?,?,?,?,?,?)",
|
||||
(cid, int(time.time()), prompt, model, ext, actor))
|
||||
made += 1
|
||||
except Exception as error: # 한 장이 실패해도 나머지는 계속 만든다.
|
||||
errors.append(str(error)[:300])
|
||||
if "키" in str(error) or "모델 이름" in str(error) or "사용 한도" in str(error):
|
||||
break
|
||||
with job_lock:
|
||||
jobs[job_id].update(made=made, errors=errors)
|
||||
# 오래된 후보부터 정리해 데이터 폴더가 계속 커지지 않게 한다.
|
||||
with db() as conn:
|
||||
old = conn.execute("SELECT id,ext FROM brand_candidates ORDER BY created DESC LIMIT -1 OFFSET ?", (MAX_CANDIDATES,)).fetchall()
|
||||
for row in old:
|
||||
(candidates / (row[0] + "." + row[1])).unlink(missing_ok=True)
|
||||
conn.execute("DELETE FROM brand_candidates WHERE id=?", (row[0],))
|
||||
with job_lock:
|
||||
# 키·모델 오류로 중간에 멈춘 경우에도 마지막 오류를 화면에 보여 줄 수 있게 함께 남긴다.
|
||||
jobs[job_id].update(made=made, errors=errors, state="done" if made else "error")
|
||||
log(actor, "logo-generate", model + " · " + str(made) + "/" + str(count) + "장" + (" · " + errors[0][:120] if errors else ""))
|
||||
|
||||
@app.post(prefix + "/api/admin/brand-generate")
|
||||
async def brand_generate(request: Request):
|
||||
actor = administrator(request)
|
||||
throttle(request, "admin-brand-generate", 10, 3600)
|
||||
data = await payload(request)
|
||||
prompt, model, count = data.get("prompt"), data.get("model", DEFAULT_MODEL), data.get("count", 2)
|
||||
if not isinstance(prompt, str) or not 10 <= len(prompt.strip()) <= 1500:
|
||||
raise HTTPException(400, "그림 설명을 10~1500자로 써 주세요.")
|
||||
if not isinstance(model, str) or not re.fullmatch(r"[a-z0-9][a-z0-9.\-]{2,80}", model):
|
||||
raise HTTPException(400, "모델 이름을 확인해 주세요.")
|
||||
if type(count) is not int or not 1 <= count <= 4:
|
||||
raise HTTPException(400, "한 번에 1~4장까지 만들 수 있습니다.")
|
||||
if not gemini_key():
|
||||
raise HTTPException(409, "제미나이 키가 아직 설정되지 않았습니다. 보조 서버에서 duty-gemini-key.sh로 키를 넣어 주세요.")
|
||||
with job_lock:
|
||||
if any(job["state"] == "running" for job in jobs.values()):
|
||||
raise HTTPException(409, "이미 후보를 만들고 있습니다. 끝난 뒤 다시 눌러 주세요.")
|
||||
job_id = secrets.token_hex(8)
|
||||
jobs[job_id] = {"state": "running", "made": 0, "count": count, "errors": [], "started": int(time.time())}
|
||||
for key in [key for key, job in jobs.items() if job["state"] != "running" and job["started"] < time.time() - 86400]:
|
||||
del jobs[key]
|
||||
threading.Thread(target=run_job, args=(job_id, actor["member"], model, prompt.strip(), count), daemon=True).start()
|
||||
return {"job": job_id}
|
||||
|
||||
@app.get(prefix + "/api/admin/brand-job/{job_id}")
|
||||
async def brand_job(request: Request, job_id: str):
|
||||
administrator(request)
|
||||
with job_lock:
|
||||
job = jobs.get(job_id)
|
||||
if job is None:
|
||||
raise HTTPException(404, "작업을 찾을 수 없습니다.")
|
||||
return dict(job)
|
||||
|
||||
# ---------------------------------------------------------------- 관리자: 보관한 그림
|
||||
@app.get(prefix + "/api/admin/brand-candidate/{candidate_id}")
|
||||
async def brand_candidate(request: Request, candidate_id: str):
|
||||
administrator(request)
|
||||
@@ -299,7 +162,7 @@ def setup(app, prefix, root, data_dir, db, administrator, payload, throttle):
|
||||
row = conn.execute("SELECT id,ext FROM brand_candidates WHERE id=?", (candidate_id,)).fetchone()
|
||||
path = candidates / (row[0] + "." + row[1]) if row else None
|
||||
if path is None or not path.exists():
|
||||
raise HTTPException(404, "후보 그림을 찾을 수 없습니다.")
|
||||
raise HTTPException(404, "보관한 그림을 찾을 수 없습니다.")
|
||||
return FileResponse(path, media_type={"png": "image/png", "jpg": "image/jpeg", "webp": "image/webp"}[row[1]])
|
||||
|
||||
@app.post(prefix + "/api/admin/brand-candidate-delete/{candidate_id}")
|
||||
@@ -308,7 +171,7 @@ def setup(app, prefix, root, data_dir, db, administrator, payload, throttle):
|
||||
with db() as conn:
|
||||
row = conn.execute("SELECT id,ext FROM brand_candidates WHERE id=?", (candidate_id,)).fetchone()
|
||||
if row is None:
|
||||
raise HTTPException(404, "후보 그림을 찾을 수 없습니다.")
|
||||
raise HTTPException(404, "보관한 그림을 찾을 수 없습니다.")
|
||||
conn.execute("DELETE FROM brand_candidates WHERE id=?", (candidate_id,))
|
||||
(candidates / (row[0] + "." + row[1])).unlink(missing_ok=True)
|
||||
log(actor["member"], "logo-candidate-delete", candidate_id)
|
||||
|
||||
+8
-11
@@ -1,13 +1,13 @@
|
||||
"""로고 그림을 서버에서 직접 넣는 운영 도구.
|
||||
|
||||
관리자 페이지의 '로고' 메뉴와 같은 저장 방식과 검사를 쓴다. 제미나이 구독(agy)처럼 서버 밖에서 만든 그림을
|
||||
후보 목록에 넣거나, 미리 만든 크기별 PNG로 로고를 바로 바꿀 때 쓴다. 작업은 관리 작업 기록에 남는다.
|
||||
관리자 페이지의 '로고' 메뉴와 같은 저장 방식과 검사를 쓴다. 그림을 관리자 화면의 '보관한 그림'에 넣거나
|
||||
미리 준비한 크기별 PNG로 로고를 바로 바꿀 때 쓴다. 작업은 관리 작업 기록에 남는다.
|
||||
서비스 계정으로 실행한다(데이터 폴더 권한 때문):
|
||||
|
||||
sudo -u duty-calendar env DUTY_DATA=/var/lib/duty-calendar /opt/duty-calendar/venv/bin/python brand_import.py \\
|
||||
add-candidate 그림.jpg --prompt-file 요청문.txt --model "agy · Gemini" --actor syskiller
|
||||
add-candidate 그림.jpg --actor syskiller
|
||||
sudo -u duty-calendar env DUTY_DATA=/var/lib/duty-calendar /opt/duty-calendar/venv/bin/python brand_import.py \\
|
||||
apply PNG폴더 --candidate 후보ID --actor syskiller (폴더에 logo-512.png logo-192.png logo-180.png logo-64.png logo-maskable.png)
|
||||
apply PNG폴더 --candidate 보관그림ID --actor syskiller (폴더에 logo-512.png logo-192.png logo-180.png logo-64.png logo-maskable.png)
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
@@ -46,7 +46,6 @@ def add_candidate(args):
|
||||
mime, ext = image_kind(raw)
|
||||
if not mime or len(raw) > 20_000_000:
|
||||
sys.exit("PNG·JPG·WebP 그림이 아니거나 너무 큽니다.")
|
||||
prompt = Path(args.prompt_file).read_text(encoding="utf8").strip()[:1500] if args.prompt_file else "서버에서 가져온 그림"
|
||||
folder = DATA / "brand" / "candidates"
|
||||
folder.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
cid = secrets.token_hex(8)
|
||||
@@ -54,8 +53,8 @@ def add_candidate(args):
|
||||
with connect() as conn:
|
||||
who = actor_id(conn, args.actor)
|
||||
conn.execute("INSERT INTO brand_candidates(id,created,prompt,model,ext,actor) VALUES(?,?,?,?,?,?)",
|
||||
(cid, int(time.time()), prompt, args.model[:80], ext, who))
|
||||
log(conn, who, "logo-import", args.model[:80] + " · " + Path(args.file).name)
|
||||
(cid, int(time.time()), "", "운영 도구", ext, who))
|
||||
log(conn, who, "logo-import", "운영 도구 · " + Path(args.file).name)
|
||||
print(cid)
|
||||
|
||||
|
||||
@@ -72,7 +71,7 @@ def apply(args):
|
||||
who = actor_id(conn, args.actor)
|
||||
name = conn.execute("SELECT display_name FROM members WHERE id=?", (who,)).fetchone()[0]
|
||||
if args.candidate and not conn.execute("SELECT 1 FROM brand_candidates WHERE id=?", (args.candidate,)).fetchone():
|
||||
sys.exit("후보를 찾을 수 없습니다: " + args.candidate)
|
||||
sys.exit("보관한 그림을 찾을 수 없습니다: " + args.candidate)
|
||||
# 관리자 화면과 같은 순서: 표식을 먼저 지우고 파일을 바꿔 끼운 뒤 표식을 다시 쓴다.
|
||||
(brand / "logo.json").unlink(missing_ok=True)
|
||||
for key, raw in data.items():
|
||||
@@ -83,7 +82,7 @@ def apply(args):
|
||||
temp = brand / "logo.json.tmp"
|
||||
temp.write_text(json.dumps(meta, ensure_ascii=False))
|
||||
temp.replace(brand / "logo.json")
|
||||
log(conn, who, "logo", "운영 도구 · " + ("제미나이 후보 " + args.candidate if args.candidate else "미리 만든 그림"))
|
||||
log(conn, who, "logo", "운영 도구 · " + ("보관한 그림 " + args.candidate if args.candidate else "미리 준비한 그림"))
|
||||
print("로고를 바꿨습니다.")
|
||||
|
||||
|
||||
@@ -92,8 +91,6 @@ def main():
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
one = sub.add_parser("add-candidate")
|
||||
one.add_argument("file")
|
||||
one.add_argument("--prompt-file")
|
||||
one.add_argument("--model", default="서버에서 가져옴")
|
||||
one.add_argument("--actor", required=True)
|
||||
two = sub.add_parser("apply")
|
||||
two.add_argument("folder")
|
||||
|
||||
@@ -10,9 +10,18 @@ import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from work_names import name_matches
|
||||
from work_plan import shift as plan_shift, name_on, name_mode_on
|
||||
from work_plan import shift as plan_shift, name_on, name_mode_on, AWAY
|
||||
|
||||
OPTIONS=('rotation','events','anniversaries','names','notes')
|
||||
# 근무 순서 이름(그날 당직자)을 다른 달력에 함께 보낼지 날 종류마다 고른다. 기본은 모두 꺼짐이라 근무 글자만 간다(2026-11-26 사용자 지시).
|
||||
NAME_KINDS=('nameWork','nameOff','nameRest','nameAway')
|
||||
|
||||
def name_kind(value):
|
||||
"""그날 근무가 어느 이름 칸에 속하는지: 비번 · 휴무 · 연차·휴가·반차·병가·교육 · 그 밖의 근무(당직·일반근무·주간·오후·야간)."""
|
||||
if value=='OFF':return 'nameOff'
|
||||
if value=='REST':return 'nameRest'
|
||||
if value in AWAY:return 'nameAway'
|
||||
return 'nameWork'
|
||||
LABELS={'DUTY':'당직','OFF':'비번','REGULAR':'일반근무','DAY':'주간','EVENING':'오후','NIGHT':'야간','REST':'휴무','LEAVE':'연차·휴가','SICK':'병가','TRAINING':'교육','ANNUAL_LEAVE':'연차','MONTHLY_LEAVE':'월차','VACATION':'일반휴가','OFFICIAL_LEAVE':'공가','FAMILY_LEAVE':'경조휴가','HALF_LEAVE':'반차'}
|
||||
KOREA=timezone(timedelta(hours=9))
|
||||
LUNAR=json.loads((Path(__file__).parent/'web/lunar-months.json').read_text(encoding='utf-8'))
|
||||
@@ -30,7 +39,9 @@ def options(data):
|
||||
# skipRegular(0.15.5): 다른 달력(구글 등)에 일반근무 날을 통째로 보내지 않는다. 없으면 끔이고 끄면 앱 달력과 같게 보낸다.
|
||||
if 'skipRegular' in data and type(data['skipRegular']) is not bool:
|
||||
raise ValueError('일반근무 빼기 선택을 확인해 주세요.')
|
||||
return {**{key:data[key] for key in OPTIONS},'skipRegular':data.get('skipRegular') is True}
|
||||
if any(key in data and type(data[key]) is not bool for key in NAME_KINDS):
|
||||
raise ValueError('이름 함께 보내기 선택을 확인해 주세요.')
|
||||
return {**{key:data[key] for key in OPTIONS},'skipRegular':data.get('skipRegular') is True,**{key:data.get(key) is True for key in NAME_KINDS}}
|
||||
|
||||
def shift(data,day):
|
||||
return plan_shift(data,day)
|
||||
@@ -91,7 +102,8 @@ def project(state,chosen,today,holidays):
|
||||
if name_matches(rule,day,own,holiday,shift(person,day) if person else None):
|
||||
name=person['name'] if rule['mode']=='PERSON' else rule['name']
|
||||
if name not in names:names.append(name)
|
||||
slot=name_on(rotation,day);slot_mode=name_mode_on(rotation,day,mode) if slot else mode
|
||||
# 근무 순서 이름은 그날 종류의 칸을 켰을 때만 보낸다. 끄면 이름만 고른 줄도 근무 글자로 보낸다.
|
||||
slot=name_on(rotation,day) if chosen.get(name_kind(own)) is True else '';slot_mode=name_mode_on(rotation,day,mode) if slot else mode
|
||||
if own=='REGULAR' and hide_regular:title=slot if slot and slot_mode!='shift' else ''
|
||||
else:title=labels[own] if not slot or slot_mode=='shift' else slot if slot_mode=='name' else labels[own]+'('+slot+')'
|
||||
text=' · '.join([title]+names if title else names)
|
||||
|
||||
+8
-8
@@ -1,13 +1,13 @@
|
||||
{
|
||||
"appVersion": "0.15.7",
|
||||
"appVersionCode": 31,
|
||||
"webVersion": "2026-11-26.2",
|
||||
"apkFile": "duty-calendar-0.15.7.apk",
|
||||
"appVersion": "0.16.1",
|
||||
"appVersionCode": 35,
|
||||
"webVersion": "2026-12-01.2",
|
||||
"apkFile": "duty-calendar-0.16.1.apk",
|
||||
"notes": [
|
||||
"연차 같은 휴가를 쓴 날은 날짜 숫자가 빨간색, 새로 더한 반차는 파란색으로 보입니다.",
|
||||
"위젯의 날짜 옆 + 표시를 뺐습니다.",
|
||||
"날짜가 바뀌면 앱 달력이 지난달에 머물지 않고 이번 달로 넘어갑니다. 12월 1일인데 11월 달력의 회색 칸에 오늘이 보이던 문제를 고쳤습니다.",
|
||||
"달력 위젯도 지난달에 옮겨 둔 달은 이번 달로 돌아옵니다. 직접 다른 달로 옮겨 둔 화면은 그대로 둡니다.",
|
||||
"Play 프로텍트 차단 해제가 확인된 버전은 아닙니다."
|
||||
],
|
||||
"apkBytes": 877582,
|
||||
"apkSha256": "9ac008956635a19e0ffae5c5ab79ccdcc6c3967da6533bc739c360372477c6bb"
|
||||
"apkBytes": 884022,
|
||||
"apkSha256": "d83b3d822ffe55507b1022394b14a78ab5d3ef696b908717637eacb558aa757f"
|
||||
}
|
||||
+15
-5
@@ -45,9 +45,11 @@ SITE_FIELDS = {
|
||||
"defaultShowLunar": {"group": "처음 기본값(웹)", "label": "음력 날짜 함께 보기", "kind": "bool", "default": False},
|
||||
"defaultOffRed": {"group": "처음 기본값(웹)", "label": "비번을 빨간색으로 표시", "kind": "bool", "default": False},
|
||||
"defaultDutyWeekday": {"group": "처음 기본값(웹)", "label": "당직일은 평일색으로 표시", "kind": "bool", "default": False},
|
||||
"noticeOn": {"group": "공지 띠", "label": "공지 띠 보이기", "kind": "bool", "default": False},
|
||||
"noticeTone": {"group": "공지 띠", "label": "공지 종류", "kind": "choice", "choices": {"info": "안내", "warn": "주의"}, "default": "info"},
|
||||
"noticeText": {"group": "공지 띠", "label": "공지 내용", "kind": "text", "max": 200, "default": ""},
|
||||
# 공지 띠는 관리자 '공지' 화면에서 고친다. 홈페이지 맨 위와 앱 첫 화면(0.16.0부터, api/version의 notice)에 같이 보인다.
|
||||
"noticeOn": {"page": "notice", "group": "공지 띠", "label": "공지 띠 보이기", "kind": "bool", "default": False},
|
||||
"noticeTone": {"page": "notice", "group": "공지 띠", "label": "공지 종류", "kind": "choice", "choices": {"info": "안내", "warn": "주의"}, "default": "info"},
|
||||
"noticeText": {"page": "notice", "group": "공지 띠", "label": "공지 내용", "kind": "text", "max": 200, "default": "",
|
||||
"help": "홈페이지 맨 위와 앱 첫 화면에 한 줄로 보입니다. 200자까지 씁니다."},
|
||||
"registrationOpen": {"group": "회원", "label": "새 회원가입 받기", "kind": "bool", "default": True},
|
||||
# 게시판 화면 설정. 게시판 종류(이름·권한)는 관리자 '게시판'에서 따로 만든다.
|
||||
"boardOn": {"page": "board", "group": "게시판 전체", "label": "게시판 열기", "kind": "bool", "default": True,
|
||||
@@ -69,8 +71,8 @@ ACTION_NAMES = {
|
||||
"rename": "소속 이름 변경", "revoke-invite": "초대코드 종료", "remove-member": "소속에서 내보내기",
|
||||
"transfer": "소속 관리자 변경", "delete-company": "소속 삭제", "settings": "홈페이지 설정 변경",
|
||||
"settings-reset": "홈페이지 설정 기본값", "holiday-refresh": "공휴일 자료 갱신",
|
||||
"logo": "로고 바꾸기", "logo-reset": "기본 로고로 되돌리기", "logo-generate": "제미나이 로고 후보 만들기",
|
||||
"logo-candidate-delete": "로고 후보 지우기", "logo-import": "로고 후보 가져오기",
|
||||
"logo": "로고 바꾸기", "logo-reset": "기본 로고로 되돌리기",
|
||||
"logo-candidate-delete": "보관한 로고 그림 지우기", "logo-import": "로고 그림 보관",
|
||||
}
|
||||
|
||||
|
||||
@@ -442,6 +444,14 @@ def setup(app, prefix, root, data_dir, db, identity, payload, throttle, administ
|
||||
return {"entries": rows, "total": total, "page": page, "pageSize": 50}
|
||||
|
||||
|
||||
def notice(db):
|
||||
"""공지 띠. 앱은 버전 확인(api/version) 때 함께 받아 첫 화면에 보인다. 꺼져 있거나 글이 없으면 text가 빈 글자다."""
|
||||
with db() as conn:
|
||||
values, _ = read_settings(conn)
|
||||
text = values["noticeText"].strip() if values["noticeOn"] else ""
|
||||
return {"text": text, "tone": values["noticeTone"] if text else "info"}
|
||||
|
||||
|
||||
def registration_open(db):
|
||||
with db() as conn:
|
||||
values, _ = read_settings(conn)
|
||||
|
||||
+53
-5
@@ -14,6 +14,9 @@ os.environ["DUTY_REFRESH"] = "0"
|
||||
from fastapi.testclient import TestClient
|
||||
import app as service
|
||||
|
||||
# 근무 순서 이름을 다른 달력에 함께 보내는 칸(0.15.8). 기본은 모두 꺼짐이다.
|
||||
ALL_NAMES=dict(nameWork=True,nameOff=True,nameRest=True,nameAway=True)
|
||||
|
||||
|
||||
class CalendarTests(unittest.TestCase):
|
||||
def name_operation(self):
|
||||
@@ -177,7 +180,7 @@ class CalendarTests(unittest.TestCase):
|
||||
for names in (['김철수'],['', '가'*11, ''],['', 1, ''],'김철수',['', '줄\x07', '']):
|
||||
self.assertEqual(self.write([rotation_op(rotation()['version'],['DUTY','OFF','REGULAR'],names)]).status_code,400,repr(names))
|
||||
# 구독 제목: 기본은 근무와 이름 둘 다, 이름만, 근무만을 고를 수 있다.
|
||||
options=dict(rotation=True,events=False,anniversaries=False,names=False,notes=False)
|
||||
options=dict(rotation=True,events=False,anniversaries=False,names=False,notes=False,**ALL_NAMES)
|
||||
feed=self.client.post('/calendar/api/calendar-sharing',json={'action':'create','options':options},headers=self.auth()).json()['url']
|
||||
text=self.client.get(feed).text
|
||||
self.assertIn('SUMMARY:비번(김철수)',text);self.assertIn('SUMMARY:일반근무(이영희)',text);self.assertIn('SUMMARY:당직\r',text)
|
||||
@@ -207,7 +210,7 @@ class CalendarTests(unittest.TestCase):
|
||||
pattern=['DUTY','OFF','REGULAR','REGULAR']
|
||||
self.assertEqual(self.write([rotation_op(0,pattern,names=['','김철수','이영희','박민수'],nameModes=['','name','both','shift'])]).status_code,200)
|
||||
self.assertEqual(rotation()['data']['nameModes'],['','name','both','shift'])
|
||||
options=dict(rotation=True,events=False,anniversaries=False,names=False,notes=False)
|
||||
options=dict(rotation=True,events=False,anniversaries=False,names=False,notes=False,**ALL_NAMES)
|
||||
feed=self.client.post('/calendar/api/calendar-sharing',json={'action':'create','options':options},headers=self.auth()).json()['url']
|
||||
text=self.client.get(feed).text
|
||||
self.assertIn('SUMMARY:김철수\r',text);self.assertIn('SUMMARY:일반근무(이영희)',text);self.assertNotIn('박민수',text);self.assertNotIn('SUMMARY:비번',text)
|
||||
@@ -240,7 +243,7 @@ class CalendarTests(unittest.TestCase):
|
||||
rotation={'id':'rotation','kind':'rotation','changeId':str(uuid.uuid4()),'baseVersion':0,'deleted':False,
|
||||
'data':{'anchor':'2026-11-19','pattern':['DUTY','OFF','REGULAR','REGULAR'],'names':['','이정훈','강주석',''],'nameModes':['','name','both','both']}}
|
||||
self.assertEqual(self.write([rotation]).status_code,200)
|
||||
options=dict(rotation=True,events=False,anniversaries=False,names=False,notes=False)
|
||||
options=dict(rotation=True,events=False,anniversaries=False,names=False,notes=False,**ALL_NAMES)
|
||||
made=self.client.post('/calendar/api/calendar-sharing',json={'action':'create','options':options},headers=self.auth()).json()
|
||||
feed=made['url'];text=self.client.get(feed).text
|
||||
self.assertIn('SUMMARY:이정훈\r',text);self.assertIn('SUMMARY:일반근무(강주석)',text);self.assertIn('SUMMARY:일반근무\r',text)
|
||||
@@ -261,13 +264,57 @@ class CalendarTests(unittest.TestCase):
|
||||
self.client.post('/calendar/api/calendar-sharing',json={'action':'disable'},headers=self.auth())
|
||||
self.assertEqual(self.client.post('/calendar/api/calendar-sharing',json={'action':'update','options':options},headers=self.auth()).status_code,400)
|
||||
|
||||
def test_feed_names_off_by_default_and_per_kind(self):
|
||||
# 2026-11-26 사용자 지시: 연동 달력은 기본이 이름 표기 없음이고 비번·휴무·연차 등 날 종류마다 체크로 켠다.
|
||||
import calendar_export
|
||||
from datetime import date
|
||||
data={'anchor':'2026-11-19','pattern':['DUTY','OFF','REGULAR','REST'],'names':['나','김철수','이영희','박민수'],'nameModes':['both','both','name','both'],
|
||||
'workPlan':{'overrides':{'2026-11-27':{'shift':'ANNUAL_LEAVE'}}}}
|
||||
state={'items':[{'id':'rotation','kind':'rotation','deleted':False,'data':data}]}
|
||||
base=dict(rotation=True,events=False,anniversaries=False,names=False,notes=False)
|
||||
rows=lambda chosen:{row['key']:row['title'] for row in calendar_export.project(state,calendar_export.options(chosen),date(2026,11,19),{})}
|
||||
# 예전 구독(칸 값 없음)과 새 기본: 이름 없이 근무 글자만. 이름만 고른 줄도 근무 글자로 보낸다.
|
||||
plain=rows(base)
|
||||
self.assertEqual([plain['rotation:2026-11-'+d] for d in ('19','20','21','22','27')],['당직','비번','일반근무','휴무','연차'])
|
||||
self.assertFalse(any(name in str(plain) for name in ('나)','김철수','이영희','박민수')))
|
||||
self.assertEqual({k:v for k,v in calendar_export.options(base).items() if k.startswith('name') and k!='names'},dict(nameWork=False,nameOff=False,nameRest=False,nameAway=False))
|
||||
# 비번만 켜면 비번 날에만 이름이 붙는다.
|
||||
only=rows({**base,'nameOff':True})
|
||||
self.assertEqual(only['rotation:2026-11-20'],'비번(김철수)');self.assertEqual(only['rotation:2026-11-22'],'휴무');self.assertEqual(only['rotation:2026-11-27'],'연차')
|
||||
# 휴무·연차(자리 비운 날)·당직과 근무도 따로 켠다. 11-27(원래 당직 자리)을 연차로 바꾼 날은 그 자리 이름이 남는다.
|
||||
self.assertEqual(rows({**base,'nameRest':True})['rotation:2026-11-22'],'휴무(박민수)')
|
||||
self.assertEqual(rows({**base,'nameAway':True})['rotation:2026-11-27'],'연차(나)')
|
||||
work=rows({**base,'nameWork':True})
|
||||
self.assertEqual(work['rotation:2026-11-19'],'당직(나)');self.assertEqual(work['rotation:2026-11-21'],'이영희');self.assertEqual(work['rotation:2026-11-20'],'비번')
|
||||
for bad in ('yes',1,None):
|
||||
with self.assertRaises(ValueError):calendar_export.options({**base,'nameOff':bad})
|
||||
# 서버에 저장해도 칸 값이 그대로 남는다.
|
||||
rotation={'id':'rotation','kind':'rotation','changeId':str(uuid.uuid4()),'baseVersion':0,'deleted':False,'data':data}
|
||||
self.assertEqual(self.write([rotation]).status_code,200)
|
||||
made=self.client.post('/calendar/api/calendar-sharing',json={'action':'create','options':base},headers=self.auth()).json()
|
||||
text=self.client.get(made['url']).text;self.assertIn('SUMMARY:비번\r',text);self.assertNotIn('김철수',text)
|
||||
changed=self.client.post('/calendar/api/calendar-sharing',json={'action':'update','options':{**base,'nameOff':True}},headers=self.auth())
|
||||
self.assertEqual(changed.status_code,200);self.assertTrue(changed.json()['options']['nameOff']);self.assertFalse(changed.json()['options']['nameRest'])
|
||||
self.assertIn('SUMMARY:비번(김철수)',self.client.get(made['url']).text)
|
||||
self.assertEqual(self.client.post('/calendar/api/calendar-sharing',json={'action':'update','options':{**base,'nameOff':'yes'}},headers=self.auth()).status_code,400)
|
||||
|
||||
def test_five_day_saturday_keeps_original_shift(self):
|
||||
# 2026-11-26 사용자 지시: 주5일제 토요일은 날짜만 빨간색이다. 휴무로 바꾸지 않고 원래 근무 순서를 따른다.
|
||||
import work_plan
|
||||
from datetime import date
|
||||
saturday=date(2026,11,21)
|
||||
for kind in work_plan.SHIFTS:
|
||||
self.assertEqual(work_plan.shift({'anchor':'2026-11-21','pattern':[kind],'workWeek':5},saturday),kind)
|
||||
plan={'anchor':'2026-11-01','pattern':['DUTY'],'workPlan':{'changes':[{'from':'2026-11-02','anchor':'2026-11-02','pattern':['OFF','REGULAR'],'workWeek':5}]}}
|
||||
self.assertEqual(work_plan.shift(plan,saturday),'REGULAR')
|
||||
|
||||
def test_leave_days_keep_slot_name(self):
|
||||
# 2026-11-26 사용자 지시: 연차를 써도 그날 당직자는 그대로라 이름이 보여야 한다.
|
||||
import work_plan,calendar_export
|
||||
from datetime import date
|
||||
away=('REST','LEAVE','SICK','TRAINING','ANNUAL_LEAVE','MONTHLY_LEAVE','VACATION','OFFICIAL_LEAVE','FAMILY_LEAVE','HALF_LEAVE')
|
||||
self.assertEqual(work_plan.AWAY,away);on=date(2026,11,22)
|
||||
chosen=dict(rotation=True,events=False,anniversaries=False,names=False,notes=False,skipRegular=True)
|
||||
chosen=dict(rotation=True,events=False,anniversaries=False,names=False,notes=False,skipRegular=True,**ALL_NAMES)
|
||||
for kind in work_plan.SHIFTS:
|
||||
for mode in ('both','name','shift'):
|
||||
data={'anchor':'2026-11-20','pattern':['DUTY','OFF','REGULAR'],'names':['','김철수','이영희'],'nameModes':['',mode,mode],'workPlan':{'overrides':{'2026-11-22':{'shift':kind}}}}
|
||||
@@ -350,7 +397,8 @@ class CalendarTests(unittest.TestCase):
|
||||
release = json.loads((Path(__file__).parent / 'release.json').read_text(encoding='utf8'))
|
||||
response = self.client.get('/calendar/api/version')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(set(response.json()), {'appVersion','appVersionCode','webVersion','notes','holidayRevision','apkBytes','apkSha256'})
|
||||
self.assertEqual(set(response.json()), {'appVersion','appVersionCode','webVersion','notes','holidayRevision','apkBytes','apkSha256','notice'})
|
||||
self.assertEqual(response.json()['notice'], {'text': '', 'tone': 'info'})
|
||||
self.assertEqual(response.json()['appVersion'], release['appVersion'])
|
||||
script = (Path(__file__).parent / 'web/updates.js').read_text(encoding='utf8')
|
||||
self.assertIn("const WEB_BUILD = '" + release['webVersion'] + "'", script)
|
||||
|
||||
+26
-72
@@ -4,11 +4,9 @@
|
||||
추가 패키지 없이 서버 실행 환경(uvicorn)만 있으면 돌릴 수 있다: python -m unittest test_site_admin
|
||||
"""
|
||||
import base64
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import threading
|
||||
import zlib
|
||||
import socket
|
||||
import subprocess
|
||||
@@ -21,7 +19,6 @@ import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
FAKE_KEY = "fake-gemini-key-for-tests-0001"
|
||||
|
||||
|
||||
def png(size, rgb=(38, 54, 77)):
|
||||
@@ -32,25 +29,6 @@ def png(size, rgb=(38, 54, 77)):
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
class FakeGemini(http.server.BaseHTTPRequestHandler):
|
||||
"""제미나이 대신 그림 한 장을 돌려주는 가짜 서버. 받은 요청을 기록한다."""
|
||||
calls = []
|
||||
|
||||
def do_POST(self):
|
||||
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
||||
FakeGemini.calls.append({"path": self.path, "key": self.headers.get("x-goog-api-key"), "body": body})
|
||||
if "bad-model" in self.path:
|
||||
self.send_response(404); self.send_header("Content-Type", "application/json"); self.end_headers()
|
||||
self.wfile.write(json.dumps({"error": {"message": "models/bad-model is not found"}}).encode()); return
|
||||
image = base64.b64encode(png(300, (182, 91, 60))).decode()
|
||||
reply = {"candidates": [{"content": {"parts": [{"text": "여기 있습니다"}, {"inlineData": {"mimeType": "image/png", "data": image}}]}}]}
|
||||
self.send_response(200); self.send_header("Content-Type", "application/json"); self.end_headers()
|
||||
self.wfile.write(json.dumps(reply).encode())
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
@@ -61,14 +39,9 @@ class SiteAdminTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.temp = tempfile.TemporaryDirectory()
|
||||
cls.fake = http.server.ThreadingHTTPServer(("127.0.0.1", 0), FakeGemini)
|
||||
threading.Thread(target=cls.fake.serve_forever, daemon=True).start()
|
||||
key_file = Path(cls.temp.name) / "gemini.key"
|
||||
key_file.write_text(FAKE_KEY)
|
||||
cls.port = free_port()
|
||||
cls.base = "http://127.0.0.1:%d/calendar/" % cls.port
|
||||
env = {**os.environ, "DUTY_DATA": cls.temp.name, "DUTY_REFRESH": "0", "DUTY_ORIGIN": "http://127.0.0.1:%d" % cls.port, "PYTHONDONTWRITEBYTECODE": "1",
|
||||
"DUTY_GEMINI_URL": "http://127.0.0.1:%d" % cls.fake.server_address[1], "DUTY_GEMINI_KEY_FILE": str(key_file)}
|
||||
env = {**os.environ, "DUTY_DATA": cls.temp.name, "DUTY_REFRESH": "0", "DUTY_ORIGIN": "http://127.0.0.1:%d" % cls.port, "PYTHONDONTWRITEBYTECODE": "1"}
|
||||
# 최초 관리자는 서버 밖에서만 만들 수 있다(공개 가입으로는 관리자가 되지 않는다).
|
||||
boot = "import manage; manage.bootstrap({'username':'adminqa','displayName':'관리자시험','password':'Admin-pass-1'}, must_change=False)"
|
||||
subprocess.run([sys.executable, "-c", boot], cwd=HERE, env=env, check=True, capture_output=True)
|
||||
@@ -92,8 +65,6 @@ class SiteAdminTest(unittest.TestCase):
|
||||
cls.server.terminate()
|
||||
cls.server.wait(10)
|
||||
cls.server.stderr.close()
|
||||
cls.fake.shutdown()
|
||||
cls.fake.server_close()
|
||||
cls.temp.cleanup()
|
||||
|
||||
@classmethod
|
||||
@@ -152,13 +123,20 @@ class SiteAdminTest(unittest.TestCase):
|
||||
self.assertEqual(settings["heroTitle"], "새 제목\n둘째 줄")
|
||||
# 한 줄 항목은 공백을 정리하고 글자 그대로 둔다. 화면에서는 textContent로만 넣는다.
|
||||
self.assertEqual(settings["noticeText"], "점검 안내 <b>")
|
||||
# 앱은 버전 확인 때 공지 띠를 같이 받는다(0.16.0).
|
||||
self.assertEqual(self.call("api/version")[1]["notice"], {"text": "점검 안내 <b>", "tone": "warn"})
|
||||
fields = {field["key"]: field for field in self.call("api/admin/settings", token=self.admin)[1]["fields"]}
|
||||
# 공지 띠 칸은 관리자 '공지' 화면에 그린다.
|
||||
self.assertEqual({fields[key].get("page") for key in ("noticeOn", "noticeTone", "noticeText")}, {"notice"})
|
||||
self.assertTrue(fields["heroTitle"]["custom"])
|
||||
self.assertEqual(fields["heroTitle"]["updatedBy"], "관리자시험")
|
||||
# 기본값과 같은 값을 저장하면 저장 행을 지운다.
|
||||
status, body = self.call("api/admin/settings", {"values": {"heroTitle": "다음 당직,\n달력에서 바로."}}, token=self.admin)
|
||||
self.assertEqual(body["changed"], ["heroTitle"])
|
||||
self.assertFalse({field["key"]: field for field in self.call("api/admin/settings", token=self.admin)[1]["fields"]}["heroTitle"]["custom"])
|
||||
# 끄면 글이 남아 있어도 앱에는 빈 공지를 준다.
|
||||
self.assertEqual(self.call("api/admin/settings", {"values": {"noticeOn": False}}, token=self.admin)[0], 200)
|
||||
self.assertEqual(self.call("api/version")[1]["notice"], {"text": "", "tone": "info"})
|
||||
status, body = self.call("api/admin/settings", {"reset": ["noticeOn", "noticeText", "noticeTone"]}, token=self.admin)
|
||||
self.assertEqual(status, 200)
|
||||
self.assertFalse(self.call("api/site")[1]["settings"]["noticeOn"])
|
||||
@@ -236,7 +214,9 @@ class SiteAdminTest(unittest.TestCase):
|
||||
self.assertEqual(manifest["icons"][0]["src"], "brand/icon-192")
|
||||
state = self.call("api/admin/brand", token=self.admin)[1]
|
||||
self.assertIsNone(state["custom"])
|
||||
self.assertTrue(state["gemini"])
|
||||
# 로고 화면에는 그림을 만드는 기능이 없다. 보관한 그림 목록과 지금 로고만 준다(2026-12-01).
|
||||
self.assertEqual(set(state), {"custom", "candidates"})
|
||||
self.assertEqual(self.call("api/admin/brand-generate", {"prompt": "달력과 초승달 아이콘", "count": 1}, token=self.admin)[0], 404)
|
||||
member = self.login("memberqa", "Member-pass-1")
|
||||
self.assertEqual(self.call("api/admin/brand", token=member)[0], 403)
|
||||
images = {name: base64.b64encode(png(size)).decode() for name, size in (("512", 512), ("192", 192), ("180", 180), ("64", 64), ("maskable", 512))}
|
||||
@@ -256,49 +236,22 @@ class SiteAdminTest(unittest.TestCase):
|
||||
self.assertEqual(self.call("api/admin/brand-logo-reset", {}, token=self.admin)[0], 200)
|
||||
self.assertEqual(self.raw("brand/logo")[1], "image/svg+xml")
|
||||
|
||||
def test_08_gemini_candidates(self):
|
||||
self.assertEqual(self.call("api/admin/brand-generate", {"prompt": "짧음", "count": 1}, token=self.admin)[0], 400)
|
||||
self.assertEqual(self.call("api/admin/brand-generate", {"prompt": "달력과 초승달 아이콘", "count": 9}, token=self.admin)[0], 400)
|
||||
status, body = self.call("api/admin/brand-generate", {"prompt": "달력과 초승달이 있는 앱 아이콘", "model": "gemini-test-image", "count": 2}, token=self.admin)
|
||||
self.assertEqual(status, 200, body)
|
||||
job = self.wait_job(body["job"])
|
||||
self.assertEqual((job["state"], job["made"]), ("done", 2))
|
||||
call = FakeGemini.calls[-1]
|
||||
self.assertEqual(call["key"], FAKE_KEY)
|
||||
self.assertIn("/v1beta/models/gemini-test-image:generateContent", call["path"])
|
||||
self.assertEqual(call["body"]["contents"][0]["parts"][0]["text"], "달력과 초승달이 있는 앱 아이콘")
|
||||
state = self.call("api/admin/brand", token=self.admin)[1]
|
||||
self.assertEqual(len(state["candidates"]), 2)
|
||||
self.assertNotIn(FAKE_KEY, json.dumps(state))
|
||||
first = state["candidates"][0]["id"]
|
||||
status, kind, raw = self.raw("api/admin/brand-candidate/" + first, token=self.admin)
|
||||
self.assertEqual((status, kind), (200, "image/png"))
|
||||
self.assertEqual(self.raw("api/admin/brand-candidate/" + first, token=self.login("memberqa", "Member-pass-1"))[0], 403)
|
||||
self.assertEqual(self.call("api/admin/brand-candidate-delete/" + first, {}, token=self.admin)[0], 200)
|
||||
self.assertEqual(len(self.call("api/admin/brand", token=self.admin)[1]["candidates"]), 1)
|
||||
# 모델 이름이 틀리면 작업이 실패로 끝나고 원인을 알려 준다.
|
||||
job = self.wait_job(self.call("api/admin/brand-generate", {"prompt": "달력과 초승달이 있는 앱 아이콘", "model": "bad-model", "count": 2}, token=self.admin)[1]["job"])
|
||||
self.assertEqual(job["state"], "error")
|
||||
self.assertIn("404", job["errors"][0])
|
||||
actions = {row["action"] for row in self.call("api/admin/log?area=site", token=self.admin)[1]["entries"]}
|
||||
self.assertTrue({"logo", "logo-reset", "logo-generate", "logo-candidate-delete"} <= actions, actions)
|
||||
|
||||
def test_09_import_tool(self):
|
||||
# 서버 밖에서 만든 그림(제미나이 구독 agy 등)을 운영 도구로 후보에 넣고 로고로 적용한다.
|
||||
# 운영 도구로 그림을 '보관한 그림'에 넣고 로고로 적용한 뒤 보관한 그림을 지운다.
|
||||
folder = Path(self.temp.name) / "import"
|
||||
folder.mkdir()
|
||||
(folder / "art.png").write_bytes(png(400, (40, 60, 90)))
|
||||
(folder / "prompt.txt").write_text("달력과 초승달", encoding="utf8")
|
||||
for name, size in (("logo-512.png", 512), ("logo-192.png", 192), ("logo-180.png", 180), ("logo-64.png", 64), ("logo-maskable.png", 512)):
|
||||
(folder / name).write_bytes(png(size, (40, 60, 90)))
|
||||
env = {**os.environ, "DUTY_DATA": self.temp.name}
|
||||
run = lambda *args: subprocess.run([sys.executable, "brand_import.py", *args], cwd=HERE, env=env, capture_output=True, text=True)
|
||||
self.assertNotEqual(run("add-candidate", str(folder / "art.png"), "--actor", "memberqa").returncode, 0)
|
||||
done = run("add-candidate", str(folder / "art.png"), "--prompt-file", str(folder / "prompt.txt"), "--model", "agy 시험", "--actor", "adminqa")
|
||||
done = run("add-candidate", str(folder / "art.png"), "--actor", "adminqa")
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
cid = done.stdout.strip()
|
||||
state = self.call("api/admin/brand", token=self.admin)[1]
|
||||
self.assertIn(cid, [row["id"] for row in state["candidates"]])
|
||||
self.assertEqual(set(state["candidates"][0]), {"id", "created", "actor"})
|
||||
(folder / "logo-64.png").write_bytes(png(32))
|
||||
self.assertNotEqual(run("apply", str(folder), "--candidate", cid, "--actor", "adminqa").returncode, 0)
|
||||
(folder / "logo-64.png").write_bytes(png(64))
|
||||
@@ -307,18 +260,19 @@ class SiteAdminTest(unittest.TestCase):
|
||||
state = self.call("api/admin/brand", token=self.admin)[1]
|
||||
self.assertEqual((state["custom"]["source"], state["custom"]["candidate"], state["custom"]["by"]), ("candidate", cid, "관리자시험"))
|
||||
self.assertEqual(self.raw("brand/favicon")[1], "image/png")
|
||||
actions = [row["action"] for row in self.call("api/admin/log?area=site", token=self.admin)[1]["entries"]]
|
||||
# 두 기록은 같은 초에 남을 수 있어 순서는 보지 않는다(2026-11-25 전체 시험에서 한 번 뒤바뀜).
|
||||
self.assertEqual(set(actions[:2]), {"logo", "logo-import"})
|
||||
entries = self.call("api/admin/log?area=site", token=self.admin)[1]["entries"]
|
||||
# 작업 기록은 초 단위로만 정렬돼 앞선 시험(test_07)의 기록과 같은 초면 순서가 섞인다.
|
||||
# 순서 대신 이번 작업의 내용으로 찾는다(2026-11-25·12-01 전체 시험에서 순서 때문에 실패).
|
||||
self.assertTrue(any(row["action"] == "logo-import" and row["detail"].endswith("art.png") for row in entries), entries[:4])
|
||||
self.assertTrue(any(row["action"] == "logo" and cid in row["detail"] for row in entries), entries[:4])
|
||||
self.assertEqual(self.call("api/admin/brand-logo-reset", {}, token=self.admin)[0], 200)
|
||||
|
||||
def wait_job(self, job_id):
|
||||
for _ in range(100):
|
||||
job = self.call("api/admin/brand-job/" + job_id, token=self.admin)[1]
|
||||
if job["state"] != "running":
|
||||
return job
|
||||
time.sleep(0.1)
|
||||
self.fail("후보 만들기가 끝나지 않았습니다")
|
||||
status, kind, _ = self.raw("api/admin/brand-candidate/" + cid, token=self.admin)
|
||||
self.assertEqual((status, kind), (200, "image/png"))
|
||||
self.assertEqual(self.raw("api/admin/brand-candidate/" + cid, token=self.login("memberqa", "Member-pass-1"))[0], 403)
|
||||
self.assertEqual(self.call("api/admin/brand-candidate-delete/" + cid, {}, token=self.admin)[0], 200)
|
||||
self.assertNotIn(cid, [row["id"] for row in self.call("api/admin/brand", token=self.admin)[1]["candidates"]])
|
||||
entries = self.call("api/admin/log?area=site", token=self.admin)[1]["entries"]
|
||||
self.assertIn("logo-candidate-delete", {row["action"] for row in entries})
|
||||
|
||||
@classmethod
|
||||
def raw(cls, path, token=None):
|
||||
|
||||
@@ -126,3 +126,7 @@ dialog h3{font-size:15px;margin:22px 0 4px}
|
||||
.data-table td.clip{max-width:320px;overflow-wrap:anywhere}
|
||||
.data-table td a{color:var(--ink);font-weight:650}
|
||||
@media(max-width:900px){.head-actions{width:100%}.board-row{flex-direction:column;align-items:flex-start}}
|
||||
/* 공지 화면: 공지 띠 미리보기는 홈페이지 공지 띠와 같은 색 */
|
||||
.card-head{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}.card-head h2{margin-bottom:0}
|
||||
.notice-preview-label{margin-top:14px}.notice-preview{display:flex;align-items:center;gap:10px;margin:6px 0 14px;padding:11px 16px;font-size:13px;line-height:1.6;background:#e9eef5;color:var(--ink);border:1px solid #cfd8e3;border-radius:5px;overflow-wrap:anywhere}.notice-preview::before{content:'';flex:none;width:8px;height:8px;border-radius:50%;background:#365fad}.notice-preview.warn{background:#f8ece5;border-color:#e8cbbb}.notice-preview.warn::before{background:#b65b3c}.notice-preview.off{background:transparent;border-style:dashed;color:var(--muted)}.notice-preview.off::before{background:#c6cbd0}
|
||||
#notice-rows td:first-child{min-width:170px}
|
||||
+21
-8
@@ -8,6 +8,7 @@
|
||||
<a class="side-brand" href="./"><img src="brand/logo" alt="" width="36" height="36"><span><b>당직근무</b><small>관리자</small></span></a>
|
||||
<nav class="side-nav" aria-label="관리 메뉴">
|
||||
<button data-view="overview" class="active"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 13h6V4H4zM14 20h6v-9h-6zM4 20h6v-4H4zM14 7h6V4h-6z"/></svg>현황</button>
|
||||
<button data-view="notice"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 10v4h3l6 4V6L7 10zM16.5 9a4 4 0 0 1 0 6M19 6.5a7.5 7.5 0 0 1 0 11"/></svg>공지</button>
|
||||
<button data-view="members"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM2 21a7 7 0 0 1 14 0M17 11a3 3 0 1 0-1-5.8M22 21a6 6 0 0 0-4-5.7"/></svg>회원</button>
|
||||
<button data-view="companies"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 21V5l8-2v18M12 8l8 2v11M3 21h18M8 9v.01M8 13v.01M8 17v.01M16 13v.01M16 17v.01"/></svg>소속</button>
|
||||
<button data-view="site"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 5h18v14H3zM3 9h18M7 13h6M7 16h4"/></svg>홈페이지</button>
|
||||
@@ -32,6 +33,18 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="view-notice" class="view" hidden>
|
||||
<header class="view-head"><div><p class="eyebrow">공지 관리</p><h1>공지</h1></div><div class="head-actions"><a class="secondary-link" href="./" target="_blank" rel="noopener">홈페이지 열기</a><a class="secondary-link" href="board" target="_blank" rel="noopener">게시판 열기</a></div></header>
|
||||
<section class="card stack"><h2>공지 띠</h2><p class="small">켜 두면 홈페이지 맨 위와 앱 첫 화면에 한 줄로 보입니다. 앱은 0.16.0부터 보이고 다음에 앱을 열 때 바뀝니다.</p>
|
||||
<p class="eyebrow notice-preview-label">미리보기</p><div id="notice-preview" class="notice-preview"></div>
|
||||
<form id="notice-form" class="site-form single compact"></form><button id="notice-save" form="notice-form" type="submit">공지 띠 저장</button></section>
|
||||
<section class="card stack"><div class="card-head"><h2>공지사항 글</h2><button id="notice-new" type="button">새 공지 쓰기</button></div>
|
||||
<p class="small">홈페이지 게시판의 공지사항에 올라갑니다. 누구나 읽을 수 있고 관리자만 씁니다. 고정한 글은 목록 맨 위에 보입니다.</p>
|
||||
<div class="table-wrap"><table class="data-table"><thead><tr><th>제목</th><th>상태</th><th>쓴 때</th><th>관리</th></tr></thead><tbody id="notice-rows"></tbody></table></div>
|
||||
<div class="pager"><button id="notice-prev" class="secondary">이전</button><span id="notice-page"></span><button id="notice-next" class="secondary">다음</button></div>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section id="view-members" class="view" hidden>
|
||||
<header class="view-head"><div><p class="eyebrow">회원 관리</p><h1>회원</h1></div><p id="member-total" class="count"></p></header>
|
||||
<form id="member-filter" class="toolbar"><input id="member-q" type="search" maxlength="40" placeholder="아이디 또는 이름" aria-label="회원 검색"><select id="member-show" aria-label="회원 범위"><option value="all">전체</option><option value="admin">관리자</option><option value="suspended">이용 중지</option><option value="mustChange">비밀번호 변경 필요</option><option value="idle">30일 넘게 미접속</option><option value="company">소속 있음</option></select><select id="member-sort" aria-label="정렬"><option value="created">가입 최신순</option><option value="login">최근 접속순</option><option value="name">이름순</option></select><button type="submit">찾기</button></form>
|
||||
@@ -88,19 +101,13 @@
|
||||
<section class="card"><h2>지금 쓰는 로고</h2>
|
||||
<div class="logo-row"><figure><img id="cur-512" alt="" width="128" height="128"><figcaption>앱 아이콘</figcaption></figure><figure><img id="cur-mask" class="round" alt="" width="96" height="96"><figcaption>둥근 홈 화면</figcaption></figure><figure><img id="cur-logo" class="rounded" alt="" width="40" height="40"><figcaption>홈페이지 로고</figcaption></figure><figure><img id="cur-fav" alt="" width="16" height="16"><figcaption>브라우저 탭</figcaption></figure></div>
|
||||
<p id="brand-source" class="small"></p></section>
|
||||
<div class="two-col">
|
||||
<section class="card"><h2>그림 올리기</h2><p class="small">PNG·JPG·WebP 그림을 고르면 가운데를 정사각형으로 잘라 크기별 아이콘을 만듭니다. 512px 이상인 그림을 권합니다.</p><label>그림 파일<input id="logo-file" type="file" accept="image/png,image/jpeg,image/webp"></label></section>
|
||||
<section class="card"><h2>제미나이로 만들기</h2><p id="gemini-status" class="small"></p>
|
||||
<label>그림 설명<textarea id="gen-prompt" rows="6" maxlength="1500"></textarea></label>
|
||||
<div class="field-row"><label>장수<select id="gen-count"><option value="1">1장</option><option value="2" selected>2장</option><option value="3">3장</option><option value="4">4장</option></select></label><label>모델<input id="gen-model" maxlength="80" autocomplete="off"></label></div>
|
||||
<div class="action-row"><button id="gen-start">후보 만들기</button><button id="gen-default" type="button" class="secondary">기본 설명으로</button></div><p id="gen-progress" class="small" role="status"></p></section>
|
||||
</div>
|
||||
<section class="card"><h2>그림 올리기</h2><p class="small">PNG·JPG·WebP 그림을 고르면 가운데를 정사각형으로 잘라 크기별 아이콘을 만듭니다. 512px 이상인 그림을 권합니다.</p><label>그림 파일<input id="logo-file" type="file" accept="image/png,image/jpeg,image/webp"></label></section>
|
||||
<section id="apply-card" class="card apply-card" hidden><h2>적용 미리보기</h2>
|
||||
<div class="logo-row"><figure><canvas id="pv-512" width="512" height="512"></canvas><figcaption>앱 아이콘</figcaption></figure><figure><canvas id="pv-mask" class="round" width="512" height="512"></canvas><figcaption>둥근 홈 화면</figcaption></figure><figure><canvas id="pv-64" class="rounded" width="64" height="64"></canvas><figcaption>홈페이지 로고</figcaption></figure><figure><canvas id="pv-16" width="16" height="16"></canvas><figcaption>브라우저 탭</figcaption></figure></div>
|
||||
<div class="field-row"><label>확대(가장자리 잘라내기)<input id="apply-zoom" type="range" min="100" max="140" value="100"></label><label>여백<input id="apply-pad" type="range" min="0" max="20" value="0"></label><label>홈 화면 배경색<input id="apply-bg" type="color" value="#26364d"></label></div>
|
||||
<p class="small">둥근 홈 화면과 아이폰 아이콘은 투명한 곳을 배경색으로 채웁니다. 그림 바깥 모서리가 흰색이면 확대로 잘라 내세요(자동으로 맞춰 둡니다).</p>
|
||||
<div class="action-row"><button id="apply-save">이 그림으로 바꾸기</button><button id="apply-cancel" type="button" class="secondary">취소</button></div></section>
|
||||
<section class="card"><h2>제미나이 후보</h2><p class="small">만든 후보는 최근 40장까지 보관합니다. 고르기를 누르면 위 미리보기에서 확인한 뒤 바꿀 수 있습니다.</p><div id="candidate-grid" class="candidate-grid"></div></section>
|
||||
<section class="card"><h2>보관한 그림</h2><p class="small">보관해 둔 로고 그림입니다. 고르기를 누르면 위 미리보기에서 확인한 뒤 바꿀 수 있습니다.</p><div id="candidate-grid" class="candidate-grid"></div></section>
|
||||
</section>
|
||||
|
||||
<section id="view-log" class="view" hidden>
|
||||
@@ -112,6 +119,12 @@
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<dialog id="notice-dialog" class="wide-dialog"><form id="notice-post-form"><div class="dialog-heading"><h2 id="notice-heading">새 공지</h2><button type="button" class="icon-button close" aria-label="닫기">×</button></div>
|
||||
<label>제목<input id="np-title" maxlength="80" required></label>
|
||||
<label>본문<textarea id="np-body" rows="10" maxlength="20000" required></textarea></label>
|
||||
<label id="np-pin-label" class="check-label"><input id="np-pin" type="checkbox">공지사항 맨 위에 고정</label>
|
||||
<p id="np-error" class="form-error" role="alert"></p>
|
||||
<div class="dialog-actions"><button type="button" class="secondary close">취소</button><button id="np-submit" type="submit">올리기</button></div></form></dialog>
|
||||
<dialog id="board-dialog"><form id="board-form"><div class="dialog-heading"><h2 id="board-heading">게시판</h2><button type="button" class="icon-button close" aria-label="닫기">×</button></div>
|
||||
<label>주소 이름 (영어 소문자·숫자·-, 만든 뒤에는 바꿀 수 없음)<input id="bd-id" maxlength="20" pattern="[a-z][a-z0-9-]{1,19}" required></label>
|
||||
<label>게시판 이름<input id="bd-name" maxlength="20" required></label>
|
||||
|
||||
+94
-41
@@ -112,7 +112,7 @@ async function start() {
|
||||
const view = (location.hash || '#overview').slice(1);
|
||||
show(Object.keys(loaders).includes(view) ? view : 'overview');
|
||||
}
|
||||
const loaders = { overview: loadOverview, members: loadMembers, companies: loadCompanies, site: loadSite, guide: loadGuide, board: loadBoard, brand: loadBrand, log: loadLog };
|
||||
const loaders = { overview: loadOverview, notice: loadNotice, members: loadMembers, companies: loadCompanies, site: loadSite, guide: loadGuide, board: loadBoard, brand: loadBrand, log: loadLog };
|
||||
function show(view) {
|
||||
document.querySelectorAll('.view').forEach(section => { section.hidden = section.id !== 'view-' + view; });
|
||||
document.querySelectorAll('.side-nav button').forEach(button => button.classList.toggle('active', button.dataset.view === view));
|
||||
@@ -384,8 +384,8 @@ $('cd-revoke').onclick = () => companyAction({ action: 'revoke-invite' }, '지
|
||||
$('cd-delete').onclick = () => companyAction({ action: 'delete-company' }, state.editingCompany.name + ' 소속을 삭제할까요? 구성원 연결과 교환·인수인계 기록이 지워집니다. 회원과 개인 달력은 남습니다.', '소속 삭제', true);
|
||||
|
||||
// ------------------------------------------------------------ 홈페이지 설정
|
||||
// 설정 칸은 서버의 SITE_FIELDS가 정한다. page(site 홈페이지 · guide 연동 안내 · board 게시판)마다 다른 화면에 그린다.
|
||||
const SETTING_FORMS = { 'site-form': 'site', 'guide-form': 'guide', 'board-settings-form': 'board' };
|
||||
// 설정 칸은 서버의 SITE_FIELDS가 정한다. page(site 홈페이지 · notice 공지 · guide 연동 안내 · board 게시판)마다 다른 화면에 그린다.
|
||||
const SETTING_FORMS = { 'site-form': 'site', 'notice-form': 'notice', 'guide-form': 'guide', 'board-settings-form': 'board' };
|
||||
async function loadSettings(formId) {
|
||||
const data = await api('admin/settings');
|
||||
state.fields = data.fields;
|
||||
@@ -435,7 +435,7 @@ function fieldControl(field) {
|
||||
}
|
||||
input.id = id;
|
||||
input.dataset.key = field.key;
|
||||
const update = () => { markChanged(field); if ((field.page || 'site') === 'site') preview(); };
|
||||
const update = () => { markChanged(field); const page = field.page || 'site'; if (page === 'site') preview(); if (page === 'notice') noticePreview(); };
|
||||
input.addEventListener('input', update);
|
||||
input.addEventListener('change', update);
|
||||
const wrap = el('div', null, 'field' + (field.kind === 'longtext' ? ' long' : ''));
|
||||
@@ -518,14 +518,96 @@ async function saveSettings(formId, button) {
|
||||
button.disabled = true;
|
||||
try {
|
||||
const result = await api('admin/settings', { values: changed });
|
||||
notify(result.changed.length ? result.changed.length + '개 항목을 저장했습니다. 홈페이지에 바로 반영됩니다.' : '바뀐 항목이 없습니다.');
|
||||
const where = page === 'notice' ? '홈페이지는 바로 바뀌고 앱은 다음에 열 때 바뀝니다.' : '홈페이지에 바로 반영됩니다.';
|
||||
notify(result.changed.length ? result.changed.length + '개 항목을 저장했습니다. ' + where : '바뀐 항목이 없습니다.');
|
||||
reloadCurrent();
|
||||
} catch (error) { failed(error); } finally { button.disabled = false; }
|
||||
}
|
||||
$('site-form').onsubmit = event => { event.preventDefault(); saveSettings('site-form', $('site-save')); };
|
||||
$('notice-form').onsubmit = event => { event.preventDefault(); saveSettings('notice-form', $('notice-save')); };
|
||||
$('guide-form').onsubmit = event => { event.preventDefault(); saveSettings('guide-form', $('guide-save')); };
|
||||
$('board-settings-form').onsubmit = event => { event.preventDefault(); saveSettings('board-settings-form', $('board-settings-save')); };
|
||||
|
||||
// ------------------------------------------------------------ 공지
|
||||
// 공지 띠는 SITE_FIELDS의 notice 칸이다. 공지사항 글은 게시판 'notice'에 쓰고 게시판 API를 그대로 쓴다.
|
||||
const NOTICE_BOARD = 'notice';
|
||||
const noticeState = { page: 1, editing: null };
|
||||
async function loadNotice() {
|
||||
try { await loadSettings('notice-form'); } catch (error) { failed(error); return; }
|
||||
noticePreview();
|
||||
loadNoticePosts();
|
||||
}
|
||||
function noticePreview() {
|
||||
const values = {};
|
||||
for (const field of state.fields) values[field.key] = readField(field);
|
||||
const text = String(values.noticeText || '').trim();
|
||||
const box = $('notice-preview');
|
||||
box.classList.toggle('warn', values.noticeTone === 'warn');
|
||||
box.classList.toggle('off', !(values.noticeOn && text));
|
||||
box.textContent = values.noticeOn && text ? text : (text ? '꺼져 있어 보이지 않습니다.' : '공지 내용이 비어 있습니다.');
|
||||
}
|
||||
async function loadNoticePosts() {
|
||||
let data;
|
||||
try { data = await api('admin/board-posts?board=' + NOTICE_BOARD + '&state=all&page=' + noticeState.page); } catch (error) { failed(error); return; }
|
||||
pager('notice', data.page, data.total, data.pageSize);
|
||||
const body = $('notice-rows');
|
||||
if (!data.posts.length) { emptyRow(body, 4, '아직 올린 공지사항 글이 없습니다.'); return; }
|
||||
body.replaceChildren();
|
||||
for (const row of data.posts) {
|
||||
const tr = el('tr');
|
||||
const title = el('td'); const link = el('a', row.title); link.href = 'board#/p/' + row.id; link.target = '_blank'; link.rel = 'noopener'; title.append(link);
|
||||
if (row.pinned) title.append(' ', badge('고정', 'admin'));
|
||||
const stateCell = el('td'); stateCell.append(badge(...STATE_BADGES[row.state]));
|
||||
const tools = el('td', null, 'row-tools');
|
||||
const act = (label, action, ask) => { const b = el('button', label, 'secondary'); b.type = 'button'; b.onclick = async () => {
|
||||
if (ask && !await confirmAction(ask, label)) return;
|
||||
try { await api('admin/board-post/' + row.id, { action }); notify(DONE_MESSAGES[action]); loadNoticePosts(); } catch (error) { failed(error); }
|
||||
}; tools.append(b); };
|
||||
if (row.state !== 'deleted') { const edit = el('button', '고치기', 'secondary'); edit.type = 'button'; edit.onclick = () => openNoticeEditor(row); tools.append(edit); }
|
||||
act(row.pinned ? '고정 해제' : '고정', row.pinned ? 'unpin' : 'pin');
|
||||
if (row.state === 'open') { act('숨기기', 'hide'); act('지우기', 'delete', '"' + row.title + '" 공지를 지울까요? 목록에서 빠지고 나중에 되살릴 수 있습니다.'); }
|
||||
else act(row.state === 'hidden' ? '다시 보이기' : '되살리기', row.state === 'hidden' ? 'show' : 'restore');
|
||||
tr.append(title, stateCell, el('td', when(row.created)), tools);
|
||||
body.append(tr);
|
||||
}
|
||||
}
|
||||
async function openNoticeEditor(row) {
|
||||
noticeState.editing = row ? row.id : null;
|
||||
$('notice-heading').textContent = row ? '공지 고치기' : '새 공지';
|
||||
$('np-submit').textContent = row ? '저장' : '올리기';
|
||||
$('np-error').textContent = '';
|
||||
$('np-title').value = ''; $('np-body').value = ''; $('np-pin').checked = false;
|
||||
$('np-pin-label').hidden = Boolean(row);
|
||||
if (row) {
|
||||
try { const data = await api('posts/' + row.id); $('np-title').value = data.post.title; $('np-body').value = data.post.body; } catch (error) { failed(error); return; }
|
||||
}
|
||||
$('notice-dialog').showModal();
|
||||
$('np-title').focus();
|
||||
}
|
||||
$('notice-new').onclick = () => openNoticeEditor(null);
|
||||
$('notice-post-form').onsubmit = async event => {
|
||||
event.preventDefault();
|
||||
const title = $('np-title').value.trim(), body = $('np-body').value.trim();
|
||||
if (!title || !body) { $('np-error').textContent = '제목과 본문을 써 주세요.'; return; }
|
||||
const editing = noticeState.editing;
|
||||
$('np-submit').disabled = true;
|
||||
try {
|
||||
if (editing) await api('posts/' + editing, { action: 'edit', title, body });
|
||||
else {
|
||||
const result = await api('boards/' + NOTICE_BOARD + '/posts', { title, body });
|
||||
if ($('np-pin').checked) await api('admin/board-post/' + result.id, { action: 'pin' });
|
||||
}
|
||||
$('notice-dialog').close();
|
||||
notify(editing ? '공지를 고쳤습니다.' : '공지를 올렸습니다.');
|
||||
if (!editing) noticeState.page = 1;
|
||||
loadNoticePosts();
|
||||
} catch (error) {
|
||||
if (error.status === 401) failed(error); else $('np-error').textContent = error.message;
|
||||
} finally { $('np-submit').disabled = false; }
|
||||
};
|
||||
$('notice-prev').onclick = () => { noticeState.page--; loadNoticePosts(); };
|
||||
$('notice-next').onclick = () => { noticeState.page++; loadNoticePosts(); };
|
||||
|
||||
// ------------------------------------------------------------ 게시판
|
||||
const boardState = { boards: [], levels: null, post: { page: 1 }, comment: { page: 1 }, editing: null };
|
||||
const DONE_MESSAGES = { pin: '맨 위에 고정했습니다.', unpin: '고정을 풀었습니다.', hide: '숨겼습니다.', show: '다시 보이게 했습니다.', delete: '지웠습니다. 나중에 되살릴 수 있습니다.', restore: '되살렸습니다.' };
|
||||
@@ -650,7 +732,7 @@ $('comment-next').onclick = () => { boardState.comment.page++; loadComments(); }
|
||||
|
||||
// ------------------------------------------------------------ 로고 그림
|
||||
// 크기별 PNG는 이 브라우저에서 만든다. 서버는 PNG 형식과 크기만 확인해 보관한다.
|
||||
const brandState = { image: null, source: null, candidate: null, polling: null, defaults: {} };
|
||||
const brandState = { image: null, source: null, candidate: null };
|
||||
function refreshLogos() {
|
||||
const stamp = '?t=' + Date.now();
|
||||
document.querySelectorAll('img[src^="brand/logo"]').forEach(img => { img.src = 'brand/logo' + stamp; });
|
||||
@@ -662,32 +744,26 @@ function refreshLogos() {
|
||||
async function loadBrand() {
|
||||
let data;
|
||||
try { data = await api('admin/brand'); } catch (error) { failed(error); return; }
|
||||
brandState.defaults = { prompt: data.defaultPrompt, model: data.defaultModel };
|
||||
refreshLogos();
|
||||
const c = data.custom;
|
||||
$('brand-source').textContent = c ? (c.source === 'upload' ? '올린 그림' : '제미나이 후보') + ' · ' + c.by + ' · ' + when(c.updated) : '기본 로고(달력과 초승달)를 쓰고 있습니다.';
|
||||
$('brand-source').textContent = c ? (c.source === 'upload' ? '올린 그림' : '보관한 그림') + ' · ' + c.by + ' · ' + when(c.updated) : '기본 로고(달력과 초승달)를 쓰고 있습니다.';
|
||||
$('brand-reset').disabled = !c;
|
||||
$('gemini-status').textContent = data.gemini ? '제미나이 API 키가 설정돼 있습니다. 설명을 고쳐 바로 후보를 만들 수 있습니다(장당 비용).' : 'API 키 없이 운영합니다. 제미나이 후보는 운영자가 메인 서버의 제미나이 구독(agy)으로 만들어 아래 목록에 넣습니다. API 키를 넣으면 이 버튼으로도 바로 만들 수 있지만 장당 비용이 듭니다.';
|
||||
$('gen-start').disabled = !data.gemini || Boolean(brandState.polling);
|
||||
if (!$('gen-prompt').value) $('gen-prompt').value = data.defaultPrompt;
|
||||
if (!$('gen-model').value) $('gen-model').value = data.defaultModel;
|
||||
const grid = $('candidate-grid');
|
||||
grid.replaceChildren();
|
||||
for (const row of data.candidates) {
|
||||
const card = el('div', null, 'candidate');
|
||||
const img = el('img'); img.alt = '로고 후보'; img.loading = 'lazy'; img.src = 'api/admin/brand-candidate/' + row.id;
|
||||
const img = el('img'); img.alt = '보관한 로고 그림'; img.loading = 'lazy'; img.src = 'api/admin/brand-candidate/' + row.id;
|
||||
const pick = el('button', '고르기'); pick.onclick = () => openApply('api/admin/brand-candidate/' + row.id, 'candidate', row.id);
|
||||
const remove = el('button', '지우기', 'secondary');
|
||||
remove.onclick = async () => {
|
||||
if (!await confirmAction('이 후보 그림을 지울까요?', '지우기')) return;
|
||||
if (!await confirmAction('이 그림을 보관한 그림에서 지울까요?', '지우기')) return;
|
||||
try { await api('admin/brand-candidate-delete/' + row.id, {}); loadBrand(); } catch (error) { failed(error); }
|
||||
};
|
||||
const actions = el('div', null, 'action-row'); actions.append(pick, remove);
|
||||
card.append(img, el('p', when(row.created) + ' · ' + row.model + ' · ' + row.prompt), actions);
|
||||
card.append(img, el('p', when(row.created) + (row.actor ? ' · ' + row.actor : '')), actions);
|
||||
grid.append(card);
|
||||
}
|
||||
if (!data.candidates.length) grid.append(el('p', '아직 만든 후보가 없습니다.', 'small'));
|
||||
if (data.running.length && !brandState.polling) pollJob(data.running[0].id);
|
||||
if (!data.candidates.length) grid.append(el('p', '보관한 그림이 없습니다.', 'small'));
|
||||
}
|
||||
function loadImage(src) {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -697,7 +773,7 @@ function loadImage(src) {
|
||||
img.src = src;
|
||||
});
|
||||
}
|
||||
// 제미나이 그림처럼 둥근 사각형 바깥 모서리가 흰색이면 모서리와 가장자리 가운데 색이 다르다.
|
||||
// 둥근 사각형 그림의 바깥 모서리가 흰색이면 모서리와 가장자리 가운데 색이 다르다.
|
||||
// 그때는 16% 확대해 모서리를 잘라 내고 배경색은 가장자리 가운데 색으로 맞춘다.
|
||||
function autoFit(img) {
|
||||
const canvas = document.createElement('canvas'); canvas.width = canvas.height = 100;
|
||||
@@ -795,29 +871,6 @@ $('brand-reset').onclick = async () => {
|
||||
if (!await confirmAction('올린 로고를 지우고 기본 로고(달력과 초승달)로 되돌릴까요?', '기본 로고로')) return;
|
||||
try { await api('admin/brand-logo-reset', {}); notify('기본 로고로 되돌렸습니다.'); loadBrand(); } catch (error) { failed(error); }
|
||||
};
|
||||
$('gen-default').onclick = () => { $('gen-prompt').value = brandState.defaults.prompt || ''; $('gen-model').value = brandState.defaults.model || ''; };
|
||||
$('gen-start').onclick = async () => {
|
||||
const count = Number($('gen-count').value);
|
||||
try {
|
||||
const result = await api('admin/brand-generate', { prompt: $('gen-prompt').value.trim(), model: $('gen-model').value.trim(), count });
|
||||
pollJob(result.job);
|
||||
} catch (error) { failed(error); }
|
||||
};
|
||||
function pollJob(id) {
|
||||
$('gen-start').disabled = true;
|
||||
$('gen-progress').textContent = '제미나이가 후보를 만드는 중입니다. 한 장에 10~40초쯤 걸립니다.';
|
||||
clearInterval(brandState.polling);
|
||||
brandState.polling = setInterval(async () => {
|
||||
let job;
|
||||
try { job = await api('admin/brand-job/' + id); } catch (error) { clearInterval(brandState.polling); brandState.polling = null; $('gen-progress').textContent = error.message; $('gen-start').disabled = false; return; }
|
||||
$('gen-progress').textContent = job.count + '장 중 ' + job.made + '장 완료' + (job.errors.length ? ' · 실패: ' + job.errors[job.errors.length - 1] : '');
|
||||
if (job.state !== 'running') {
|
||||
clearInterval(brandState.polling); brandState.polling = null;
|
||||
if (job.state === 'done') notify(job.made + '장을 만들었습니다. 아래 후보에서 고르세요.');
|
||||
loadBrand();
|
||||
}
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ 작업 기록
|
||||
async function loadLog() {
|
||||
|
||||
+15
-5
@@ -13,7 +13,10 @@ function applyShiftNames(){const name='';labels.REGULAR=name||DEFAULT_REGULAR;re
|
||||
// 근무 순서에 넣은 이름을 달력에 어떻게 보일지(근무만 · 이름만 · 둘 다). 이름이 없는 날은 근무가 보인다.
|
||||
function slotView(key){const r=rotation(),display=displaySettings(),shift=shiftOn(key);if(!shift)return {shift:'',name:'',shiftKey:null,hidden:false};const name=r?WorkPlan.nameOn(r,key):'',mode=WorkPlan.nameModeOn(r,key,display.nameDisplay||'both'),label=shift==='REGULAR'?regularShort:labels[shift],hidden=shift==='REGULAR'&&display.hideRegular===true;
|
||||
if(name&&mode==='name')return {shift:'',name,shiftKey:shift,hidden:false,only:true};return {shift:label,name:name&&mode==='both'?name:'',shiftKey:shift,hidden};}
|
||||
function slotTitle(key){const shift=shiftOn(key);if(!shift)return '';const r=rotation(),name=r?WorkPlan.nameOn(r,key):'',mode=WorkPlan.nameModeOn(r,key,displaySettings().nameDisplay||'both');return name&&mode!=='shift'?labels[shift]+'('+name+')':labels[shift];}
|
||||
// 그날 당직자 이름(근무 순서 이름). 근무만 고른 줄이나 이름이 없으면 빈 글자. 앱 ShiftNames.dutyName과 같다.
|
||||
// 2026-11-26 사용자 지시: '오늘은 비번(이정훈)'처럼 괄호로 붙이지 않고 '오늘은 비번' 아래에 '당직자 이정훈'으로 보인다.
|
||||
function dutyName(key){const shift=shiftOn(key);if(!shift)return '';const r=rotation(),name=r?WorkPlan.nameOn(r,key):'',mode=WorkPlan.nameModeOn(r,key,displaySettings().nameDisplay||'both');return name&&mode!=='shift'?name:'';}
|
||||
function dutyLine(key){const name=dutyName(key);return name?'당직자 '+name:'';}
|
||||
// 근무 순서 이름 창의 줄 이름: 내 당직 기준 +1 · 비번, +2 · 일반근무. 다음 당직 전날의 (-1)은 헷갈려서 넣지 않는다. 앱 ShiftNames.relativeLabel과 같다.
|
||||
function relativeLabel(pattern,index){const size=pattern.length,title=labels[pattern[index]];if(!pattern.includes('DUTY'))return (index+1)+'일째 · '+title;let after=1;while(pattern[((index-after)%size+size)%size]!=='DUTY')after++;return '+'+after+' · '+title;}
|
||||
function cleanSlotName(value){return String(value??'').trim().split(/\s+/).filter(Boolean).join(' ');}
|
||||
@@ -38,7 +41,7 @@ function siteDefaults(){const s=window.dutySiteSettings||{};return {dutyAsWeekda
|
||||
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일제로 읽는다.
|
||||
// 주5일제·주6일제는 토요일 날짜 색만 바꾼다. 자료에 기준이 없으면 기존 주6일제로 읽는다.
|
||||
function shiftFor(data,key){
|
||||
return WorkPlan.shift(data,key);
|
||||
}
|
||||
@@ -115,15 +118,16 @@ function render(){
|
||||
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?'오늘은 '+slotTitle(today):'근무표를 설정해 주세요';
|
||||
$('today-duty').textContent=current?'오늘은 '+labels[current]:'근무표를 설정해 주세요';
|
||||
$('today-name').textContent=current?dutyLine(today):'';$('today-name').hidden=!$('today-name').textContent;
|
||||
$('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':'')+(WorkPlan.fullLeave(shift)?' leave-red':shift==='HALF_LEAVE'?' half-blue':'');button.setAttribute('aria-label',`${key} ${shift?slotTitle(key):''} ${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){const view=slotView(key);if(view.only)button.append(text('span',view.name,'shift slot-only '+classes[shift]));else{button.append(text('span',view.shift,'shift '+classes[shift]+(view.hidden?' is-hidden':'')));if(view.name)button.append(text('span',view.name,'slot-name'));}}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=[slotTitle(selected),holiday(selected)].filter(Boolean).join(' · ')||'등록한 일정을 확인하고 새로 추가하세요.';
|
||||
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':'')+(WorkPlan.fullLeave(shift)?' leave-red':shift==='HALF_LEAVE'?' half-blue':'');button.setAttribute('aria-label',`${key} ${shift?labels[shift]+' '+dutyLine(key):''} ${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){const view=slotView(key);if(view.only)button.append(text('span',view.name,'shift slot-only '+classes[shift]));else{button.append(text('span',view.shift,'shift '+classes[shift]+(view.hidden?' is-hidden':'')));if(view.name)button.append(text('span',view.name,'slot-name'));}}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);{const first=[shiftOn(selected)?labels[shiftOn(selected)]:'',holiday(selected)].filter(Boolean).join(' · '),duty=dutyLine(selected);$('day-detail').replaceChildren(text('span',first||(duty?'':'등록한 일정을 확인하고 새로 추가하세요.')));if(duty)$('day-detail').append(text('span',duty,'day-duty'));}
|
||||
$('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();
|
||||
@@ -140,6 +144,12 @@ $('event-delete').onclick=async()=>{if(await confirmAction('이 일정을 삭제
|
||||
$('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();};
|
||||
// 열어 둔 채 날짜가 바뀌면 보던 달과 고른 날이 그 전 오늘이었을 때 새 오늘로 옮긴다(2026-12-01: 12월 1일인데 11월 달력이 보이던 문제).
|
||||
let shownDay=selected;
|
||||
function followToday(){const today=todayKey();if(today===shownDay)return false;if(month===shownDay.slice(0,7))month=today.slice(0,7);if(selected===shownDay)selected=today;shownDay=today;return true;}
|
||||
setInterval(()=>{if(followToday())render();},30000);
|
||||
document.addEventListener('visibilitychange',()=>{if(!document.hidden&&followToday())render();});
|
||||
window.addEventListener('focus',()=>{if(followToday())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;}// 근무 순서 이름은 따로 된 창에서 넣는다. 순서 길이가 그대로면 넣어 둔 이름을 남기고 바뀌면 비운다.
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
'use strict';
|
||||
// 구독 주소는 사용자가 만든 직후에만 표시한다. 저장된 비밀 주소를 다시 조회하는 기능은 두지 않는다.
|
||||
document.addEventListener('DOMContentLoaded',()=>{
|
||||
const chosen=()=>Object.fromEntries(['rotation','events','anniversaries','names','notes','skipRegular'].map(key=>[key,$('share-'+key).checked]));
|
||||
// 근무 순서 이름 칸(nameWork·nameOff·nameRest·nameAway)은 기본 꺼짐이다. 예전 구독에 값이 없으면 이름 없이 보낸다(2026-11-26 사용자 지시).
|
||||
const shareKeys=['rotation','events','anniversaries','names','notes','skipRegular','nameWork','nameOff','nameRest','nameAway'];
|
||||
const chosen=()=>Object.fromEntries(shareKeys.map(key=>[key,$('share-'+key).checked]));
|
||||
let enabled=false;
|
||||
async function openSharing(){
|
||||
$('share-error').textContent='';$('share-address-box').hidden=true;$('share-address').value='';$('calendar-sharing-dialog').showModal();
|
||||
try{const result=await api('calendar-sharing');enabled=result.enabled;for(const key of ['rotation','events','anniversaries','names','notes','skipRegular'])$('share-'+key).checked=result.options?result.options[key]===true:key==='rotation';$('share-state').textContent=enabled?'구독 주소 사용 중 · 항목만 바꾸면 주소는 그대로이고 다시 만들면 이전 주소는 종료됩니다.':'구독 주소를 아직 만들지 않았습니다.';$('share-disable').hidden=!enabled;$('share-update').hidden=!enabled;}
|
||||
try{const result=await api('calendar-sharing');enabled=result.enabled;for(const key of shareKeys)$('share-'+key).checked=result.options?result.options[key]===true:key==='rotation';$('share-state').textContent=enabled?'구독 주소 사용 중 · 항목만 바꾸면 주소는 그대로이고 다시 만들면 이전 주소는 종료됩니다.':'구독 주소를 아직 만들지 않았습니다.';$('share-disable').hidden=!enabled;$('share-update').hidden=!enabled;}
|
||||
catch(error){$('share-error').textContent=error.message;}
|
||||
}
|
||||
$('calendar-sharing-open').onclick=openSharing;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<main>
|
||||
<section id="welcome" class="welcome">
|
||||
<div class="welcome-hero">
|
||||
<div class="welcome-copy"><p class="eyebrow" data-site="heroEyebrow">당직 · 교대근무 · 개인 일정</p><h1 data-site="heroTitle">다음 당직,<br>달력에서 바로.</h1><p class="intro" data-site="heroIntro">내 근무 순서대로 채워지는 달력.<br>휴대폰을 켜면 홈 화면에서 바로 확인하세요.</p><div class="welcome-actions"><a class="download-button" data-site-href="downloadUrl" href="https://forum.itosm.co.kr/c/web-apps/duty-calendar/47"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3v12m-5-5 5 5 5-5M5 16v5h14v-5"/></svg><span data-site="downloadLabel">안드로이드 앱 받기</span></a><a class="install-link" href="#install-guide">설치 안내</a></div><p class="download-meta"><a data-site-href="downloadUrl" href="https://forum.itosm.co.kr/c/web-apps/duty-calendar/47">공식 배포 · 소스 · 제작 매뉴얼</a><br>Android 8.0 이상 · 미리보기 0.15.7</p><div class="welcome-caption"><strong data-site="captionTitle">내 달력은 로그인 없이.</strong><p data-site="captionText">함께 보는 근무표와 소속 공유는 <br>회원 로그인 후 이용할 수 있습니다.</p></div></div>
|
||||
<div class="welcome-copy"><p class="eyebrow" data-site="heroEyebrow">당직 · 교대근무 · 개인 일정</p><h1 data-site="heroTitle">다음 당직,<br>달력에서 바로.</h1><p class="intro" data-site="heroIntro">내 근무 순서대로 채워지는 달력.<br>휴대폰을 켜면 홈 화면에서 바로 확인하세요.</p><div class="welcome-actions"><a class="download-button" data-site-href="downloadUrl" href="https://forum.itosm.co.kr/c/web-apps/duty-calendar/47"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3v12m-5-5 5 5 5-5M5 16v5h14v-5"/></svg><span data-site="downloadLabel">안드로이드 앱 받기</span></a><a class="install-link" href="#install-guide">설치 안내</a></div><p class="download-meta"><a data-site-href="downloadUrl" href="https://forum.itosm.co.kr/c/web-apps/duty-calendar/47">공식 배포 · 소스 · 제작 매뉴얼</a><br>Android 8.0 이상 · 미리보기 0.16.1</p><div class="welcome-caption"><strong data-site="captionTitle">내 달력은 로그인 없이.</strong><p data-site="captionText">함께 보는 근무표와 소속 공유는 <br>회원 로그인 후 이용할 수 있습니다.</p></div></div>
|
||||
<figure class="calendar-preview" aria-label="3당직근무 화면 예시">
|
||||
<figcaption><span>홈 화면에 두는 나의 근무표</span><span>화면 예시</span></figcaption>
|
||||
<div class="calendar-paper"><div class="paper-heading"><div><span class="paper-year">2026</span><strong>11<span>월</span></strong></div><div class="paper-note"><b>당직근무</b><span>당직 · 비번 · 일반근무</span></div></div><div class="sample-week"><span>일</span><span>월</span><span>화</span><span>수</span><span>목</span><span>금</span><span>토</span></div><div class="sample-grid"><div class="sample-day sun"><span>1</span><em class="off">비번</em></div><div class="sample-day"><span>2</span><em class="regular">일반</em></div><div class="sample-day"><span>3</span><em class="duty">당직</em></div><div class="sample-day"><span>4</span><em class="off">비번</em></div><div class="sample-day"><span>5</span><em class="regular">일반</em></div><div class="sample-day"><span>6</span><em class="duty">당직</em></div><div class="sample-day sat"><span>7</span><em class="off">비번</em></div><div class="sample-day sun"><span>8</span><em class="regular">일반</em></div><div class="sample-day"><span>9</span><em class="duty">당직</em></div><div class="sample-day"><span>10</span><em class="off">비번</em></div><div class="sample-day"><span>11</span><em class="regular">일반</em></div><div class="sample-day"><span>12</span><em class="duty">당직</em></div><div class="sample-day"><span>13</span><em class="off">비번</em></div><div class="sample-day sat"><span>14</span><em class="regular">일반</em></div><div class="sample-day sun"><span>15</span><em class="duty">당직</em></div><div class="sample-day"><span>16</span><em class="off">비번</em></div><div class="sample-day"><span>17</span><em class="regular">일반</em></div><div class="sample-day"><span>18</span><em class="duty">당직</em></div><div class="sample-day"><span>19</span><em class="off">비번</em></div><div class="sample-day"><span>20</span><em class="regular">일반</em></div><div class="sample-day sat picked"><span>21</span><em class="duty">당직</em></div><div class="sample-day sun"><span>22</span><em class="off">비번</em></div><div class="sample-day"><span>23</span><em class="regular">일반</em></div><div class="sample-day"><span>24</span><em class="duty">당직</em></div><div class="sample-day"><span>25</span><em class="off">비번</em></div><div class="sample-day"><span>26</span><em class="regular">일반</em></div><div class="sample-day"><span>27</span><em class="duty">당직</em></div><div class="sample-day sat"><span>28</span><em class="off">비번</em></div><div class="sample-day sun"><span>29</span><em class="regular">일반</em></div><div class="sample-day"><span>30</span><em class="duty">당직</em></div><div class="sample-day empty-day" aria-hidden="true"></div><div class="sample-day empty-day" aria-hidden="true"></div><div class="sample-day empty-day" aria-hidden="true"></div><div class="sample-day empty-day" aria-hidden="true"></div><div class="sample-day empty-day" aria-hidden="true"></div></div><div class="paper-footer"><span><i></i>선택한 날 · 11월 21일 당직</span><span>3일 반복</span></div></div>
|
||||
@@ -19,7 +19,7 @@
|
||||
<section id="workspace" hidden>
|
||||
<p id="calendar-sharing-hint" class="settings-note" hidden>달력 구독 주소는 옵션 → 달력 연동·공유에서 만들 수 있습니다.</p>
|
||||
<div class="page-heading"><div><div class="eyebrow">근무와 일정</div><h1>나의 달력</h1></div><button id="add">일정 추가</button></div>
|
||||
<div class="summary-row"><article class="today-card"><div id="today-date" class="small"></div><h2 id="today-duty"></h2><p id="today-caption"></p></article><article class="month-summary"><span class="small">이번 달의 일정</span><strong id="month-count">0</strong><span id="rotation-label"></span><div class="settings-actions"><button id="work-management-open" class="secondary">근무 관리</button><button id="rotation" class="text-button">당직 기초 설정</button><button id="display-options" class="secondary">옵션</button></div></article></div>
|
||||
<div class="summary-row"><article class="today-card"><div id="today-date" class="small"></div><h2 id="today-duty"></h2><p id="today-name" class="today-name" hidden></p><p id="today-caption"></p></article><article class="month-summary"><span class="small">이번 달의 일정</span><strong id="month-count">0</strong><span id="rotation-label"></span><div class="settings-actions"><button id="work-management-open" class="secondary">근무 관리</button><button id="rotation" class="text-button">당직 기초 설정</button><button id="display-options" class="secondary">옵션</button></div></article></div>
|
||||
<section id="company-start" class="company-start" hidden><div><h2>함께 일하는 사람들</h2><p>소속을 만들거나 초대코드로 가입하세요. 본인의 근무표만 공유합니다.</p></div><button id="company-start-open">소속 만들기·가입</button></section>
|
||||
<div class="calendar-layout"><section class="calendar-card"><div class="month-heading"><h2 id="month"></h2><div class="month-controls"><button id="prev" class="icon-button" aria-label="이전 달"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="m15 5-7 7 7 7"/></svg></button><button id="today" class="secondary">오늘</button><button id="next" class="icon-button" aria-label="다음 달"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="m9 5 7 7-7 7"/></svg></button></div></div><div class="week" id="calendar-weekdays"><span>일</span><span>월</span><span>화</span><span>수</span><span>목</span><span>금</span><span>토</span></div><div id="grid" class="grid"></div><div class="legend"><span class="duty">당직</span><span class="off">비번</span><span class="regular">일반근무</span><span class="shift daytime">주간</span><span class="shift evening">오후</span><span class="shift night">야간</span><span class="shift rest">휴무</span><span>공휴일에도 근무 순서는 유지됩니다.</span></div></section><aside class="agenda-card"><div class="agenda-heading"><div><span class="small">선택한 날짜</span><h2 id="selected-date"></h2></div><button id="day-add" class="text-button">추가</button></div><p id="day-detail"></p><button id="parttime-add" class="secondary parttime-add">알바·시간근무 추가</button><div id="agenda"></div><section class="anniversary-panel"><div class="agenda-heading"><h3>내 생일·기념일</h3><button id="anniversary-open" class="text-button">관리</button></div><p class="small">양력·음력 매년 반복 · 내 계정에 보관</p><p class="small">서버 저장 완료 후 같은 계정으로 로그인하면 재설치해도 복원됩니다.</p></section><section class="people-panel"><div class="agenda-heading"><h3>함께 보는 근무표</h3><button id="person-add" class="text-button">사람 추가</button></div><p class="small">선택한 날짜의 근무 · 이름을 눌러 수정</p><div id="people-list"></div></section><div id="conflict-notice" hidden><strong>동시에 수정된 일정이 있습니다.</strong><p>작성한 내용은 보관 중입니다. 저장할 내용을 선택해 주세요.</p><button id="resolve">내용 비교</button></div></aside></div>
|
||||
<p class="source-note">공휴일 자료: holidays-kr · <a href="assets/holidays-LICENSE.txt">이용 조건</a> · <a href="assets/lunar-LICENSE.txt">한국 음력 자료 이용 조건</a><span id="holiday-note"></span></p>
|
||||
@@ -34,7 +34,7 @@
|
||||
<dialog id="calendar-sharing-dialog"><div class="dialog-heading"><h2>달력 연동·공유</h2><button class="icon-button close" aria-label="닫기">×</button></div>
|
||||
<section class="settings-note"><h3>휴대폰 기본 달력</h3><p>안드로이드 앱 → 설정 → 달력 연동·공유 → 기본 달력에 자동 반영에서 대상 달력을 고르세요. 위젯 없이 기본 달력에 근무와 일정을 표시합니다.</p><p class="small">당직근무에서 수정한 내용을 기본 달력으로 보냅니다. 반대 방향의 자동 수정은 지원하지 않습니다. 휴대폰 달력에서 선택한 일정을 가져오는 기능은 별도로 사용할 수 있습니다.</p></section>
|
||||
<h3>다른 달력에서 구독하기</h3><p class="small">지난 30일부터 앞으로 1년까지 읽기 전용으로 제공합니다. 구독 주소를 아는 사람은 선택한 항목을 볼 수 있습니다. 주소를 전달하기 전에 공유 범위를 확인하세요.</p>
|
||||
<fieldset><legend>내보낼 항목</legend><label class="check-label"><input id="share-rotation" type="checkbox" checked>나의 근무표</label><label class="check-label"><input id="share-skipRegular" type="checkbox">일반근무 날 빼기</label><p class="small">일반근무 날 빼기를 켜면 일반근무 날은 이름까지 통째로 보내지 않습니다. 끄면 앱 달력과 같게 보냅니다(근무 순서 이름 표시와 일반근무 글자 숨기기를 따름).</p><label class="check-label"><input id="share-names" type="checkbox"><span class="regular-name">일반근무</span> 아래 이름 포함</label><label class="check-label"><input id="share-events" type="checkbox">개인 일정과 알바</label><label class="check-label"><input id="share-anniversaries" type="checkbox">생일·기념일</label><label class="check-label"><input id="share-notes" type="checkbox">일정과 기념일 메모 포함</label></fieldset>
|
||||
<fieldset><legend>내보낼 항목</legend><label class="check-label"><input id="share-rotation" type="checkbox" checked>나의 근무표</label><label class="check-label"><input id="share-skipRegular" type="checkbox">일반근무 날 빼기</label><p class="small">일반근무 날 빼기를 켜면 일반근무 날은 통째로 보내지 않습니다. 끄면 앱 달력과 같게 보냅니다(일반근무 글자 숨기기를 따름).</p><p class="small share-names-title"><strong>근무 순서 이름 함께 보내기</strong> · 체크한 날에만 이름이 붙습니다. 체크하지 않으면 이름 없이 근무 글자만 보냅니다.</p><label class="check-label"><input id="share-nameWork" type="checkbox">당직·근무 날</label><label class="check-label"><input id="share-nameOff" type="checkbox">비번 날</label><label class="check-label"><input id="share-nameRest" type="checkbox">휴무 날</label><label class="check-label"><input id="share-nameAway" type="checkbox">연차·휴가·반차·병가·교육 날</label><label class="check-label"><input id="share-names" type="checkbox"><span class="regular-name">일반근무</span> 아래 이름 포함</label><label class="check-label"><input id="share-events" type="checkbox">개인 일정과 알바</label><label class="check-label"><input id="share-anniversaries" type="checkbox">생일·기념일</label><label class="check-label"><input id="share-notes" type="checkbox">일정과 기념일 메모 포함</label></fieldset>
|
||||
<p id="share-state" class="small" role="status"></p><div id="share-address-box" hidden><label>구독 주소 · 이 창에서 복사해 보관<input id="share-address" readonly autocomplete="off"></label><button id="share-copy" class="secondary">주소 복사</button></div>
|
||||
<p class="small">외부 달력의 ‘URL로 추가’ 또는 ‘웹에서 구독’에 주소를 붙여 넣으세요. 구독 갱신 주기는 외부 달력 서비스가 정하므로 즉시 반영되지 않을 수 있습니다. 파일로 가져오기는 저장 시점의 사본이며 이후 변경을 자동으로 받지 않습니다. <a class="guide-link" href="guide" target="_blank" rel="noopener" data-guide-link>구글·삼성·아이폰·아웃룩별 자세한 방법 보기</a></p>
|
||||
<p id="share-error" class="form-error" role="alert"></p><div class="dialog-actions"><button id="share-disable" class="danger" hidden>주소 종료</button><button id="share-file" class="secondary">달력 파일 받기</button><button id="share-update" class="secondary" hidden>항목만 바꾸기(주소 그대로)</button><button id="share-create">구독 주소 만들기</button></div><div class="dialog-actions"><button class="secondary close">닫기</button></div></dialog>
|
||||
@@ -60,11 +60,11 @@
|
||||
<p id="name-error" class="form-error" role="alert"></p><div class="dialog-actions"><button id="name-delete" type="button" class="danger" hidden>삭제</button><button type="button" class="secondary close">취소</button><button type="submit">저장</button></div></form></dialog>
|
||||
<dialog id="slot-names-dialog"><form id="slot-names-form"><div class="dialog-heading"><h2>근무 순서 이름</h2><button type="button" class="icon-button close" aria-label="닫기">×</button></div><p class="small">내 당직(나) 기준으로 +1(비번)부터 각 근무에 그날 당직 서는 다른 사람 이름을 붙입니다. 근무 순서는 그대로이고 이름(명칭)만 더해집니다. 이름 옆에서 그 이름을 달력에 어떻게 보일지 줄마다 고릅니다. 둘 다: 비번(김철수) · 이름만: 김철수 · 근무만: 비번. 이름을 비운 근무는 근무만 보입니다. 연차·반차·휴가·병가·교육·휴무로 바꾼 날에도 그날 이름이 같이 보입니다.</p><div id="slot-names" class="slot-names"></div><p id="slot-names-error" class="form-error" role="alert"></p><div class="dialog-actions"><button type="button" class="secondary close">취소</button><button type="submit">저장</button></div></form></dialog>
|
||||
<dialog id="options-dialog"><form id="options-form"><div class="dialog-heading"><h2>달력 표시</h2><button type="button" class="icon-button close" aria-label="닫기">×</button></div><h3>달력 표시</h3><p class="small">내 계정의 개인 설정으로 서버에 보관합니다. 같은 계정으로 로그인한 앱과 홈 위젯에도 적용합니다. 근무 순서와 기준일은 바뀌지 않습니다.</p><label>주 시작 요일<select id="rotation-week-start"><option value="1">월요일 시작</option><option value="0">일요일 시작</option></select></label><label class="check-label"><input id="rotation-duty-weekday" type="checkbox">당직일은 평일색으로 표시</label><p class="small">주말·공휴일이어도 당직 날짜는 평일색으로 표시합니다. 공휴일 이름과 근무 순서는 유지됩니다.</p><label class="check-label"><input id="rotation-off-red" type="checkbox">비번을 빨간색으로 표시</label><p class="small">비번 날짜와 비번 글씨를 빨간색으로 표시합니다.</p><label class="check-label"><input id="rotation-show-lunar" type="checkbox">음력 날짜 함께 보기</label><p class="small">양력 아래에 작은 글씨로 표시합니다. 윤달은 윤으로 구분합니다.</p><h3>일반근무</h3><label class="check-label"><input id="regular-hide" type="checkbox">달력 칸에서 일반근무 글자 숨기기</label><p class="small">달력 칸과 근무표 그림의 일반근무 날에 근무 글자를 넣지 않습니다. 오늘 안내와 날짜 상세에는 그대로 보이고 다른 달력 연동과 구독에는 그대로 보냅니다.</p><p id="options-error" class="form-error" role="alert"></p><div class="dialog-actions"><button type="button" class="secondary close">취소</button><button type="submit">저장</button></div></form></dialog>
|
||||
<dialog id="rotation-dialog"><form id="rotation-form"><div class="dialog-heading"><h2>당직 기초 설정</h2><button type="button" class="icon-button close" aria-label="닫기">×</button></div><p class="small">기준 날짜를 첫째 날로 삼아 같은 순서로 반복합니다. 날짜 색상과 음력은 옵션에서 바꿀 수 있습니다.</p><label>토요일 근무제<select id="rotation-work-week"><option value="6">주6일제 · 토요일 기존 근무</option><option value="5">주5일제 · 토요일 당직만 근무</option></select></label><p class="small">주5일제는 토요일을 빨간색으로 표시하며 당직이 아니면 휴무입니다. 주6일제는 파란색으로 표시하고 원래 근무를 따릅니다.</p><label>근무 유형<select id="rotation-mode"><option value="custom">직접 설정</option><option value="duty">일당직 · 숫자로 입력</option></select></label><label id="rotation-remainder-label" hidden>당직·비번 다음 남은 날<select id="rotation-remainder"><option value="REGULAR">일반근무</option><option value="OFF">비번</option><option value="REST">휴무</option></select></label><p class="small">일당직은 숫자만 입력하면 당직·비번 다음의 근무를 채웁니다. 교대 유형은 예시이며 아래 순서를 직접 고칠 수 있습니다.</p><label>반복 일수<input id="rotation-count" type="number" min="1" max="366" required></label><div id="rotation-days" class="rotation-days"></div><label>첫째 날의 날짜<input id="rotation-anchor" type="date" min="2000-01-01" max="2099-12-31" required></label><p id="rotation-error" class="form-error" role="alert"></p><div class="dialog-actions"><button type="button" class="secondary close">취소</button><button type="submit">저장</button></div></form></dialog>
|
||||
<dialog id="rotation-dialog"><form id="rotation-form"><div class="dialog-heading"><h2>당직 기초 설정</h2><button type="button" class="icon-button close" aria-label="닫기">×</button></div><p class="small">기준 날짜를 첫째 날로 삼아 같은 순서로 반복합니다. 날짜 색상과 음력은 옵션에서 바꿀 수 있습니다.</p><label>토요일 근무제<select id="rotation-work-week"><option value="6">주6일제 · 토요일 파란 날짜</option><option value="5">주5일제 · 토요일 빨간 날짜</option></select></label><p class="small">주5일제는 토요일 날짜를 빨간색으로, 주6일제는 파란색으로 표시합니다. 근무는 두 방식 모두 원래 순서를 따릅니다.</p><label>근무 유형<select id="rotation-mode"><option value="custom">직접 설정</option><option value="duty">일당직 · 숫자로 입력</option></select></label><label id="rotation-remainder-label" hidden>당직·비번 다음 남은 날<select id="rotation-remainder"><option value="REGULAR">일반근무</option><option value="OFF">비번</option><option value="REST">휴무</option></select></label><p class="small">일당직은 숫자만 입력하면 당직·비번 다음의 근무를 채웁니다. 교대 유형은 예시이며 아래 순서를 직접 고칠 수 있습니다.</p><label>반복 일수<input id="rotation-count" type="number" min="1" max="366" required></label><div id="rotation-days" class="rotation-days"></div><label>첫째 날의 날짜<input id="rotation-anchor" type="date" min="2000-01-01" max="2099-12-31" required></label><p id="rotation-error" class="form-error" role="alert"></p><div class="dialog-actions"><button type="button" class="secondary close">취소</button><button type="submit">저장</button></div></form></dialog>
|
||||
<dialog id="auth-dialog"><form id="auth-form"><div class="dialog-heading"><h2 id="auth-heading">회원 로그인</h2><button type="button" class="icon-button close" aria-label="닫기">×</button></div><p id="auth-help" class="small"></p><label>아이디<input id="auth-username" autocomplete="username" minlength="3" maxlength="32" pattern="[a-zA-Z0-9_]{3,32}" required></label><label id="auth-name-label" hidden>이름<input id="auth-name" maxlength="40" autocomplete="name"></label><label id="auth-code-label" hidden>복구 코드<input id="auth-code" maxlength="32" autocomplete="off"></label><label>비밀번호<input id="auth-password" type="password" maxlength="128" autocomplete="current-password" required></label><label id="auth-repeat-label" hidden>비밀번호 확인<input id="auth-repeat" type="password" maxlength="128" autocomplete="new-password"></label><p id="auth-error" class="form-error" role="alert"></p><div class="dialog-actions"><button id="auth-recovery" type="button" class="text-button">비밀번호 복구</button><button id="auth-submit" type="submit">로그인</button></div></form></dialog>
|
||||
<dialog id="account-dialog"><div class="dialog-heading"><h2>내 정보</h2><button class="icon-button close" aria-label="닫기">×</button></div><p id="account-description"></p><p class="small">앱의 웹 연동을 켠 뒤 같은 아이디로 로그인하면 일정과 함께 보는 근무표가 동기화됩니다.</p><div class="dialog-actions"><button id="account-logout" class="secondary">로그아웃</button><button id="password-open">비밀번호 변경</button></div></dialog>
|
||||
<dialog id="password-dialog"><form id="password-form"><div class="dialog-heading"><h2>비밀번호 변경</h2><button type="button" class="icon-button close" aria-label="닫기">×</button></div><p class="small">비밀번호를 변경하면 다른 기기의 로그인은 해제됩니다. 다시 로그인하면 저장한 일정을 이어서 사용할 수 있습니다.</p><label>현재 비밀번호<input id="password-current" type="password" maxlength="128" autocomplete="current-password" required></label><label>새 비밀번호<input id="password-new" type="password" minlength="6" maxlength="128" autocomplete="new-password" required></label><label>새 비밀번호 확인<input id="password-repeat" type="password" minlength="6" maxlength="128" autocomplete="new-password" required></label><p id="password-error" class="form-error" role="alert"></p><div class="dialog-actions"><button type="submit">변경</button></div></form></dialog>
|
||||
<dialog id="person-dialog"><form id="person-form"><div class="dialog-heading"><h2 id="person-heading">함께 볼 사람 추가</h2><button type="button" class="icon-button close" aria-label="닫기">×</button></div><p class="small">직접 입력한 근무표를 함께 봅니다. 상대방에게 계정이나 접근 권한을 부여하지 않습니다.</p><label>이름<input id="person-name" maxlength="30" required></label><label>표시 색상<select id="person-color"><option value="BLUE">파랑</option><option value="PURPLE">보라</option><option value="ORANGE">주황</option><option value="PINK">분홍</option><option value="TEAL">청록</option><option value="BROWN">갈색</option></select></label><h3 class="settings-section">당직 기초 설정</h3><label>토요일 근무제<select id="person-work-week"><option value="6">주6일제 · 토요일 기존 근무</option><option value="5">주5일제 · 토요일 당직만 근무</option></select></label><p class="small">주5일제는 토요일을 빨간색으로 표시하며 당직이 아니면 휴무입니다. 주6일제는 파란색으로 표시하고 원래 근무를 따릅니다.</p><label>근무 유형<select id="person-mode"><option value="custom">직접 설정</option><option value="duty">일당직 · 숫자로 입력</option></select></label><label id="person-remainder-label" hidden>당직·비번 다음 남은 날<select id="person-remainder"><option value="REGULAR">일반근무</option><option value="OFF">비번</option><option value="REST">휴무</option></select></label><p class="small">일당직은 숫자만 입력하면 당직·비번 다음의 근무를 채웁니다. 교대 유형은 예시이며 아래 순서를 직접 고칠 수 있습니다.</p><label>반복 일수<input id="person-count" type="number" min="1" max="366" required></label><div id="person-days" class="rotation-days"></div><label>첫째 날의 날짜<input id="person-anchor" type="date" min="2000-01-01" max="2099-12-31" required></label><h3 class="settings-section">표시 옵션</h3><label class="check-label"><input id="person-duty-weekday" type="checkbox">당직일은 평일색으로 표시</label><p class="small">주말·공휴일이어도 당직 날짜는 평일색으로 표시합니다. 공휴일 이름과 근무 순서는 유지됩니다.</p><p id="person-error" class="form-error" role="alert"></p><div class="dialog-actions"><button id="person-delete" type="button" class="danger" hidden>삭제</button><button type="button" class="secondary close">취소</button><button type="submit">저장</button></div></form></dialog>
|
||||
<dialog id="person-dialog"><form id="person-form"><div class="dialog-heading"><h2 id="person-heading">함께 볼 사람 추가</h2><button type="button" class="icon-button close" aria-label="닫기">×</button></div><p class="small">직접 입력한 근무표를 함께 봅니다. 상대방에게 계정이나 접근 권한을 부여하지 않습니다.</p><label>이름<input id="person-name" maxlength="30" required></label><label>표시 색상<select id="person-color"><option value="BLUE">파랑</option><option value="PURPLE">보라</option><option value="ORANGE">주황</option><option value="PINK">분홍</option><option value="TEAL">청록</option><option value="BROWN">갈색</option></select></label><h3 class="settings-section">당직 기초 설정</h3><label>토요일 근무제<select id="person-work-week"><option value="6">주6일제 · 토요일 파란 날짜</option><option value="5">주5일제 · 토요일 빨간 날짜</option></select></label><p class="small">주5일제는 토요일 날짜를 빨간색으로, 주6일제는 파란색으로 표시합니다. 근무는 두 방식 모두 원래 순서를 따릅니다.</p><label>근무 유형<select id="person-mode"><option value="custom">직접 설정</option><option value="duty">일당직 · 숫자로 입력</option></select></label><label id="person-remainder-label" hidden>당직·비번 다음 남은 날<select id="person-remainder"><option value="REGULAR">일반근무</option><option value="OFF">비번</option><option value="REST">휴무</option></select></label><p class="small">일당직은 숫자만 입력하면 당직·비번 다음의 근무를 채웁니다. 교대 유형은 예시이며 아래 순서를 직접 고칠 수 있습니다.</p><label>반복 일수<input id="person-count" type="number" min="1" max="366" required></label><div id="person-days" class="rotation-days"></div><label>첫째 날의 날짜<input id="person-anchor" type="date" min="2000-01-01" max="2099-12-31" required></label><h3 class="settings-section">표시 옵션</h3><label class="check-label"><input id="person-duty-weekday" type="checkbox">당직일은 평일색으로 표시</label><p class="small">주말·공휴일이어도 당직 날짜는 평일색으로 표시합니다. 공휴일 이름과 근무 순서는 유지됩니다.</p><p id="person-error" class="form-error" role="alert"></p><div class="dialog-actions"><button id="person-delete" type="button" class="danger" hidden>삭제</button><button type="button" class="secondary close">취소</button><button type="submit">저장</button></div></form></dialog>
|
||||
<dialog id="conflict-dialog"><div class="dialog-heading"><h2>동시 수정 확인</h2><button class="icon-button close" aria-label="닫기">×</button></div><p>같은 항목을 다른 기기에서도 수정했습니다. 두 내용을 확인한 뒤 보관할 내용을 선택하세요.</p><h3>이 브라우저의 내용</h3><pre id="conflict-local"></pre><h3>서버의 최신 내용</h3><pre id="conflict-remote"></pre><div class="dialog-actions"><button id="use-remote" class="secondary">서버 내용 사용</button><button id="use-local">내 내용 저장</button></div></dialog>
|
||||
<dialog id="confirm-dialog" aria-labelledby="confirm-heading"><h2 id="confirm-heading">변경 확인</h2><p id="confirm-message"></p><div class="dialog-actions"><button id="confirm-cancel" class="secondary">취소</button><button id="confirm-accept">확인</button></div></dialog>
|
||||
<div id="toast" class="toast" role="status" hidden></div>
|
||||
|
||||
@@ -40,3 +40,5 @@ dialog{border:1px solid #c2c8cd;border-top:4px solid var(--ink);border-radius:5p
|
||||
.brand-mark{width:38px;height:38px;border-radius:10px;box-shadow:0 6px 14px #26364d29}.brand b{font-weight:inherit}.brand small{letter-spacing:.06em}
|
||||
.site-notice{display:flex;align-items:center;gap:10px;padding:11px max(40px,calc((100% - 1240px) / 2));font-size:13px;line-height:1.6;background:#e9eef5;color:var(--ink);border-bottom:1px solid #cfd8e3}.site-notice::before{content:'';flex:none;width:8px;height:8px;border-radius:50%;background:var(--blue)}.site-notice.warn{background:#f8ece5;border-color:#e8cbbb}.site-notice.warn::before{background:var(--accent)}
|
||||
@media(max-width:760px){.brand-mark{width:32px;height:32px;border-radius:9px}.site-notice{padding:10px 20px;font-size:12px}}
|
||||
/* 그날 당직자는 근무 글자 뒤 괄호가 아니라 아래 줄에 따로 보인다(2026-11-26 사용자 지시). */
|
||||
.today-card p.today-name{color:var(--ink);font-size:15px;font-weight:600;margin:-2px 0 7px}#day-detail .day-duty{display:block;color:var(--ink);font-weight:600}
|
||||
@@ -1,5 +1,5 @@
|
||||
'use strict';
|
||||
const WEB_BUILD = '2026-11-26.2';
|
||||
const WEB_BUILD = '2026-12-01.2';
|
||||
let offeredRelease=null, versionChecking=false;
|
||||
const versionDeferKey='duty-web-update-later';
|
||||
const versionSeenKey='duty-web-update-seen';
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
const WorkPlan={
|
||||
empty:()=>({changes:[],overrides:{},hours:{},minimumRestHours:0}),
|
||||
regime:(r,key)=>(r.workPlan?.changes||[]).filter(v=>v.from<=key).sort((a,b)=>a.from.localeCompare(b.from)).at(-1)||r,
|
||||
shift(r,key){if(!r)return null;const change=r.workPlan?.overrides?.[key];if(change)return change.shift;const v=this.regime(r,key),d=new Date(key+'T00:00:00Z'),gap=Math.round((d-new Date(v.anchor+'T00:00:00Z'))/86400000),planned=v.pattern[((gap%v.pattern.length)+v.pattern.length)%v.pattern.length];return v.workWeek===5&&d.getUTCDay()===6&&planned!=='DUTY'?'REST':planned;},
|
||||
shift(r,key){if(!r)return null;const change=r.workPlan?.overrides?.[key];if(change)return change.shift;const v=this.regime(r,key),d=new Date(key+'T00:00:00Z'),gap=Math.round((d-new Date(v.anchor+'T00:00:00Z'))/86400000),planned=v.pattern[((gap%v.pattern.length)+v.pattern.length)%v.pattern.length];return planned;},
|
||||
// 주5일제는 토요일 날짜만 빨간색이다. 근무는 원래 순서대로 보인다(2026-11-26 사용자 지시: 토요일 휴무 글자 넣지 않기).
|
||||
// 하루를 쉬는 휴가와 병가. 날짜 숫자를 빨간색으로 보인다. 반차(HALF_LEAVE)는 파란색이다(2026-11-26 사용자 지시).
|
||||
fullLeave:shift=>['LEAVE','ANNUAL_LEAVE','MONTHLY_LEAVE','VACATION','OFFICIAL_LEAVE','FAMILY_LEAVE','SICK'].includes(shift),
|
||||
// 휴가·반차·병가·교육·휴무로 바꾼 날은 내가 자리를 비워도 그날 자리 이름(그날 당직자)은 그대로다.
|
||||
|
||||
+2
-1
@@ -40,7 +40,8 @@ def shift(data,on):
|
||||
choices=[entry for entry in plan.get('changes',[]) if entry['from']<=key]
|
||||
regime=max(choices,key=lambda entry:entry['from']) if choices else data
|
||||
value=regime['pattern'][(on-date.fromisoformat(regime['anchor'])).days%len(regime['pattern'])]
|
||||
return 'REST' if regime.get('workWeek')==5 and on.isoweekday()==6 and value!='DUTY' else value
|
||||
# 주5일제는 토요일 날짜만 빨간색으로 보인다. 근무는 일요일처럼 원래 순서를 그대로 따른다(2026-11-26 사용자 지시: 토요일은 그냥 빨강, 휴무 글자 넣지 않기).
|
||||
return value
|
||||
|
||||
def away_on(data,on):
|
||||
"""휴가·반차·병가·교육·휴무로 바꾼 날인지."""
|
||||
|
||||
Reference in new issue
Block a user