- 달력 표시에 일반근무 글자 숨기기(hideRegular). 앱·웹 달력 칸과 위젯 및 근무표 그림에서만 빼고 오늘 카드·날짜 상세·기본 달력 반영·구독은 그대로 - 달력 연동 안내 페이지(/calendar/guide): 구독 주소 · 안드로이드 앱 기본 달력 반영 · 구글 · 삼성 · 아이폰 · 아웃룩 · 파일 · 문제 해결. 글은 관리자에서 고침(guide_text.py 기본값) - 게시판(/calendar/board, board.py): 게시판 종류와 읽기·쓰기·댓글 권한을 관리자에서 만들고 고침, 글·댓글 쓰기·고치기·지우기, 운영진 숨김·고정·되살리기, 하루 한도 - 관리자: 설정 칸에 화면 구분(page)과 숫자·색·긴 글 종류. 색·메뉴·탭 제목·처음 기본값(웹)·게시판 한도 - 홈페이지 위쪽 메뉴 줄, 달력 연동·공유 창과 앱 메뉴에서 안내 페이지로 가는 링크 - 검사: 서버 103개(게시판 9개 새로), 앱 단위 54개, 위젯 기기 검사에 숨기기 확인. 로고 가져오기 시험의 같은 초 기록 순서 흔들림 고침
496 lines
37 KiB
Kotlin
496 lines
37 KiB
Kotlin
package kr.co.itosm.dutycalendar
|
|
|
|
import android.app.Activity
|
|
import android.app.AlertDialog
|
|
import android.app.DatePickerDialog
|
|
import android.appwidget.AppWidgetManager
|
|
import android.content.ComponentName
|
|
import android.graphics.Typeface
|
|
import android.graphics.drawable.GradientDrawable
|
|
import android.os.Bundle
|
|
import android.view.Gravity
|
|
import android.view.View
|
|
import android.widget.*
|
|
import java.time.LocalDate
|
|
import java.time.YearMonth
|
|
import java.time.format.DateTimeFormatter
|
|
import java.util.Locale
|
|
|
|
/**
|
|
* 오늘의 근무와 월간 달력 및 반복 설정을 한 화면에서 제공한다.
|
|
* 저장된 근무표를 읽어 화면을 다시 그리며 월 이동만으로 저장된 기준일을 바꾸지 않는다.
|
|
* 위젯과 계산식을 따로 만들지 않고 Schedule과 Holidays를 공유해 표시 결과를 맞춘다.
|
|
*/
|
|
class MainActivity : Activity() {
|
|
private var month = YearMonth.now()
|
|
private var selectedDate = LocalDate.now()
|
|
private val planner by lazy { PlannerDialogs(this) { render() } }
|
|
private val peopleEditor by lazy { PeopleDialogs(this) { render() } }
|
|
private val anniversaries by lazy { AnniversaryDialogs(this) { render() } }
|
|
private val deviceCalendar by lazy { DeviceCalendar(this) { render() } }
|
|
private lateinit var content: LinearLayout
|
|
private var scrollOffset = 0
|
|
private var restoringScroll = false
|
|
private var renderGeneration = 0
|
|
private val ink = 0xFF26364D.toInt()
|
|
private val muted = 0xFF626976.toInt()
|
|
private val accent = 0xFF26364D.toInt()
|
|
private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()
|
|
private fun background(color: Int, radius: Int = 5, border: Int? = null) = GradientDrawable().apply {
|
|
setColor(color); cornerRadius = dp(radius).toFloat()
|
|
border?.let { setStroke(dp(1), it) }
|
|
}
|
|
private fun label(value: String, size: Float = 15f, color: Int = ink, bold: Boolean = false) = TextView(this).apply {
|
|
text = value; textSize = size; setTextColor(color)
|
|
if (bold) setTypeface(typeface, Typeface.BOLD)
|
|
}
|
|
private fun column() = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
|
|
private fun row() = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL }
|
|
private fun button(title: String, filled: Boolean = false, action: () -> Unit) = Button(this).apply {
|
|
text = title; isAllCaps = false; textSize = 14f
|
|
minHeight = dp(48); minimumHeight = dp(48)
|
|
setTextColor(if (filled) 0xFFFFFFFF.toInt() else accent)
|
|
background = background(if (filled) accent else 0xFFEBEDF2.toInt(), 5)
|
|
setPadding(dp(12), dp(8), dp(12), dp(8))
|
|
setOnClickListener { action() }
|
|
}
|
|
private fun space(parent: LinearLayout, height: Int) { parent.addView(View(this), LinearLayout.LayoutParams(1, dp(height))) }
|
|
private fun card(parent: LinearLayout, color: Int = 0xFFFFFFFF.toInt()): LinearLayout {
|
|
return column().apply {
|
|
background = background(color, 5, 0xFFDEDED8.toInt())
|
|
setPadding(dp(16), dp(16), dp(16), dp(16))
|
|
parent.addView(this, LinearLayout.LayoutParams(-1, -2))
|
|
}
|
|
}
|
|
override fun onCreate(savedInstanceState: Bundle?) {
|
|
super.onCreate(savedInstanceState)
|
|
savedInstanceState?.getString("month")?.let { month = YearMonth.parse(it) }
|
|
savedInstanceState?.getString("selectedDate")?.let { selectedDate = LocalDate.parse(it) }
|
|
PlannerStore.migrate(this)
|
|
if(savedInstanceState==null) receiveNavigation(intent)
|
|
}
|
|
private fun receiveNavigation(incoming:android.content.Intent) {
|
|
AppNavigation.takeDate(incoming)?.let { selectedDate=it;month=YearMonth.from(it) }
|
|
AppNavigation.takeWidget(incoming)?.let { id -> window.decorView.post {
|
|
if(!isFinishing&&!isDestroyed)WidgetStyleDialog.show(this,id)
|
|
} }
|
|
}
|
|
override fun onNewIntent(incoming:android.content.Intent) {
|
|
super.onNewIntent(incoming)
|
|
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 onResume() {
|
|
super.onResume(); render(); DutyWidget.updateAll(this); Reminders.reschedule(this)
|
|
CalendarMirror.request(this)
|
|
Holidays.schedule(this)
|
|
val holidayRevision=Holidays.revision(this)
|
|
Holidays.refresh(this) { success -> if (success&&Holidays.revision(this)!=holidayRevision) runOnUiThread { if (!isFinishing && !isDestroyed) render() } }
|
|
SyncClient.schedule(this)
|
|
SyncClient.foreground(this) { runOnUiThread { if (!isFinishing && !isDestroyed) render() } }
|
|
UpdateChecker.check(this, fresh = true)
|
|
}
|
|
override fun onPause() { SyncClient.background(); super.onPause() }
|
|
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
|
super.onWindowFocusChanged(hasFocus)
|
|
// 첫 실행에서는 onResume보다 창 표시가 늦을 수 있다. 저장된 새 버전도 창이 준비된 뒤 안내한다.
|
|
// 확인 간격과 나중에 알림 설정은 UpdateChecker가 유지하므로 초점 변경마다 통신하지 않는다.
|
|
if (hasFocus) UpdateChecker.check(this)
|
|
}
|
|
|
|
internal fun render() {
|
|
// 다른 기기의 변경을 받더라도 사용자가 읽고 있던 위치를 유지한다.
|
|
// 연결 확인과 공휴일 갱신이 연달아 끝나면 앞선 화면의 위치 복원이 아직 대기 중일 수 있다.
|
|
// 이때 새 화면의 임시 0 위치를 읽으면 아래쪽 메뉴가 갑자기 맨 위로 돌아가므로 저장한 위치를 유지한다.
|
|
if (!restoringScroll && ::content.isInitialized) scrollOffset = (content.parent as? ScrollView)?.scrollY ?: scrollOffset
|
|
restoringScroll = true
|
|
val generation = ++renderGeneration
|
|
val schedule = ScheduleStore.load(this)
|
|
val configured = ScheduleStore.isConfigured(this)
|
|
val today = LocalDate.now()
|
|
val snapshot = CalendarSnapshot.load(this)
|
|
val people = snapshot.people
|
|
val scroll = ScrollView(this).apply {
|
|
isFillViewport = true; setBackgroundColor(0xFFF4F1EA.toInt())
|
|
setOnScrollChangeListener { _, _, y, _, _ -> if (!restoringScroll && generation == renderGeneration) scrollOffset = y }
|
|
}
|
|
content = column().apply { setPadding(dp(16), dp(18), dp(16), dp(24)) }
|
|
scroll.addView(content)
|
|
// 최신 안드로이드의 화면 가장자리 표시에서도 상태 표시줄과 탐색 버튼에 내용이 가리지 않게 한다.
|
|
// 구형 기기는 기존 여백 API를 사용한다. 앱의 최소 지원 버전에서도 같은 내용을 볼 수 있어야 한다.
|
|
scroll.setOnApplyWindowInsetsListener { view, insets ->
|
|
if (android.os.Build.VERSION.SDK_INT >= 30) {
|
|
val bars = insets.getInsets(android.view.WindowInsets.Type.systemBars() or android.view.WindowInsets.Type.displayCutout())
|
|
view.setPadding(bars.left, bars.top, bars.right, bars.bottom)
|
|
} else {
|
|
@Suppress("DEPRECATION")
|
|
view.setPadding(insets.systemWindowInsetLeft, insets.systemWindowInsetTop, insets.systemWindowInsetRight, insets.systemWindowInsetBottom)
|
|
}
|
|
insets
|
|
}
|
|
setContentView(scroll)
|
|
val brand = row()
|
|
brand.addView(ImageView(this).apply { setImageResource(R.drawable.ic_calendar); contentDescription = null }, LinearLayout.LayoutParams(dp(32), dp(36)).apply { marginEnd = dp(10) })
|
|
brand.addView(label("당직근무", 23f, ink, true), LinearLayout.LayoutParams(0, -2, 1f))
|
|
brand.addView(button("옵션") { showOptions() }, LinearLayout.LayoutParams(-2, dp(44)))
|
|
content.addView(brand)
|
|
space(content, 8)
|
|
content.addView(label(if (SyncClient.connected(this)) SyncClient.message else "나의 근무 기록 · 이 기기에 저장", 12f, muted))
|
|
space(content, 20)
|
|
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) "오늘은 ${schedule.shiftOn(today).title}" else "근무표를 설정해 주세요", 22f, if (configured) schedule.shiftColor(today) else 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) {
|
|
todayCard.isFocusable = true
|
|
todayCard.setOnClickListener { showSettings() }
|
|
}
|
|
space(content, 16)
|
|
// 자주 쓰는 일정과 근무 설정을 달력 바로 앞에 둔다. 연결 관리가 날짜 확인을 밀어내지 않도록 한다.
|
|
val quickActions = row()
|
|
quickActions.addView(button("일정 추가", true) { planner.event(selectedDate) }, LinearLayout.LayoutParams(0, dp(48), 1f).apply { marginEnd = dp(8) })
|
|
quickActions.addView(button("당직 기초 설정") { showSettings() }, LinearLayout.LayoutParams(0, dp(48), 1f))
|
|
content.addView(quickActions)
|
|
space(content, 14)
|
|
val calendar = card(content, 0xFFFFFEFA.toInt())
|
|
val navigation = row()
|
|
navigation.addView(label("${month.year}. ${month.monthValue.toString().padStart(2, '0')}", 24f, ink, true), LinearLayout.LayoutParams(0, -2, 1f))
|
|
navigation.addView(button("오늘") { month = YearMonth.now(); render() }, LinearLayout.LayoutParams(dp(62), dp(44)))
|
|
calendar.addView(navigation)
|
|
space(calendar, 12)
|
|
val week = row()
|
|
calendarWeekdays(schedule.weekStart).forEach { day ->
|
|
val text = listOf("일", "월", "화", "수", "목", "금", "토")[day]
|
|
week.addView(label(text, 13f, if (day == 0) 0xFFBD5163.toInt() else if (day == 6) schedule.saturdayColor else muted, true).apply { gravity = Gravity.CENTER }, LinearLayout.LayoutParams(0, dp(32), 1f))
|
|
}
|
|
calendar.addView(week)
|
|
// 한 주를 7칸으로 나누고 같은 너비를 배정한다. 공휴일은 날짜 색상과 이름으로 함께 구분한다.
|
|
// 앞뒤 달의 근무도 계산하지만 투명도를 낮춰 현재 보고 있는 달과 혼동하지 않게 한다.
|
|
calendarDays(month, schedule.weekStart).chunked(7).forEach { dates ->
|
|
val cells = row()
|
|
dates.forEach { date ->
|
|
val shift = schedule.shiftOn(date)
|
|
val holiday = Holidays.name(this, date)
|
|
val lunar = if (schedule.showLunar) LunarDates.label(this, date) else null
|
|
val events = snapshot.eventsOn(date)
|
|
val personalDays = snapshot.anniversariesOn(date)
|
|
val workNames = snapshot.workNames(date, schedule)
|
|
val colleagues = People.onDuty(people, date)
|
|
val inside = YearMonth.from(date) == month
|
|
val cell = column().apply {
|
|
gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL
|
|
setPadding(0, dp(6), 0, 0)
|
|
if (date == today) background = background(0xFFE8ECF3.toInt(), 3, accent)
|
|
alpha = if (inside) 1f else 0.55f
|
|
val dateColor = schedule.dateColor(date, holiday != null)
|
|
addView(label(date.dayOfMonth.toString(), 18f, dateColor, true).apply { gravity = Gravity.CENTER })
|
|
if (lunar != null) addView(label(lunar, 9f, muted).apply { gravity = Gravity.CENTER; maxLines = 1 })
|
|
// 일반근무 숨기기를 켜면 글자만 비우고 자리는 남겨 날짜 줄이 흔들리지 않게 한다.
|
|
val shiftText = ShiftNames.cellLabel(shift)
|
|
addView(label(shiftText, 12f, schedule.shiftColor(date), true).apply {
|
|
gravity = Gravity.CENTER
|
|
setPadding(dp(4), dp(2), dp(4), dp(2))
|
|
if (shiftText.isNotEmpty()) background = background(schedule.shiftPale(date), 3)
|
|
}, LinearLayout.LayoutParams(-2, -2).apply { topMargin = dp(3) })
|
|
workNames.take(2).forEach { name -> addView(label(name.name, 10f, name.color).apply { gravity=Gravity.CENTER; maxLines=1; ellipsize=android.text.TextUtils.TruncateAt.END }) }
|
|
if (workNames.size > 2) addView(label("외 ${workNames.size - 2}명", 9f, muted).apply { gravity=Gravity.CENTER })
|
|
if (holiday != null) addView(label(if (holiday.contains("대체공휴일")) "대체휴일" else holiday.replace("기독탄신일", "성탄절").replace("1월 1일", "신정"), 10f, 0xFFBD5163.toInt(), true).apply {
|
|
gravity = Gravity.CENTER; maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END
|
|
})
|
|
if (events.isNotEmpty()) addView(label("일정 ${events.size}", 10f, 0xFF8B653C.toInt(), true).apply { gravity = Gravity.CENTER })
|
|
if (personalDays.isNotEmpty()) addView(label(personalDays.first().getJSONObject("data").getString("title"), 10f, 0xFF896238.toInt(), true).apply { gravity = Gravity.CENTER; maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END })
|
|
colleagues.take(2).forEach { person -> addView(label(person.name, 10f, person.color, true).apply { gravity = Gravity.CENTER; maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END }) }
|
|
if (colleagues.size > 2) addView(label("외 ${colleagues.size - 2}명", 9f, muted).apply { gravity = Gravity.CENTER })
|
|
// 좁은 칸에서 공휴일 이름이 생략돼도 날짜를 누르면 전체 이름을 확인할 수 있다.
|
|
// 화면 읽기 기능에도 날짜와 전체 근무 이름 및 공휴일을 함께 전달한다.
|
|
contentDescription = "${date.monthValue}월 ${date.dayOfMonth}일 ${shift.title} ${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}일 ${shift.title}")
|
|
.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("나: ${shift.title}\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()
|
|
}
|
|
}
|
|
cells.addView(cell, LinearLayout.LayoutParams(0, dp((if (people.isEmpty() && !snapshot.hasNames) 103 else 174) + if (schedule.showLunar) 14 else 0), 1f))
|
|
}
|
|
calendar.addView(View(this).apply { setBackgroundColor(0xFFE6E4DC.toInt()) }, LinearLayout.LayoutParams(-1, dp(1)))
|
|
calendar.addView(cells)
|
|
}
|
|
space(calendar, 12)
|
|
val monthButtons = row()
|
|
monthButtons.addView(button("이전 달") { month = month.minusMonths(1); render() }, LinearLayout.LayoutParams(0, dp(44), 1f).apply { marginEnd = dp(8) })
|
|
monthButtons.addView(button("다음 달") { month = month.plusMonths(1); render() }, LinearLayout.LayoutParams(0, dp(44), 1f))
|
|
calendar.addView(monthButtons)
|
|
space(calendar, 14)
|
|
calendar.addView(label(listOf(Shift.DUTY, Shift.REGULAR, Shift.DAY, Shift.EVENING, Shift.NIGHT, Shift.OFF, Shift.REST).joinToString(" · ") { it.shortTitle }, 11f, muted).apply { gravity = Gravity.CENTER })
|
|
space(content, 16)
|
|
val connection = card(content, 0xFFFFFEFA.toInt())
|
|
connection.addView(label("웹과 연결", 16f, ink, true))
|
|
if (SyncClient.connected(this)) {
|
|
val tools = row()
|
|
tools.addView(button("새로 불러오기") { SyncClient.sync(this, force = true) }, LinearLayout.LayoutParams(0, dp(48), 1f))
|
|
tools.addView(button("소속 회사") { planner.openWebsite() }, LinearLayout.LayoutParams(0, dp(48), 1f))
|
|
connection.addView(tools)
|
|
PlannerStore.company(this)?.let { company -> connection.addView(label("소속 · ${company.getString("name")} · 근무표 공유", 12f, muted)) }
|
|
connection.addView(label("저장된 자료 사용 · 월 1회 또는 변경 시 갱신", 11f, muted))
|
|
}
|
|
connection.addView(Switch(this).apply {
|
|
text = "웹 연동 (선택)"; textSize = 14f; minHeight = dp(48); isChecked = SyncClient.enabled(this@MainActivity)
|
|
setOnCheckedChangeListener { _, checked ->
|
|
if (checked && !SyncClient.enabled(this@MainActivity)) { isChecked = false; planner.connection() }
|
|
else if (!checked && SyncClient.enabled(this@MainActivity)) { SyncClient.disable(this@MainActivity); render() }
|
|
}
|
|
})
|
|
space(content, 16)
|
|
if (SyncClient.connected(this)) {
|
|
val peopleCard = card(content)
|
|
peopleCard.addView(label("함께 보는 근무표", 18f, ink, true))
|
|
space(peopleCard, 6)
|
|
peopleCard.addView(label("${selectedDate.monthValue}월 ${selectedDate.dayOfMonth}일 · 직접 등록한 근무표는 이름을 눌러 수정합니다.", 12f, muted))
|
|
space(peopleCard, 8)
|
|
people.forEach { person ->
|
|
peopleCard.addView(button("${person.name} · ${person.schedule.shiftOn(selectedDate).title} (${person.schedule.pattern.size}일 반복${if (person.shared) " · 소속" else ""})") { if (person.shared) Toast.makeText(this, "소속 회원의 근무표는 본인만 수정할 수 있습니다.", Toast.LENGTH_LONG).show() else peopleEditor.edit(person) }.apply { setTextColor(person.color) }, LinearLayout.LayoutParams(-1, -2))
|
|
}
|
|
if (people.isEmpty()) peopleCard.addView(label("이름과 반복 근무를 등록하면 날짜별 당직을 함께 볼 수 있습니다.", 13f, muted))
|
|
peopleCard.addView(button("함께 볼 사람 추가") { peopleEditor.edit() }, LinearLayout.LayoutParams(-1, dp(48)))
|
|
space(content, 16)
|
|
} else {
|
|
val memberInfo = card(content)
|
|
memberInfo.addView(label("함께 보는 근무표 · 회원 전용", 18f, ink, true))
|
|
space(memberInfo, 8)
|
|
memberInfo.addView(label("로그인하면 다른 사람의 근무표와 소속 근무표를 함께 볼 수 있습니다.", 13f, muted))
|
|
space(memberInfo, 10)
|
|
memberInfo.addView(button("로그인하고 함께 보기") { planner.connection() }, LinearLayout.LayoutParams(-1, dp(48)))
|
|
space(content, 16)
|
|
}
|
|
val agenda = card(content)
|
|
agenda.addView(label("${selectedDate.monthValue}월 ${selectedDate.dayOfMonth}일 일정", 18f, ink, true))
|
|
agenda.addView(button("이 날짜 근무 변경") { WorkPlanDialogs(this){render()}.overrides(selectedDate) })
|
|
ScheduleStore.load(this).workPlan?.overrides?.get(selectedDate)?.note?.takeIf{it.isNotBlank()}?.let { agenda.addView(label(it,12f,muted)) }
|
|
space(agenda, 10)
|
|
val selectedEvents = PlannerStore.eventsOn(this, selectedDate)
|
|
val selectedDays = Anniversaries.on(this, selectedDate)
|
|
if (selectedEvents.isEmpty() && selectedDays.isEmpty()) agenda.addView(label("등록된 일정이 없습니다. 날짜를 눌러 새 일정을 추가하세요.", 13f, muted))
|
|
selectedDays.forEach { item ->
|
|
val data = item.getJSONObject("data")
|
|
agenda.addView(button("${data.getString("title")}\n${Anniversaries.description(data)}") { anniversaries.edit(item) }, LinearLayout.LayoutParams(-1, -2))
|
|
}
|
|
if (SyncClient.connected(this)) {
|
|
agenda.addView(button("내 생일·기념일 관리") { anniversaries.list() }, LinearLayout.LayoutParams(-1, dp(48)))
|
|
agenda.addView(label("내 계정에 보관 · 같은 계정으로 재로그인하면 복원", 12f, muted))
|
|
}
|
|
agenda.addView(button("알바·시간근무 추가") { planner.event(selectedDate, partTime = true) }, LinearLayout.LayoutParams(-1, dp(48)))
|
|
selectedEvents.forEach { item ->
|
|
val data = item.getJSONObject("data")
|
|
val time = PlannerStore.timeSummary(data)
|
|
agenda.addView(button("${data.getString("title")}\n$time") { planner.event(selectedDate, item) }, LinearLayout.LayoutParams(-1, dp(64)).apply { bottomMargin = dp(8) })
|
|
}
|
|
if (PlannerStore.conflictCount(this) > 0) {
|
|
space(agenda, 12)
|
|
agenda.addView(button("동시에 수정된 내용 확인", true) { planner.conflict() }, LinearLayout.LayoutParams(-1, dp(48)))
|
|
}
|
|
space(content, 16)
|
|
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.pattern.joinToString(" → ") { it.title }, 14f, muted))
|
|
space(settings, 4)
|
|
settings.addView(label(if (configured) "첫째 날: ${schedule.anchor}" else "시작 날짜를 저장하면 위젯에도 반영됩니다.", 12f, muted))
|
|
space(settings, 14)
|
|
settings.addView(button("당직 기초 설정", true) { showSettings() }, LinearLayout.LayoutParams(-1, dp(48)))
|
|
space(settings, 8)
|
|
settings.addView(button("옵션 · 날짜 색상과 음력") { showOptions() }, LinearLayout.LayoutParams(-1, dp(48)))
|
|
space(content, 12)
|
|
content.addView(button("위젯 꾸미기 · 투명도와 크기") { WidgetStyleDialog.show(this) }, LinearLayout.LayoutParams(-1, dp(48)))
|
|
content.addView(button("홈 화면에 달력 추가") { pinWidget() }, LinearLayout.LayoutParams(-1, dp(52)))
|
|
space(content, 10)
|
|
content.addView(label("위젯은 앱을 닫아도 홈 화면에 표시됩니다.\n홈 화면을 길게 누른 뒤 ‘위젯’에서도 추가할 수 있습니다.", 12f, muted).apply { gravity = Gravity.CENTER })
|
|
space(content, 20)
|
|
val holidayInfo = card(content)
|
|
holidayInfo.addView(label("대한민국 공휴일", 17f, ink, true))
|
|
space(holidayInfo, 6)
|
|
val updateTime = Holidays.updatedAt(this)
|
|
val updated = if (updateTime == 0L) "기본 공휴일 자료를 사용 중입니다." else "최근 갱신: " + java.text.SimpleDateFormat("yyyy.MM.dd HH:mm", Locale.KOREAN).format(java.util.Date(updateTime))
|
|
holidayInfo.addView(label(if (month.year in Holidays.years(this)) "공휴일과 대체공휴일을 자동으로 갱신합니다.\n$updated" + if (Holidays.usesSaved(this)) "\n서버에 보관된 정상 자료를 사용합니다." else "" else "${month.year}년 자료가 아직 제공되지 않았습니다.\n공휴일이 없는 것으로 판단하지 마세요.", 12f, muted))
|
|
space(holidayInfo, 10)
|
|
holidayInfo.addView(button("공휴일 새로고침") {
|
|
Holidays.refresh(this, force = true) { success -> runOnUiThread {
|
|
if (!isFinishing && !isDestroyed) {
|
|
render()
|
|
Toast.makeText(this, if (success) { if (Holidays.usesSaved(this)) "제공처 확인이 지연되어 저장된 공휴일을 표시합니다." else "공휴일을 갱신했습니다." } else "연결을 확인해 주세요. 저장된 공휴일을 계속 표시합니다.", Toast.LENGTH_LONG).show()
|
|
}
|
|
} }
|
|
}, LinearLayout.LayoutParams(-1, dp(44)))
|
|
space(holidayInfo, 8)
|
|
holidayInfo.addView(label("음력 표시: 1900~2050년 · 한국 음력 기준", 11f, muted).apply {
|
|
setOnClickListener { AlertDialog.Builder(this@MainActivity).setTitle("음력 자료 이용 조건").setMessage(assets.open("lunar-LICENSE.txt").bufferedReader().use { it.readText() }).setPositiveButton("확인", null).show() }
|
|
})
|
|
holidayInfo.addView(label("월력요항 기반 공개 자료 · holidays-kr\n공휴일에도 설정한 근무 순서는 유지됩니다.", 11f, muted).apply {
|
|
setOnClickListener {
|
|
val license = assets.open("holidays-LICENSE.txt").bufferedReader().use { it.readText() }
|
|
AlertDialog.Builder(this@MainActivity).setTitle("공휴일 자료 출처")
|
|
.setMessage("https://github.com/hyunbinseo/holidays-kr\n\n월력요항을 기반으로 관리되는 공개 자료입니다. 임시공휴일은 제공 자료가 갱신된 뒤 반영됩니다.\n\n$license")
|
|
.setPositiveButton("확인", null).show()
|
|
}
|
|
})
|
|
space(content, 24)
|
|
content.addView(button("앱 업데이트 확인") { UpdateChecker.check(this, force = true) }, LinearLayout.LayoutParams(-1, dp(48)))
|
|
space(content, 12)
|
|
content.addView(label("제작자 블리어 (이창현)", 13f, muted).apply { gravity = Gravity.CENTER })
|
|
space(content, 4)
|
|
content.addView(label("당직근무 " + packageManager.getPackageInfo(packageName, 0).versionName, 11f, muted).apply { gravity = Gravity.CENTER })
|
|
scroll.post {
|
|
if (generation == renderGeneration) {
|
|
scroll.scrollTo(0, scrollOffset)
|
|
restoringScroll = false
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 기준일을 저장한 뒤 홈 화면에 위젯 추가를 요청한다. 최종 배치와 크기는 홈 화면 앱이 관리한다.
|
|
* 바로 추가하는 기능을 지원하지 않는 홈 화면에서는 위젯 목록으로 추가하는 방법을 안내한다.
|
|
* 별도 오버레이 권한을 요구하지 않으며 일반적인 안드로이드 위젯으로 동작한다.
|
|
*/
|
|
private fun pinWidget() {
|
|
if (!ScheduleStore.isConfigured(this)) { showSettings(); return }
|
|
val manager = getSystemService(AppWidgetManager::class.java)
|
|
if (manager.isRequestPinAppWidgetSupported) {
|
|
AlertDialog.Builder(this).setTitle("위젯 크기 선택 · 가로×세로")
|
|
.setItems(WidgetKind.entries.map{it.title}.toTypedArray()){_,index->
|
|
manager.requestPinAppWidget(WidgetKind.entries[index].component(this),null,null)
|
|
}.setNegativeButton("취소",null).show()
|
|
} else {
|
|
AlertDialog.Builder(this).setTitle("홈 화면에 추가하기").setMessage("홈 화면의 빈 곳을 길게 누른 뒤 위젯 목록에서 ‘당직근무’를 선택해 주세요.").setPositiveButton("확인", null).show()
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 설정 창에서는 저장값을 복사한 임시 목록만 바꾼다. 취소하면 기존 근무표에 영향을 주지 않는다.
|
|
* 반복 일수가 늘어나면 추가된 날은 일반근무로 채운다. 줄어들면 뒤쪽 날을 잘라낸다.
|
|
* 저장을 누를 때만 기준일과 전체 순서를 함께 반영하고 모든 홈 위젯을 갱신한다.
|
|
*/
|
|
private fun showSettings() {
|
|
val current = ScheduleStore.load(this)
|
|
var anchor = current.anchor
|
|
val form = column().apply { setPadding(dp(20), dp(8), dp(20), dp(8)) }
|
|
form.addView(label("전체 기간의 기본 근무표입니다. 특정 날짜부터 바뀌는 제도는 옵션 → 근무 관리 → 근무제 변경 이력에서 추가하세요.\n날짜 색상과 음력은 옵션에서 바꿀 수 있습니다.", 12f, muted))
|
|
val patternEditor = ShiftPatternEditor(this, current.pattern, current.workWeek)
|
|
form.addView(patternEditor)
|
|
space(form, 12)
|
|
form.addView(label("1일째에 해당하는 날짜", 14f, ink, true))
|
|
lateinit var dateButton: Button
|
|
dateButton = button(anchor.toString()) {
|
|
DatePickerDialog(this, { _, year, monthIndex, day ->
|
|
anchor = LocalDate.of(year, monthIndex + 1, day)
|
|
dateButton.text = anchor.toString()
|
|
}, anchor.year, anchor.monthValue - 1, anchor.dayOfMonth).show()
|
|
}
|
|
space(form, 8)
|
|
form.addView(dateButton, LinearLayout.LayoutParams(-1, dp(48)))
|
|
space(form, 10)
|
|
form.addView(label("선택한 날짜부터 위 순서가 반복됩니다.\n비번과 휴일을 포함해 날짜 단위로 계산합니다.", 12f, muted))
|
|
val scroll = ScrollView(this).apply { addView(form) }
|
|
val dialog = AlertDialog.Builder(this).setTitle("당직 기초 설정").setView(scroll)
|
|
.setNegativeButton("취소", null).setPositiveButton("저장", null).create()
|
|
dialog.setOnShowListener {
|
|
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
|
|
// 기초 설정에서 표시 옵션을 저장하지 않는다. 창을 연 뒤 들어온 최신 표시 선택도 보존한다.
|
|
runCatching { ScheduleStore.save(this, ScheduleStore.load(this).copy(anchor = anchor, pattern = patternEditor.pattern(), workWeek = patternEditor.workWeek())) }
|
|
.onSuccess { render(); dialog.dismiss(); Toast.makeText(this, "근무표와 위젯을 갱신했습니다.", Toast.LENGTH_SHORT).show() }
|
|
.onFailure { Toast.makeText(this, it.message ?: "입력 내용을 확인해 주세요.", Toast.LENGTH_LONG).show() }
|
|
}
|
|
}
|
|
dialog.show()
|
|
}
|
|
|
|
/** 계산 기준과 표시 선택을 분리한다. 취소는 저장하지 않으며 옵션 저장도 근무 순서를 바꾸지 않는다. */
|
|
private fun showOptions() {
|
|
val form=column().apply { setPadding(dp(20),dp(8),dp(20),dp(16)) }
|
|
val dialog=AlertDialog.Builder(this).setTitle("설정").setView(ScrollView(this).apply{addView(form)}).setNegativeButton("닫기",null).create()
|
|
fun group(title:String,description:String,action:()->Unit) {
|
|
space(form,12)
|
|
form.addView(button(title){dialog.dismiss();action()},LinearLayout.LayoutParams(-1,dp(48)))
|
|
form.addView(label(description,12f,muted))
|
|
}
|
|
group("당직 기초 설정","근무 유형 · 반복 순서 · 기준일 · 주5일·주6일제",::showSettings)
|
|
group("달력 표시","주 시작 · 날짜 색상 · 음력 · 일반근무 이름과 숨기기",::showDisplayOptions)
|
|
group("이름 표시","${Shift.REGULAR.title} 아래 이름 · 다른 사람 주기 · 요일과 간격") { WorkNameDialogs(this){render()}.open() }
|
|
group("일정·알림","일정과 알바 · 기념일 · 휴대폰 알림") {
|
|
AlertDialog.Builder(this).setTitle("일정·알림").setItems(arrayOf("일정 찾기 · 다가오는 일정","일정 추가","알바·시간근무 추가","내 생일·기념일","휴대폰 알림 허용")){_,index->
|
|
when(index){0->AgendaDialogs(this){render()}.open();1->planner.event(selectedDate);2->planner.event(selectedDate,partTime=true);3->anniversaries.list();else->Reminders.requestPermission(this)}
|
|
}.setNegativeButton("닫기",null).show()
|
|
}
|
|
group("달력 연동·공유","휴대폰 기본 달력 · 다른 달력 · 웹과 소속") { deviceCalendar.open() }
|
|
group("근무 관리","날짜별 변경 · 변경 이력 · 통계 · 출력 · 휴지통") { WorkPlanDialogs(this){render()}.open(selectedDate) }
|
|
group("위젯 꾸미기","크기 · 투명도 · 글자 · 표시 항목") { WidgetStyleDialog.show(this) }
|
|
dialog.show()
|
|
}
|
|
|
|
private fun showDisplayOptions() {
|
|
val current = ScheduleStore.load(this)
|
|
val form = column().apply { setPadding(dp(20), dp(8), dp(20), dp(16)) }
|
|
form.addView(label("달력 표시", 16f, ink, true))
|
|
form.addView(label(if (SyncClient.connected(this)) "${SyncClient.memberName(this)} 계정에 개인 설정을 보관합니다." else "현재 기기에 저장합니다. 회원 로그인 후 서버에 보관할 수 있습니다.", 12f, muted))
|
|
form.addView(label("앱과 홈 위젯에 함께 적용합니다.\n근무 순서와 기준일은 바뀌지 않습니다.", 12f, muted))
|
|
space(form, 12)
|
|
form.addView(label("주 시작 요일", 14f, ink, true))
|
|
val weekStart = Spinner(this).apply {
|
|
adapter = ArrayAdapter(this@MainActivity, android.R.layout.simple_spinner_dropdown_item, listOf("월요일 시작", "일요일 시작"))
|
|
setSelection(if (current.weekStart == 1) 0 else 1)
|
|
contentDescription = "주 시작 요일"
|
|
}
|
|
form.addView(weekStart, LinearLayout.LayoutParams(-1, dp(48)))
|
|
fun choice(title: String, description: String, checked: Boolean): CheckBox {
|
|
val option = CheckBox(this).apply { text = title; textSize = 14f; isChecked = checked; minHeight = dp(48) }
|
|
space(form, 8); form.addView(option); form.addView(label(description, 12f, muted))
|
|
return option
|
|
}
|
|
val weekday = choice("당직일은 평일색으로 표시", "주말·공휴일에도 당직 날짜는 평일색으로 표시합니다.", current.dutyAsWeekday)
|
|
val off = choice("비번을 빨간색으로 표시", "비번 날짜와 비번 글씨를 빨간색으로 표시합니다.", current.offAsHoliday)
|
|
val lunar = choice("음력 날짜 함께 보기", "양력 아래에 작은 글씨로 표시합니다. 윤달은 윤으로 구분합니다.", current.showLunar)
|
|
space(form, 16)
|
|
form.addView(label("일반근무 이름", 14f, ink, true))
|
|
val regularName = EditText(this).apply {
|
|
setSingleLine(true); hint = Shift.REGULAR.defaultTitle; setText(ScheduleStore.regularName(this@MainActivity))
|
|
filters = arrayOf(android.text.InputFilter.LengthFilter(ShiftNames.MAX_LENGTH * 2)); contentDescription = "일반근무 이름"; minHeight = dp(48)
|
|
}
|
|
form.addView(regularName, LinearLayout.LayoutParams(-1, -2))
|
|
form.addView(label("주간·일근처럼 직장에서 부르는 이름으로 바꿀 수 있습니다. ${ShiftNames.MAX_LENGTH}자까지 쓰고 비우면 일반근무로 돌아갑니다. 달력 칸에는 세 글자까지 그대로 보이고 더 길면 앞 두 글자만 보입니다. 근무 순서는 바뀌지 않습니다.", 12f, muted))
|
|
val hideRegular = choice("달력 칸에서 일반근무 글자 숨기기", "앱 달력과 위젯 및 근무표 그림의 일반근무 날에 근무 글자를 넣지 않습니다. 오늘 카드와 날짜 상세에는 그대로 보이고 기본 달력 반영과 구독에는 그대로 보냅니다.", ScheduleStore.hideRegular(this))
|
|
val dialog = AlertDialog.Builder(this).setTitle("달력 표시").setView(ScrollView(this).apply { addView(form) })
|
|
.setNegativeButton("취소", null).setPositiveButton("저장", null).create()
|
|
dialog.setOnShowListener {
|
|
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
|
|
runCatching { ScheduleStore.saveDisplay(this, weekday.isChecked, lunar.isChecked, off.isChecked, if (weekStart.selectedItemPosition == 0) 1 else 0, regularName = regularName.text.toString(), hideRegular = hideRegular.isChecked) }
|
|
.onSuccess { render(); dialog.dismiss(); Toast.makeText(this, "표시 옵션을 저장했습니다.", Toast.LENGTH_SHORT).show() }
|
|
.onFailure { Toast.makeText(this, it.message ?: "저장 공간을 확인해 주세요.", Toast.LENGTH_LONG).show() }
|
|
}
|
|
}
|
|
dialog.show()
|
|
}
|
|
|
|
override fun onRequestPermissionsResult(requestCode:Int,permissions:Array<out String>,grantResults:IntArray) {
|
|
super.onRequestPermissionsResult(requestCode,permissions,grantResults)
|
|
deviceCalendar.permissionResult(requestCode,grantResults)
|
|
if(requestCode==CalendarMirrorDialogs.REQUEST) {
|
|
if(CalendarMirror.allowed(this))CalendarMirrorDialogs(this).open()
|
|
else Toast.makeText(this,"기본 달력 자동 반영에는 달력 읽기와 쓰기 권한이 필요합니다.",Toast.LENGTH_LONG).show()
|
|
}
|
|
if(requestCode==Reminders.REQUEST_NOTIFY) {
|
|
Reminders.reschedule(this)
|
|
Toast.makeText(this,if(grantResults.firstOrNull()==android.content.pm.PackageManager.PERMISSION_GRANTED)"일정 알림을 켰습니다." else "알림을 허용하면 저장한 일정의 알림을 받을 수 있습니다.",Toast.LENGTH_LONG).show()
|
|
}
|
|
}
|
|
}
|