기본 달력 자동 반영과 평일 이름 표시 및 설정 분류 추가
일반근무 아래 이름을 작게 표시한다. 다른 사람의 당직 주기와 매주 요일 및 날짜 간격을 선택하며 회원별 규칙을 보관한다. 당직 기초와 달력 표시 및 이름 표시와 일정·알림 및 달력 연동·공유와 위젯 꾸미기로 설정을 나눴다. 제목과 메모로 다가오는 일정도 찾을 수 있다. Android Calendar Provider에 선택한 근무와 일정 및 기념일을 자동 반영한다. 로그인 없이 나의 근무표를 보낼 수 있다. 기기별 소유 표식을 확인한 사본만 수정하고 삭제한다. 외부 일정은 보존하며 자동 반영한 사본을 다시 가져오는 중복도 막았다. 원본 수정은 당직근무에서 한다. 회원이 선택한 범위로 ICS 구독 주소와 파일을 만든다. 구독 비밀값은 해시로 보관하고 재발급과 종료 및 회원 정지를 적용한다. calendar_feeds 테이블을 추가했다. 기존 회원과 근무 및 소속 자료 이전은 없다. 구독 경로의 프록시 로그에는 비밀 주소 대신 고정 경로와 응답 상태를 남긴다. 주요 파일은 WorkNames와 NameRule 및 CalendarMirror와 설정 화면과 일정 검색이다. 서버는 work_names.py와 calendar_export.py 및 calendar_sharing.py와 웹 설정을 추가했다. 사용법과 제작 매뉴얼 및 배포 절차를 함께 갱신했다. 앞으로도 검증을 마친 기능과 배포 단위마다 Gitea와 포럼에 기록한다. 앱 단위 검사 42개와 서버 검사 74개 통과. 웹 이름·주 시작·반복·음력·업데이트 검사 및 JavaScript 문법 검사 통과. 정적 검사 오류 0개와 경고 80개. 공개 ZIP을 새 폴더에 풀어 앱 빌드 통과. Android API 36에서 달력 등록·재실행 중복 방지·제목 수정·원본 삭제·앱 사본만 삭제를 확인했다. 위젯 크기와 주 시작도 재검사했다. 웹에서 이름 저장과 표시 및 ICS 파일 다운로드와 일정 검색을 확인했다. 0.13.0과 설치 번호 17 및 웹 2026-11-21.3으로 운영 반영했다. 변경 전 소스와 회원 DB 및 공휴일 DB와 프록시 설정은 보조서버 비공개 20261121-calendar-bridge 백업에 보관했다. 기존 회원과 근무 및 소속 행 전체와 관리자 월요일 시작을 보존했다. 다른 컨테이너와 원격 작업 세션은 유지했다. 기본 달력에서 역방향 자동 수정은 지원하지 않으며 외부 구독 갱신 시간과 제조사별 실물 달력 화면은 별도 확인이 필요하다.
This commit is contained in:
1 parent
30d2fb26c7
commit
45ca9f675e
44 files changed
+1182
-55
No files matched your search
@@ -0,0 +1,35 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.text.Editable
|
||||
import android.text.TextWatcher
|
||||
import android.widget.*
|
||||
import org.json.JSONObject
|
||||
import java.time.LocalDate
|
||||
|
||||
/** 앞으로 90일의 일정과 기념일을 제목·메모로 찾는다. 조회는 기기 자료만 사용해 연결이 끊겨도 동작한다. */
|
||||
class AgendaDialogs(private val activity:Activity,private val changed:()->Unit) {
|
||||
fun open(){
|
||||
val form=LinearLayout(activity).apply{orientation=LinearLayout.VERTICAL;val p=(20*resources.displayMetrics.density).toInt();setPadding(p,p,p,p)}
|
||||
val search=EditText(activity).apply{hint="제목이나 메모 검색";setSingleLine(true);contentDescription="일정 검색"};form.addView(search)
|
||||
form.addView(TextView(activity).apply{text="오늘부터 90일 · 날짜를 누르면 해당 일정을 수정합니다.";textSize=12f})
|
||||
val rows=LinearLayout(activity).apply{orientation=LinearLayout.VERTICAL};form.addView(rows)
|
||||
val items=PlannerStore.items(activity).filter{it.getString("kind")=="event"}
|
||||
val found=mutableListOf<Pair<LocalDate,JSONObject>>()
|
||||
val seen=mutableSetOf<String>()
|
||||
for(offset in 0L..89L){val day=LocalDate.now().plusDays(offset)
|
||||
items.forEach{item->PlannerStore.eventRule(item.getJSONObject("data")).occurrenceOn(day)?.let{start->if(seen.add(item.getString("id")+":"+start))found.add(start to item)}}
|
||||
Anniversaries.on(activity,day).forEach{found.add(day to it)}
|
||||
}
|
||||
val dialog=AlertDialog.Builder(activity).setTitle("일정 찾기 · 다가오는 일정").setView(ScrollView(activity).apply{addView(form)}).setNegativeButton("닫기",null).create()
|
||||
fun render(){
|
||||
rows.removeAllViews();val query=search.text.toString().trim();val filtered=found.filter{(_,item)->val d=item.getJSONObject("data");(d.getString("title")+" "+d.optString("notes")).contains(query,true)}
|
||||
if(filtered.isEmpty())rows.addView(TextView(activity).apply{text="해당 일정이 없습니다."})
|
||||
filtered.take(100).forEach{(day,item)->val d=item.getJSONObject("data");rows.addView(Button(activity).apply{text="$day · ${d.getString("title")}\n"+(if(item.getString("kind")=="anniversary")Anniversaries.description(d) else PlannerStore.timeSummary(d));isAllCaps=false;setOnClickListener{dialog.dismiss();if(item.getString("kind")=="anniversary")AnniversaryDialogs(activity,changed).edit(item) else PlannerDialogs(activity,changed).event(day,item)}})}
|
||||
if(filtered.size>100)rows.addView(TextView(activity).apply{text="100개까지 표시합니다. 검색어를 입력해 범위를 좁혀 주세요."})
|
||||
}
|
||||
search.addTextChangedListener(object:TextWatcher{override fun beforeTextChanged(s:CharSequence?,start:Int,count:Int,after:Int)=Unit;override fun onTextChanged(s:CharSequence?,start:Int,before:Int,count:Int)=render();override fun afterTextChanged(s:Editable?)=Unit})
|
||||
render();dialog.show()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.Manifest
|
||||
import android.app.job.JobInfo
|
||||
import android.app.job.JobParameters
|
||||
import android.app.job.JobScheduler
|
||||
import android.app.job.JobService
|
||||
import android.content.ComponentName
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.provider.CalendarContract
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
import java.time.ZoneOffset
|
||||
import java.time.temporal.ChronoUnit
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.ScheduledFuture
|
||||
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)
|
||||
|
||||
/** 휴대폰 달력은 이 앱 자료의 읽기용 사본이다. 원본 편집은 당직근무에서 하고 변경된 사본만 갱신한다.
|
||||
* 앱 전용 표식이 정확히 일치하는 행만 수정한다. 다른 앱 일정과 수동으로 만든 일정은 건드리지 않는다.
|
||||
* 전체 출력 목록을 만든 뒤 쓰기 때문에 자료 변환 실패가 기존 달력의 일괄 삭제로 이어지지 않는다.
|
||||
*/
|
||||
object CalendarMirror {
|
||||
private const val JOB=2104
|
||||
private val executor=Executors.newSingleThreadScheduledExecutor()
|
||||
private var waiting:ScheduledFuture<*>?=null
|
||||
fun prefs(context:Context)=context.getSharedPreferences("calendar_mirror",0)
|
||||
fun allowed(context:Context)=listOf(Manifest.permission.READ_CALENDAR,Manifest.permission.WRITE_CALENDAR).all{context.checkSelfPermission(it)==PackageManager.PERMISSION_GRANTED}
|
||||
fun enabled(context:Context)=prefs(context).getBoolean("enabled",false)
|
||||
private fun owner(context:Context):String {
|
||||
val file=File(context.noBackupFilesDir,"calendar-mirror-owner")
|
||||
if(!file.exists())file.writeText(UUID.randomUUID().toString())
|
||||
return file.readText().trim().also{require(runCatching{UUID.fromString(it)}.isSuccess)}
|
||||
}
|
||||
@Synchronized fun request(context:Context) {
|
||||
if(!enabled(context))return
|
||||
val app=context.applicationContext
|
||||
schedule(app);waiting?.cancel(false)
|
||||
waiting=executor.schedule({refresh(app)},800,TimeUnit.MILLISECONDS)
|
||||
}
|
||||
fun schedule(context:Context) {
|
||||
if(enabled(context))context.getSystemService(JobScheduler::class.java).schedule(JobInfo.Builder(JOB,ComponentName(context,CalendarMirrorService::class.java)).setPersisted(true).setPeriodic(24*60*60*1000L).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) {
|
||||
require(!enabled(context)||prefs(context).getLong("calendar",-1)==calendar){"대상 달력을 바꾸려면 기존 자동 반영을 먼저 해제해 주세요."}
|
||||
require(rotation||events||anniversaries){"반영할 항목을 하나 이상 선택해 주세요."}
|
||||
check(prefs(context).edit().putLong("calendar",calendar).putString("title",title).putBoolean("rotation",rotation).putBoolean("events",events).putBoolean("anniversaries",anniversaries).putBoolean("enabled",true).commit())
|
||||
request(context)
|
||||
}
|
||||
fun stop(context:Context,remove:Boolean,done:(Boolean)->Unit) {
|
||||
// 쓰기와 해제를 같은 큐에서 처리해 해제 완료 뒤 대기 중인 쓰기가 다시 들어가지 않게 한다.
|
||||
executor.execute {
|
||||
val ok=runCatching {
|
||||
prefs(context).edit().putBoolean("enabled",false).commit()
|
||||
context.getSystemService(JobScheduler::class.java).cancel(JOB)
|
||||
if(remove){check(allowed(context));owned(context,prefs(context).getLong("calendar",-1)).forEach{row->delete(context,row.id,row.marker)}}
|
||||
prefs(context).edit().putString("status",if(remove)"자동 반영 해제 · 등록한 사본 삭제" else "자동 반영 해제 · 기존 사본 유지").commit()
|
||||
}.isSuccess;done(ok)
|
||||
}
|
||||
}
|
||||
private data class Stored(val id:Long,val marker:String,val event:MirroredEvent)
|
||||
private fun owned(context:Context,calendar:Long):List<Stored> {
|
||||
val prefix="dutycalendar://mirror/${owner(context)}/"
|
||||
val rows=mutableListOf<Stored>()
|
||||
val projection=arrayOf("_id","customAppUri","title","description","dtstart","dtend","allDay")
|
||||
val cursor=checkNotNull(context.contentResolver.query(CalendarContract.Events.CONTENT_URI,projection,"calendar_id=? AND customAppPackage=? AND deleted=0",arrayOf(calendar.toString(),context.packageName),null)){"달력 자료를 읽지 못했습니다."}
|
||||
cursor.use{while(it.moveToNext()){val marker=it.getString(1).orEmpty();if(marker.startsWith(prefix))rows.add(Stored(it.getLong(0),marker,MirroredEvent(marker.removePrefix(prefix),it.getString(2).orEmpty(),it.getString(3).orEmpty(),it.getLong(4),it.getLong(5),it.getInt(6)==1)))}}
|
||||
return rows
|
||||
}
|
||||
// 개별 이벤트 URI는 Android Provider가 추가 선택 조건을 거부한다. 목록 URI에서 ID와 소유 표식을 함께 검사한다.
|
||||
private fun delete(context:Context,id:Long,marker:String) = context.contentResolver.delete(CalendarContract.Events.CONTENT_URI,"_id=? AND customAppPackage=? AND customAppUri=?",arrayOf(id.toString(),context.packageName,marker))
|
||||
private fun values(context:Context,calendar:Long,event:MirroredEvent,marker:String)=ContentValues().apply {
|
||||
put(CalendarContract.Events.CALENDAR_ID,calendar);put(CalendarContract.Events.TITLE,event.title);put(CalendarContract.Events.DESCRIPTION,event.notes)
|
||||
put(CalendarContract.Events.DTSTART,event.start);put(CalendarContract.Events.DTEND,event.end);put(CalendarContract.Events.ALL_DAY,if(event.allDay)1 else 0)
|
||||
put(CalendarContract.Events.EVENT_TIMEZONE,if(event.allDay)"UTC" else "Asia/Seoul")
|
||||
put(CalendarContract.Events.CUSTOM_APP_PACKAGE,context.packageName);put(CalendarContract.Events.CUSTOM_APP_URI,marker)
|
||||
put(CalendarContract.Events.AVAILABILITY,CalendarContract.Events.AVAILABILITY_FREE);put(CalendarContract.Events.HAS_ALARM,0)
|
||||
}
|
||||
private fun refresh(context:Context):Boolean {
|
||||
if(!enabled(context))return true
|
||||
return runCatching {
|
||||
check(allowed(context)){"달력 권한을 허용하면 자동 반영을 다시 시작합니다."}
|
||||
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))
|
||||
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
|
||||
if(old==null)checkNotNull(context.contentResolver.insert(CalendarContract.Events.CONTENT_URI,values(context,calendar,event,marker))){"달력에 저장하지 못했습니다."}
|
||||
else if(old.event!=event)check(context.contentResolver.update(CalendarContract.Events.CONTENT_URI,values(context,calendar,event,marker),"_id=? AND customAppPackage=? AND customAppUri=?",arrayOf(old.id.toString(),context.packageName,old.marker))==1){"달력 변경을 저장하지 못했습니다."}
|
||||
rows.drop(1).forEach{delete(context,it.id,it.marker)}
|
||||
}
|
||||
val keys=desired.map{it.key}.toSet()
|
||||
existing.filterKeys{it !in keys}.values.flatten().forEach{delete(context,it.id,it.marker)}
|
||||
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):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"}
|
||||
fun add(event:MirroredEvent){output[event.key]=event;require(output.size<=10000){"일정이 10,000개를 넘습니다. 반영할 항목을 줄여 주세요."}}
|
||||
for(offset in 0L..ChronoUnit.DAYS.between(first,last)){
|
||||
val day=first.plusDays(offset)
|
||||
if(rotation&&ScheduleStore.isConfigured(context)){
|
||||
val names=WorkNames.on(context,day,schedule).joinToString(" · "){it.name}
|
||||
add(allDay("rotation:$day",schedule.shiftOn(day).title+(if(names.isNotBlank())" · $names" else ""),"당직근무에서 수정하면 자동으로 반영됩니다.",day))
|
||||
}
|
||||
if(anniversaries)for(item in Anniversaries.on(context,day)){val d=item.getJSONObject("data");add(allDay("anniversary:${item.getString("id")}:$day",d.getString("title"),d.getString("notes"),day))}
|
||||
}
|
||||
if(events)for(item in items){
|
||||
val d=item.getJSONObject("data");val rule=PlannerStore.eventRule(d)
|
||||
val length=ChronoUnit.DAYS.between(rule.start,rule.end)
|
||||
val begin=maxOf(first.minusDays(length),rule.start)
|
||||
for(offset in 0L..ChronoUnit.DAYS.between(begin,last)){
|
||||
val day=begin.plusDays(offset)
|
||||
if(rule.occurrenceOn(day)==day)add(event("event:${item.getString("id")}:$day",d,day))
|
||||
}
|
||||
}
|
||||
return output.values.toList()
|
||||
}
|
||||
internal fun allDay(key:String,title:String,notes:String,day:LocalDate)=MirroredEvent(key,title,notes,day.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli(),day.plusDays(1).atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli(),true)
|
||||
internal fun event(key:String,data:JSONObject,start:LocalDate):MirroredEvent {
|
||||
val length=ChronoUnit.DAYS.between(LocalDate.parse(data.getString("date")),LocalDate.parse(data.getString("endDate")))
|
||||
val allDay=data.getBoolean("allDay");val zone=if(allDay)ZoneOffset.UTC else ZoneId.of("Asia/Seoul")
|
||||
val begin=if(allDay)start.atStartOfDay(zone) else start.atTime(LocalTime.parse(data.getString("startTime"))).atZone(zone)
|
||||
val end=if(allDay)start.plusDays(length+1).atStartOfDay(zone) else start.plusDays(length).atTime(LocalTime.parse(data.getString("endTime"))).atZone(zone)
|
||||
return MirroredEvent(key,data.getString("title"),data.getString("notes"),begin.toInstant().toEpochMilli(),end.toInstant().toEpochMilli(),allDay)
|
||||
}
|
||||
}
|
||||
|
||||
class CalendarMirrorService:JobService() {
|
||||
override fun onStartJob(params:JobParameters):Boolean { CalendarMirror.run(applicationContext){jobFinished(params,!it)};return true }
|
||||
override fun onStopJob(params:JobParameters)=true
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.content.ContentUris
|
||||
import android.content.ContentValues
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.provider.CalendarContract
|
||||
import android.widget.*
|
||||
|
||||
class CalendarMirrorDialogs(private val activity:Activity) {
|
||||
companion object {const val REQUEST=7202}
|
||||
fun open() {
|
||||
if(!CalendarMirror.allowed(activity)){activity.requestPermissions(arrayOf(Manifest.permission.READ_CALENDAR,Manifest.permission.WRITE_CALENDAR),REQUEST);return}
|
||||
val settings=CalendarMirror.prefs(activity)
|
||||
if(CalendarMirror.enabled(activity)){
|
||||
val status=settings.getString("status","첫 반영 대기 중")
|
||||
AlertDialog.Builder(activity).setTitle("기본 달력 자동 반영").setMessage("대상: ${settings.getString("title","")}\n$status\n\n당직근무 → 기본 달력으로 반영합니다. 기본 달력에서 바꾼 내용은 당직근무로 가져오지 않으며 다음 반영 때 원본으로 돌아갑니다.")
|
||||
.setItems(arrayOf("지금 다시 반영","반영 항목 변경","자동 반영 해제")){_,index->when(index){0->CalendarMirror.run(activity){ok->activity.runOnUiThread{toast(if(ok)"달력 반영을 완료했습니다." else CalendarMirror.prefs(activity).getString("status","").orEmpty())}};1->options(settings.getLong("calendar",-1),settings.getString("title","").orEmpty());else->stop()}}
|
||||
.setNegativeButton("닫기",null).show()
|
||||
}else pick()
|
||||
}
|
||||
private fun toast(value:String)=Toast.makeText(activity,value,Toast.LENGTH_LONG).show()
|
||||
private fun pick() {
|
||||
runCatching {
|
||||
val rows=mutableListOf<Pair<Long,String>>()
|
||||
activity.contentResolver.query(CalendarContract.Calendars.CONTENT_URI,arrayOf("_id","calendar_displayName","account_name"),"calendar_access_level>=?",arrayOf(CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR.toString()),null)?.use{while(it.moveToNext())rows.add(it.getLong(0) to "${it.getString(1)} · ${it.getString(2)}")}
|
||||
AlertDialog.Builder(activity).setTitle("자동 반영할 달력 선택").setItems((rows.map{it.second}+"이 휴대폰에 전용 달력 만들기").toTypedArray()){_,index->
|
||||
if(index<rows.size)options(rows[index].first,rows[index].second)
|
||||
else runCatching{createLocal()}.onSuccess{options(it,"당직근무 · 이 휴대폰")}.onFailure{toast("전용 달력을 만들지 못했습니다. 달력 앱에서 쓰기 가능한 계정을 먼저 추가해 주세요.")}
|
||||
}.setNegativeButton("취소",null).show()
|
||||
}.onFailure{toast("휴대폰 달력 연결과 권한을 확인해 주세요.")}
|
||||
}
|
||||
private fun createLocal():Long {
|
||||
val uri=CalendarContract.Calendars.CONTENT_URI.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER,"true").appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME,"당직근무").appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE,CalendarContract.ACCOUNT_TYPE_LOCAL).build()
|
||||
val values=ContentValues().apply{
|
||||
put(CalendarContract.Calendars.ACCOUNT_NAME,"당직근무");put(CalendarContract.Calendars.ACCOUNT_TYPE,CalendarContract.ACCOUNT_TYPE_LOCAL)
|
||||
put(CalendarContract.Calendars.NAME,"duty-calendar-local");put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,"당직근무")
|
||||
put(CalendarContract.Calendars.CALENDAR_COLOR,0xFF365FAD.toInt());put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,CalendarContract.Calendars.CAL_ACCESS_OWNER)
|
||||
put(CalendarContract.Calendars.OWNER_ACCOUNT,"당직근무");put(CalendarContract.Calendars.VISIBLE,1);put(CalendarContract.Calendars.SYNC_EVENTS,1)
|
||||
put(CalendarContract.Calendars.CALENDAR_TIME_ZONE,java.time.ZoneId.systemDefault().id)
|
||||
}
|
||||
return ContentUris.parseId(checkNotNull(activity.contentResolver.insert(uri,values)))
|
||||
}
|
||||
private fun options(calendar:Long,title:String){
|
||||
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 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()
|
||||
dialog.setOnShowListener{dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener{
|
||||
runCatching{CalendarMirror.configure(activity,calendar,title,rotation.isChecked,events.isChecked,annual.isChecked)}.onSuccess{dialog.dismiss();toast("자동 반영을 시작했습니다. 기본 달력 앱에서 대상 달력을 표시해 주세요.")}.onFailure{toast(it.message?:"항목을 확인해 주세요.")}
|
||||
}};dialog.show()
|
||||
}
|
||||
private fun stop(){AlertDialog.Builder(activity).setTitle("자동 반영 해제").setMessage("당직근무가 등록한 사본을 함께 지울 수 있습니다. 다른 앱에서 만든 일정은 유지합니다.")
|
||||
.setPositiveButton("사본도 삭제"){_,_->CalendarMirror.stop(activity,true){ok->activity.runOnUiThread{toast(if(ok)"자동 반영을 끄고 사본을 삭제했습니다." else "자동 반영은 껐지만 사본 삭제를 완료하지 못했습니다. 달력 권한을 확인해 주세요.")}}}
|
||||
.setNeutralButton("사본 유지"){_,_->CalendarMirror.stop(activity,false){_->activity.runOnUiThread{toast("자동 반영을 껐습니다. 기존 사본은 유지됩니다.")}}}.setNegativeButton("취소",null).show()}
|
||||
fun website(){activity.startActivity(Intent(Intent.ACTION_VIEW,Uri.parse(SyncClient.WEB_URL+"#calendar-sharing")))}
|
||||
}
|
||||
@@ -109,6 +109,7 @@ object CompactWidgetViews {
|
||||
}
|
||||
private fun detail(context:Context,date:LocalDate,schedule:Schedule,style:WidgetStyle):String {
|
||||
val values=mutableListOf<String>()
|
||||
if(style.people)values.addAll(WorkNames.on(context,date,schedule).map{it.name})
|
||||
if(style.lunar&&schedule.showLunar)LunarDates.label(context,date)?.let{values.add(it)}
|
||||
if(style.holidays)Holidays.name(context,date)?.let{values.add(it)}
|
||||
if(style.anniversaries)Anniversaries.on(context,date).firstOrNull()?.let{values.add(it.getJSONObject("data").getString("title"))}
|
||||
|
||||
@@ -45,14 +45,21 @@ class DeviceCalendar(private val activity: Activity, private val changed: () ->
|
||||
}
|
||||
}
|
||||
fun open() {
|
||||
AlertDialog.Builder(activity).setTitle("휴대폰 달력 연동")
|
||||
.setMessage("휴대폰 달력에서 선택한 일정만 가져옵니다. 반복 일정은 선택한 날짜의 한 회차를 복사합니다.\n\n앱의 일정을 보내려면 저장된 일정이나 기념일을 열고 ‘휴대폰 달력에 보내기’를 누르세요. 달력 앱에서 최종 저장합니다.\n\n서로의 수정과 삭제를 자동 반영하는 방식은 아닙니다.")
|
||||
.setPositiveButton("일정 가져오기"){_,_->
|
||||
if(activity.checkSelfPermission(Manifest.permission.READ_CALENDAR)==PackageManager.PERMISSION_GRANTED)pickCalendar()
|
||||
else activity.requestPermissions(arrayOf(Manifest.permission.READ_CALENDAR),REQUEST_READ)
|
||||
AlertDialog.Builder(activity).setTitle("달력 연동·공유")
|
||||
.setItems(arrayOf("기본 달력에 자동 반영","휴대폰 일정 선택해서 가져오기","다른 달력 구독 주소·파일 내보내기")){_,index->
|
||||
when(index){
|
||||
0->CalendarMirrorDialogs(activity).open()
|
||||
1->{if(activity.checkSelfPermission(Manifest.permission.READ_CALENDAR)==PackageManager.PERMISSION_GRANTED)pickCalendar() else activity.requestPermissions(arrayOf(Manifest.permission.READ_CALENDAR),REQUEST_READ)}
|
||||
else->CalendarMirrorDialogs(activity).website()
|
||||
}
|
||||
}.setNegativeButton("닫기",null).show()
|
||||
}
|
||||
fun permissionResult(code:Int,results:IntArray) {
|
||||
if(code==CalendarMirrorDialogs.REQUEST){
|
||||
if(CalendarMirror.allowed(activity))CalendarMirrorDialogs(activity).open()
|
||||
else Toast.makeText(activity,"자동 반영은 달력 읽기와 쓰기 권한이 필요합니다. 기존 일정은 유지됩니다.",Toast.LENGTH_LONG).show()
|
||||
return
|
||||
}
|
||||
if(code!=REQUEST_READ)return
|
||||
if(results.firstOrNull()==PackageManager.PERMISSION_GRANTED)pickCalendar()
|
||||
else Toast.makeText(activity,"달력 읽기를 허용하면 선택한 일정을 가져올 수 있습니다.",Toast.LENGTH_LONG).show()
|
||||
@@ -74,8 +81,9 @@ class DeviceCalendar(private val activity: Activity, private val changed: () ->
|
||||
runCatching {
|
||||
val prefs=activity.getSharedPreferences("device_calendar",0)
|
||||
val salt=prefs.getString("id",null)?:UUID.randomUUID().toString().also{prefs.edit().putString("id",it).commit()}
|
||||
activity.contentResolver.query(uri,arrayOf("event_id","title","begin","end","allDay","description"),"calendar_id=?",arrayOf(calendar.toString()),"begin ASC")?.use{cursor->
|
||||
activity.contentResolver.query(uri,arrayOf("event_id","title","begin","end","allDay","description","customAppPackage"),"calendar_id=?",arrayOf(calendar.toString()),"begin ASC")?.use{cursor->
|
||||
while(cursor.moveToNext()&&candidates.size<100){
|
||||
if(cursor.getString(6)==activity.packageName)continue
|
||||
val allDay=cursor.getInt(4)==1;val eventZone=if(allDay)ZoneOffset.UTC else zone
|
||||
val begin=Instant.ofEpochMilli(cursor.getLong(2)).atZone(eventZone);val finish=Instant.ofEpochMilli(cursor.getLong(3)).atZone(eventZone)
|
||||
if(!finish.isAfter(begin))continue
|
||||
|
||||
@@ -152,7 +152,9 @@ open class DutyWidget : AppWidgetProvider() {
|
||||
val lunar = if (schedule.showLunar&&style.lunar&&!compact) LunarDates.label(context, date) else null
|
||||
val heading = number + (lunar?.let { "\n$it" } ?: "")
|
||||
val shiftStart = heading.length + 1
|
||||
val baseText = "$heading\n${shift.shortTitle}" + (holidayShort?.let { "\n$it" } ?: "")
|
||||
val workNames = if (style.people && !compact) WorkNames.on(context, date, schedule) else emptyList()
|
||||
val workLabel = workNames.take(2).joinToString("\n") { it.name.take(5) }
|
||||
val baseText = "$heading\n${shift.shortTitle}" + (if (workLabel.isNotBlank()) "\n$workLabel" else "") + (holidayShort?.let { "\n$it" } ?: "")
|
||||
val colleagues = People.onDuty(people, date)
|
||||
// 작은 위젯에는 두 줄까지만 표시한다. 사람이 많아도 날짜의 높이와 정렬을 유지하고 전체 이름은 눌러서 확인한다.
|
||||
val names = if (colleagues.size > 2) listOf(colleagues.first().name.take(3), "외${colleagues.size - 1}명") else colleagues.map { it.name.take(3) }
|
||||
@@ -176,6 +178,13 @@ open class DutyWidget : AppWidgetProvider() {
|
||||
styled.setSpan(ForegroundColorSpan(if (colleagues.size > 2 && i == 1) style.muted else style.color(colleagues[i].color)), nameStart, nameStart + name.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
nameStart += name.length + 1
|
||||
}
|
||||
var workStart = shiftStart + shift.shortTitle.length + 1
|
||||
workNames.take(2).forEach { name ->
|
||||
val end = workStart + name.name.take(5).length
|
||||
styled.setSpan(RelativeSizeSpan(0.8f), workStart, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
styled.setSpan(ForegroundColorSpan(style.color(name.color)), workStart, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
workStart = end + 1
|
||||
}
|
||||
if (YearMonth.from(date) != month) {
|
||||
styled.setSpan(ForegroundColorSpan(0xFF9AA4B3.toInt()), 0, cellText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
}
|
||||
|
||||
@@ -74,6 +74,7 @@ class MainActivity : Activity() {
|
||||
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)
|
||||
Holidays.refresh(this) { success -> if (success) runOnUiThread { if (!isFinishing && !isDestroyed) render() } }
|
||||
SyncClient.schedule(this)
|
||||
@@ -165,6 +166,7 @@ class MainActivity : Activity() {
|
||||
val lunar = if (schedule.showLunar) LunarDates.label(this, date) else null
|
||||
val events = PlannerStore.eventsOn(this, date)
|
||||
val personalDays = Anniversaries.on(this, date)
|
||||
val workNames = WorkNames.on(this, date, schedule)
|
||||
val colleagues = People.onDuty(people, date)
|
||||
val inside = YearMonth.from(date) == month
|
||||
val cell = column().apply {
|
||||
@@ -180,6 +182,8 @@ class MainActivity : Activity() {
|
||||
setPadding(dp(4), dp(2), dp(4), dp(2))
|
||||
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
|
||||
})
|
||||
@@ -189,7 +193,7 @@ class MainActivity : Activity() {
|
||||
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}개. 기념일: ${personalDays.joinToString { it.getJSONObject("data").getString("title") }}. 함께 당직: ${colleagues.joinToString { it.name }}"
|
||||
contentDescription = "${date.monthValue}월 ${date.dayOfMonth}일 ${shift.title} ${lunar.orEmpty()} ${holiday.orEmpty()} 일정 ${events.size}개. 일반근무 이름: ${workNames.joinToString { it.name }}. 기념일: ${personalDays.joinToString { it.getJSONObject("data").getString("title") }}. 함께 당직: ${colleagues.joinToString { it.name }}"
|
||||
isFocusable = true
|
||||
setOnClickListener {
|
||||
selectedDate = date
|
||||
@@ -199,11 +203,11 @@ class MainActivity : Activity() {
|
||||
.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${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("나: ${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()) 103 else 148) + if (schedule.showLunar) 14 else 0), 1f))
|
||||
cells.addView(cell, LinearLayout.LayoutParams(0, dp((if (people.isEmpty() && WorkNames.rules(this).isEmpty()) 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)
|
||||
@@ -397,12 +401,31 @@ class MainActivity : Activity() {
|
||||
|
||||
/** 계산 기준과 표시 선택을 분리한다. 취소는 저장하지 않으며 옵션 저장도 근무 순서를 바꾸지 않는다. */
|
||||
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("이름 표시","일반근무 아래 이름 · 다른 사람 주기 · 요일과 간격") { 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("위젯 꾸미기","크기 · 투명도 · 글자 · 표시 항목") { 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(button("위젯 꾸미기 · 투명도와 크기") { WidgetStyleDialog.show(this) }, LinearLayout.LayoutParams(-1,dp(48)))
|
||||
form.addView(button("휴대폰 달력 연동") { deviceCalendar.open() }, LinearLayout.LayoutParams(-1,dp(48)))
|
||||
form.addView(label("앱과 홈 위젯에 함께 적용합니다.\n근무 순서와 기준일은 바뀌지 않습니다.", 12f, muted))
|
||||
space(form, 12)
|
||||
form.addView(label("주 시작 요일", 14f, ink, true))
|
||||
@@ -420,7 +443,7 @@ class MainActivity : Activity() {
|
||||
val weekday = choice("당직일은 평일색으로 표시", "주말·공휴일에도 당직 날짜는 평일색으로 표시합니다.", current.dutyAsWeekday)
|
||||
val off = choice("비번을 빨간색으로 표시", "비번 날짜와 비번 글씨를 빨간색으로 표시합니다.", current.offAsHoliday)
|
||||
val lunar = choice("음력 날짜 함께 보기", "양력 아래에 작은 글씨로 표시합니다. 윤달은 윤으로 구분합니다.", current.showLunar)
|
||||
val dialog = AlertDialog.Builder(this).setTitle("옵션").setView(ScrollView(this).apply { addView(form) })
|
||||
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 {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import java.time.LocalDate
|
||||
import java.time.temporal.ChronoUnit
|
||||
|
||||
/** 이름은 근무 자체를 바꾸지 않는 보조 표시다. 평일 일반근무에만 붙여 휴무나 당직과 혼동하지 않게 한다.
|
||||
* 간격은 기준일 이후 달력 날짜로 센다. 주말을 건너뛰어도 다음 표시 날짜를 당기지 않는다.
|
||||
*/
|
||||
data class NameRule(val mode: String, val anchor: LocalDate, val interval: Int, val weekdays: Set<Int>) {
|
||||
init {
|
||||
require(mode in setOf("PERSON", "WEEKLY", "INTERVAL")) { "이름 표시 방식을 선택해 주세요." }
|
||||
require(anchor.year in 2000..2099 && interval in 1..366) { "기준일과 1~366일 간격을 확인해 주세요." }
|
||||
require(weekdays.isNotEmpty() && weekdays.all { it in 1..5 }) { "표시할 평일을 선택해 주세요." }
|
||||
}
|
||||
fun matches(date: LocalDate, ownShift: Shift, holiday: Boolean, personShift: Shift? = null): Boolean {
|
||||
if (ownShift != Shift.REGULAR || holiday || date.dayOfWeek.value !in 1..5) return false
|
||||
return when (mode) {
|
||||
"PERSON" -> personShift == Shift.DUTY
|
||||
"WEEKLY" -> date.dayOfWeek.value in weekdays && date >= anchor
|
||||
else -> date >= anchor && ChronoUnit.DAYS.between(anchor, date) % interval == 0L && date.dayOfWeek.value in weekdays
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -157,6 +157,7 @@ class PlannerDialogs(private val activity: Activity, private val changed: () ->
|
||||
val data = item.getJSONObject("data")
|
||||
if (item.getString("kind") == "anniversary") return "${data.getString("title")}\n${Anniversaries.description(data)}\n${data.getString("notes")}"
|
||||
if (item.getString("kind") == "preferences") return "당직일 평일색: ${if (data.getBoolean("dutyAsWeekday")) "켜짐" else "꺼짐"}\n비번 빨간색: ${if (data.getBoolean("offAsHoliday")) "켜짐" else "꺼짐"}\n음력 표시: ${if (data.getBoolean("showLunar")) "켜짐" else "꺼짐"}\n주 시작: ${if (data.optInt("weekStart", 0) == 1) "월요일" else "일요일"}"
|
||||
if (item.getString("kind") == "name_rule") return data.getString("name") + "\n" + WorkNames.description(data)
|
||||
if (item.getString("kind") == "person") return "${data.getString("name")} · ${People.colors.getValue(data.getString("color")).first}\n첫째 날: ${data.getString("anchor")}\n" + PlannerStore.listStrings(data.getJSONArray("pattern")).joinToString(" → ") { Shift.valueOf(it).title }
|
||||
if (item.getString("kind") == "rotation") return "첫째 날: ${data.getString("anchor")}\n" + (0 until data.getJSONArray("pattern").length()).joinToString(" → ") { Shift.valueOf(data.getJSONArray("pattern").getString(it)).title }
|
||||
return "${data.getString("title")}\n${data.getString("date")} ~ ${data.getString("endDate")}\n" + (if (data.getBoolean("allDay")) "하루 종일" else "${data.getString("startTime")} ~ ${data.getString("endTime")}") + "\n${categoryName(data.getString("category"))}\n${data.getString("notes")}"
|
||||
|
||||
@@ -64,6 +64,13 @@ object PlannerStore {
|
||||
People.validate(data)
|
||||
require(items(context).count { it.getString("kind") == "person" && it.getString("id") != id } < 20) { "함께 볼 사람은 20명까지 등록할 수 있습니다." }
|
||||
}
|
||||
if (kind == "name_rule") {
|
||||
require(SyncClient.connected(context)) { "이름 표시는 회원 로그인 후 사용할 수 있습니다." }
|
||||
if (!deleted) {
|
||||
WorkNames.validate(data)
|
||||
require(items(context).count { it.getString("kind") == "name_rule" && it.getString("id") != id } < 20) { "이름 표시 규칙은 20개까지 등록할 수 있습니다." }
|
||||
}
|
||||
}
|
||||
val document = read(context)
|
||||
val pending = list(document.getJSONArray("pending"))
|
||||
val previous = pending.find { it.getString("id") == id }
|
||||
@@ -73,6 +80,7 @@ object PlannerStore {
|
||||
document.put("pending", JSONArray(pending.filter { it.getString("id") != id } + operation))
|
||||
document.put("conflicts", JSONArray(strings(document.getJSONArray("conflicts")).filter { it != previous?.getString("changeId") }))
|
||||
save(context, document)
|
||||
CalendarMirror.request(context)
|
||||
DutyWidget.updateAll(context)
|
||||
Reminders.reschedule(context)
|
||||
}
|
||||
@@ -88,6 +96,7 @@ object PlannerStore {
|
||||
document.put("conflicts", JSONArray((strings(document.getJSONArray("conflicts")) + result?.optJSONArray("conflicts")?.let(::strings).orEmpty()).distinct().filter { it in ids }))
|
||||
save(context, document)
|
||||
applyRotation(context)
|
||||
CalendarMirror.request(context)
|
||||
DutyWidget.updateAll(context)
|
||||
Reminders.reschedule(context)
|
||||
}
|
||||
@@ -131,6 +140,7 @@ object PlannerStore {
|
||||
document.put("pending", JSONArray(pending))
|
||||
save(context, document)
|
||||
applyRotation(context)
|
||||
CalendarMirror.request(context)
|
||||
DutyWidget.updateAll(context)
|
||||
Reminders.reschedule(context)
|
||||
}
|
||||
|
||||
@@ -77,6 +77,7 @@ object Reminders {
|
||||
|
||||
class ReminderReceiver:BroadcastReceiver() {
|
||||
override fun onReceive(context:Context,intent:Intent) {
|
||||
CalendarMirror.request(context)
|
||||
val pending=goAsync()
|
||||
Thread{try{runCatching{Reminders.receive(context.applicationContext,intent)}}finally{pending.finish()}}.start()
|
||||
}
|
||||
|
||||
@@ -41,6 +41,7 @@ object ScheduleStore {
|
||||
PlannerStore.queuePreferences(context, load(context))
|
||||
SyncClient.sync(context)
|
||||
}
|
||||
CalendarMirror.request(context)
|
||||
DutyWidget.updateAll(context)
|
||||
}
|
||||
fun save(context: Context, schedule: Schedule, fromSync: Boolean = false) {
|
||||
@@ -59,6 +60,7 @@ object ScheduleStore {
|
||||
PlannerStore.queueRotation(context, schedule)
|
||||
SyncClient.sync(context)
|
||||
}
|
||||
CalendarMirror.request(context)
|
||||
DutyWidget.updateAll(context)
|
||||
}
|
||||
}
|
||||
@@ -71,6 +71,7 @@ object SyncClient {
|
||||
context.getSharedPreferences("web_sync", Context.MODE_PRIVATE).edit().putBoolean("enabled", false).commit()
|
||||
background(); context.getSystemService(JobScheduler::class.java).apply { cancel(2102); cancel(2103) }
|
||||
file(context).delete(); message = "웹 연동 꺼짐 · 이 기기에 저장"
|
||||
CalendarMirror.request(context)
|
||||
DutyWidget.updateAll(context)
|
||||
Reminders.reschedule(context)
|
||||
if (previous != null) executor.execute { runCatching { request(context.applicationContext, "logout", JSONObject(), tokenOverride = previous) } }
|
||||
@@ -79,6 +80,7 @@ object SyncClient {
|
||||
// 인증이 끝난 뒤에는 회원용 근무표를 표시하지 않는다. 개인 자료는 재로그인을 위해 보관한다.
|
||||
file(context).delete()
|
||||
context.getSystemService(JobScheduler::class.java).apply { cancel(2102); cancel(2103) }
|
||||
CalendarMirror.request(context)
|
||||
DutyWidget.updateAll(context)
|
||||
Reminders.reschedule(context)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.app.DatePickerDialog
|
||||
import android.text.InputFilter
|
||||
import android.view.View
|
||||
import android.widget.*
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.time.LocalDate
|
||||
import java.util.UUID
|
||||
|
||||
/** 표시 규칙은 회원별 자료로 저장한다. 취소하면 원본을 유지하며 사람을 지워도 임의의 다른 사람으로 연결하지 않는다. */
|
||||
class WorkNameDialogs(private val activity: Activity, private val changed: () -> Unit) {
|
||||
private fun dp(n: Int) = (n * activity.resources.displayMetrics.density).toInt()
|
||||
fun open() {
|
||||
if (!SyncClient.connected(activity)) { Toast.makeText(activity, "이름 표시는 회원 로그인 후 사용할 수 있습니다.", Toast.LENGTH_LONG).show(); return }
|
||||
val items = WorkNames.rules(activity)
|
||||
AlertDialog.Builder(activity).setTitle("일반근무 아래 이름 표시")
|
||||
.setItems(items.map { val d=it.getJSONObject("data"); "${d.getString("name")} · ${WorkNames.description(d)}" }.toTypedArray()) { _, index -> edit(items[index]) }
|
||||
.setPositiveButton("이름 추가") { _, _ -> edit() }.setNegativeButton("닫기", null).show()
|
||||
}
|
||||
private fun edit(item: JSONObject? = null) {
|
||||
val data = item?.getJSONObject("data")
|
||||
var anchor = data?.getString("anchor")?.let(LocalDate::parse) ?: LocalDate.now()
|
||||
val form = LinearLayout(activity).apply { orientation=LinearLayout.VERTICAL; setPadding(dp(20),dp(8),dp(20),dp(16)) }
|
||||
fun caption(value:String) { form.addView(TextView(activity).apply { text=value; textSize=14f; setPadding(0,dp(12),0,dp(6)) }) }
|
||||
fun spinner(title:String, values:List<String>, selected:Int=0):Spinner { caption(title); return Spinner(activity).apply { contentDescription=title; adapter=ArrayAdapter(activity,android.R.layout.simple_spinner_dropdown_item,values); setSelection(selected.coerceAtLeast(0)); form.addView(this) } }
|
||||
caption("월~금 중 내 일반근무일에만 이름을 작게 표시합니다. 공휴일과 당직·비번·휴무에는 표시하지 않습니다.")
|
||||
val enabled=CheckBox(activity).apply { text="이름 표시 사용"; isChecked=data?.optBoolean("enabled")?:true };form.addView(enabled)
|
||||
caption("표시 이름")
|
||||
val name=EditText(activity).apply { setSingleLine(true); hint="예: 김민수"; setText(data?.optString("name")); filters=arrayOf(InputFilter.LengthFilter(30)) };form.addView(name)
|
||||
val colorKeys=People.colors.keys.toList()
|
||||
val color=spinner("이름 색상",People.colors.values.map{it.first},colorKeys.indexOf(data?.optString("color")?:"BLUE"))
|
||||
val modes=listOf("PERSON","WEEKLY","INTERVAL")
|
||||
val mode=spinner("표시 기준",listOf("다른 사람의 당직 주기","매주 선택한 요일","기준일부터 며칠 간격"),modes.indexOf(data?.optString("mode")?:"WEEKLY"))
|
||||
val people=People.all(activity)
|
||||
// 연결된 사람이 사라졌을 때 첫 번째 사람을 대신 선택하지 않는다. 반드시 다시 선택하게 한다.
|
||||
val person=spinner("연결할 근무표",listOf("사람 선택")+people.map{it.name},people.indexOfFirst{it.id==data?.optString("personId")}+1)
|
||||
caption("기준일 · 이날부터 표시")
|
||||
val date=Button(activity).apply { text=anchor.toString() };date.setOnClickListener { DatePickerDialog(activity,{_,y,m,d->anchor=LocalDate.of(y,m+1,d);date.text=anchor.toString()},anchor.year,anchor.monthValue-1,anchor.dayOfMonth).show() };form.addView(date)
|
||||
caption("반복 간격 · 1~366일")
|
||||
val interval=EditText(activity).apply { inputType=android.text.InputType.TYPE_CLASS_NUMBER;setText((data?.optInt("interval")?:1).toString());contentDescription="이름 반복 간격" };form.addView(interval)
|
||||
caption("표시할 요일 · 간격 방식에서도 선택한 평일만 표시")
|
||||
val chosen=data?.getJSONArray("weekdays")?.let{(0 until it.length()).map(it::getInt).toSet()}?:setOf(1,2,3,4,5)
|
||||
val weekdays=(1..5).map { day -> CheckBox(activity).apply { text=listOf("", "월요일", "화요일", "수요일", "목요일", "금요일")[day];isChecked=day in chosen;form.addView(this) } }
|
||||
mode.onItemSelectedListener=object:AdapterView.OnItemSelectedListener {
|
||||
override fun onNothingSelected(p:AdapterView<*>?)=Unit
|
||||
override fun onItemSelected(p:AdapterView<*>?,v:View?,position:Int,id:Long) { person.isEnabled=position==0; name.isEnabled=position!=0; date.isEnabled=position!=0; interval.isEnabled=position==2; weekdays.forEach{it.isEnabled=position!=0} }
|
||||
}
|
||||
val error=TextView(activity).apply{setTextColor(0xFFAD3D6E.toInt())};form.addView(error)
|
||||
val builder=AlertDialog.Builder(activity).setTitle(if(item==null)"이름 표시 추가" else "이름 표시 수정").setView(ScrollView(activity).apply{addView(form)}).setNegativeButton("취소",null).setPositiveButton("저장",null)
|
||||
if(item!=null)builder.setNeutralButton("삭제",null)
|
||||
val dialog=builder.create();dialog.setOnShowListener {
|
||||
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
|
||||
runCatching {
|
||||
val selected=people.getOrNull(person.selectedItemPosition-1)
|
||||
require(mode.selectedItemPosition!=0||selected!=null){"연결할 사람을 선택해 주세요. 함께 보는 근무표에서 먼저 추가할 수 있습니다."}
|
||||
val result=JSONObject().put("enabled",enabled.isChecked).put("name",if(mode.selectedItemPosition==0)selected!!.name else name.text.toString().trim())
|
||||
.put("color",colorKeys[color.selectedItemPosition]).put("mode",modes[mode.selectedItemPosition]).put("personId",selected?.id?:"")
|
||||
.put("anchor",anchor.toString()).put("interval",if(mode.selectedItemPosition==2)interval.text.toString().toIntOrNull()?:0 else 1)
|
||||
.put("weekdays",JSONArray(if(mode.selectedItemPosition==0)listOf(1,2,3,4,5) else weekdays.mapIndexedNotNull{i,check->if(check.isChecked)i+1 else null}))
|
||||
PlannerStore.put(activity,item?.getString("id")?:UUID.randomUUID().toString(),"name_rule",result)
|
||||
}.onSuccess{SyncClient.sync(activity);changed();dialog.dismiss()}.onFailure{error.text=it.message?:"입력 내용을 확인해 주세요."}
|
||||
}
|
||||
if(item!=null)dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener {
|
||||
AlertDialog.Builder(activity).setTitle("이 이름 표시를 삭제할까요?").setMessage("연결된 사람의 근무표는 그대로 둡니다.").setNegativeButton("취소",null).setPositiveButton("삭제"){_,_->
|
||||
runCatching{PlannerStore.put(activity,item.getString("id"),"name_rule",JSONObject(),true)}.onSuccess{SyncClient.sync(activity);changed();dialog.dismiss()}.onFailure{error.text=it.message}
|
||||
}.show()
|
||||
}
|
||||
};dialog.show()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONObject
|
||||
import java.time.LocalDate
|
||||
|
||||
data class WorkName(val name: String, val color: Int)
|
||||
|
||||
object WorkNames {
|
||||
fun rules(context: Context) = if (SyncClient.connected(context)) PlannerStore.items(context).filter { it.getString("kind") == "name_rule" } else emptyList()
|
||||
fun rule(data: JSONObject) = NameRule(data.getString("mode"), LocalDate.parse(data.getString("anchor")), data.getInt("interval"),
|
||||
(0 until data.getJSONArray("weekdays").length()).map { data.getJSONArray("weekdays").getInt(it) }.toSet())
|
||||
fun validate(data: JSONObject) {
|
||||
require(data.optString("name").trim().length in 1..30) { "이름은 1~30자로 입력해 주세요." }
|
||||
require(data.optString("color") in People.colors) { "이름 색상을 선택해 주세요." }
|
||||
require(data.get("enabled") is Boolean) { "표시 여부를 확인해 주세요." }
|
||||
rule(data)
|
||||
require(data.getString("mode") != "PERSON" || data.optString("personId").isNotBlank()) { "근무표를 연결할 사람을 선택해 주세요." }
|
||||
}
|
||||
fun on(context: Context, date: LocalDate, schedule: Schedule = ScheduleStore.load(context)): List<WorkName> {
|
||||
val people = People.all(context).associateBy { it.id }
|
||||
return rules(context).mapNotNull { item ->
|
||||
val data = item.getJSONObject("data")
|
||||
val person = people[data.optString("personId")]
|
||||
if (!data.optBoolean("enabled") || !rule(data).matches(date, schedule.shiftOn(date), Holidays.name(context, date) != null, person?.schedule?.shiftOn(date))) null
|
||||
else WorkName(if (data.getString("mode") == "PERSON") person!!.name else data.getString("name"), People.colors.getValue(data.getString("color")).second)
|
||||
}.distinctBy { it.name }
|
||||
}
|
||||
fun description(data: JSONObject): String = when (data.getString("mode")) {
|
||||
"PERSON" -> "연결한 사람의 당직일"
|
||||
"WEEKLY" -> "매주 " + rule(data).weekdays.sorted().joinToString("·") { listOf("", "월", "화", "수", "목", "금")[it] }
|
||||
else -> "${data.getString("anchor")}부터 ${data.getInt("interval")}일 간격"
|
||||
} + if (data.optBoolean("enabled")) "" else " · 표시 꺼짐"
|
||||
}
|
||||
Reference in new issue
Block a user