당직근무 0.10.0 소스와 위젯 꾸미기 및 제작 매뉴얼 공개

위젯별 투명도와 밝은·어두운 색상 및 글자 크기와 표시 항목을 추가했다.
모든 위젯에 함께 적용하는 기본값과 개별 설정을 구분하고 크기에 따라 배치를 바꾼다.
포럼에 APK와 전체 소스 및 사용법과 제작 매뉴얼을 함께 배포한다.

앱 단위 검사 34개와 서버 검사 63개 및 웹 날짜·업데이트 검사 통과.
공개 소스에서 APK 빌드와 정적 검사 오류 0개 확인. 경고는 69개다.
Android 16 가상 기기에서 기존 앱 위에 설치하고 투명 위젯과 큰 글자 및 RemoteViews 검사를 확인했다.
실제 휴대폰과 다른 홈 화면 앱의 절전·크기 동작은 별도 확인이 필요하다.
회원 DB와 인증 정보 및 배포 서명 키와 내부 운영 기록은 공개 자료에 포함하지 않았다.
This commit is contained in:
블리어 committed 2026-11-20 10:00:42 +00:00
commit 8112721fa8
96 files changed
+7495

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
# 당직근무 웹 서버
제작자 블리어 (이창현) · 0.10.0
설치와 초기 관리자 등록 및 검사와 백업은 [웹 서버 제작 매뉴얼](../docs/제작매뉴얼-웹서버.md)에 정리했습니다. 서버를 실행하기 전에 데이터 경로와 HTTPS 주소를 맞추세요. 운영 DB와 보호 키 및 인증 정보는 이 저장소와 소스 ZIP에 포함하지 않습니다.
[구조와 동기화](../docs/구조와동기화.md) · [배포 절차](../docs/배포절차.md)
+669
View File
@@ -0,0 +1,669 @@
"""당직 달력의 개인 일정 저장과 기기 연결 및 변경 알림을 담당한다.
각 캘린더는 홈페이지 회원에게 귀속된다. 다른 기기도 같은 회원으로 로그인해야 한다.
비밀번호는 해시로 저장하며 원본 인증값은 데이터베이스와 접근 로그에 남기지 않는다.
일정별 버전을 비교해 오래된 화면이 다른 기기의 수정을 조용히 덮어쓰지 못하게 한다.
"""
import asyncio
import company
from personal import validate_personal, mirror_display, validate_event_options
import hashlib
import hmac
import json
import os
from pathlib import Path
import re
import secrets
import sqlite3
import time
from contextlib import asynccontextmanager, contextmanager, suppress
from datetime import date, datetime
from urllib.request import Request as UrlRequest, urlopen
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse, JSONResponse
from argon2 import PasswordHasher
from argon2.exceptions import VerificationError, InvalidHashError
ROOT = Path(__file__).parent
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"
COOKIE = "__Secure-duty_session"
pepper_file = DATA / "pairing.key"
if not pepper_file.exists():
fd = os.open(pepper_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "wb") as stream:
stream.write(secrets.token_bytes(32))
PEPPER = pepper_file.read_bytes()
changed = asyncio.Condition()
limits = {}
passwords = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=1)
# 존재하지 않는 아이디도 같은 암호 검사를 거쳐 응답 시간으로 가입 여부를 쉽게 구분하지 못하게 한다.
dummy_password = passwords.hash(secrets.token_urlsafe(32))
password_gate = asyncio.Semaphore(2)
from holiday_store import HolidayStore
holidays = HolidayStore(DATA, ROOT / "web/holidays.json")
def refresh_holidays():
holidays.refresh()
@asynccontextmanager
async def lifespan(application):
async def refresh_loop():
while True:
await asyncio.to_thread(refresh_holidays)
await asyncio.sleep(3600)
task = asyncio.create_task(refresh_loop()) if os.environ.get("DUTY_REFRESH", "1") == "1" else None
yield
if task:
task.cancel()
with suppress(asyncio.CancelledError):
await task
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
@contextmanager
def db():
"""짧은 읽기나 쓰기 작업마다 연결한다. 예외로 끝난 쓰기는 연결 종료 때 되돌아간다."""
connection = sqlite3.connect(DATA / "calendar.sqlite3", timeout=10)
connection.row_factory = sqlite3.Row
connection.execute("PRAGMA foreign_keys=ON")
try:
yield connection
connection.commit()
finally:
connection.close()
with db() as conn:
conn.execute("PRAGMA journal_mode=WAL")
conn.executescript("""
CREATE TABLE IF NOT EXISTS calendars(id TEXT PRIMARY KEY, revision INTEGER NOT NULL DEFAULT 0);
CREATE TABLE IF NOT EXISTS clients(hash TEXT PRIMARY KEY, calendar TEXT NOT NULL REFERENCES calendars(id) ON DELETE CASCADE, expires INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS pairs(hash TEXT PRIMARY KEY, calendar TEXT NOT NULL REFERENCES calendars(id) ON DELETE CASCADE, expires INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS items(calendar TEXT NOT NULL REFERENCES calendars(id) ON DELETE CASCADE, id TEXT NOT NULL, kind TEXT NOT NULL, version INTEGER NOT NULL, deleted INTEGER NOT NULL, data TEXT NOT NULL, PRIMARY KEY(calendar,id));
CREATE TABLE IF NOT EXISTS applied(client TEXT NOT NULL REFERENCES clients(hash) ON DELETE CASCADE, change_id TEXT NOT NULL, created INTEGER NOT NULL, PRIMARY KEY(client,change_id));
CREATE INDEX IF NOT EXISTS clients_calendar ON clients(calendar);
CREATE TABLE IF NOT EXISTS members(
id TEXT PRIMARY KEY, username TEXT NOT NULL UNIQUE, display_name TEXT NOT NULL,
password_hash TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'member', active INTEGER NOT NULL DEFAULT 1,
must_change INTEGER NOT NULL DEFAULT 0, created INTEGER NOT NULL, last_login INTEGER NOT NULL DEFAULT 0,
calendar TEXT NOT NULL UNIQUE REFERENCES calendars(id) ON DELETE CASCADE,
reset_hash TEXT, reset_expires INTEGER NOT NULL DEFAULT 0);
CREATE TABLE IF NOT EXISTS member_audit(id INTEGER PRIMARY KEY, actor TEXT NOT NULL, target TEXT NOT NULL,
action TEXT NOT NULL, created INTEGER NOT NULL);
""")
company.init_schema(conn)
# 이전 일정 구조는 그대로 둔다. 회원에 연결되지 않은 옛 익명 인증값은 새 접근 검사에서 거절한다.
columns = {row[1] for row in conn.execute("PRAGMA table_info(clients)")}
if "member" not in columns:
conn.execute("ALTER TABLE clients ADD COLUMN member TEXT REFERENCES members(id) ON DELETE CASCADE")
if "kind" not in columns:
conn.execute("ALTER TABLE clients ADD COLUMN kind TEXT NOT NULL DEFAULT 'legacy'")
def digest(value):
return hashlib.sha256(value.encode()).hexdigest()
def pair_hash(value):
return hmac.new(PEPPER, value.encode(), hashlib.sha256).hexdigest()
def throttle(request, label, count, seconds):
# 프록시가 전달한 주소는 uvicorn이 로컬 프록시에서 온 경우에만 신뢰한다.
# 연결 코드 대입과 공개 캘린더 생성 횟수를 제한한다. 주소 원문은 저장하지 않는다.
now = time.monotonic()
if len(limits) > 10000:
for key in list(limits):
if limits[key][1] < now:
del limits[key]
key = (digest(request.client.host), label)
used, until = limits.get(key, (0, now + seconds))
if until < now:
used, until = 0, now + seconds
if used >= count:
raise HTTPException(429, "요청이 많습니다. 잠시 후 다시 시도해 주세요.")
limits[key] = (used + 1, until)
@app.middleware("http")
async def boundaries(request: Request, call_next):
# 브라우저 쓰기 요청은 같은 출처와 전용 헤더를 모두 확인한다.
# 쿠키는 HttpOnly와 Secure로 설정하고 요청 본문 크기는 프록시와 앱에서 함께 제한한다.
if request.method in ("POST", "PUT", "DELETE"):
if request.headers.get("origin") not in (None, ORIGIN):
return JSONResponse({"detail": "허용되지 않은 요청 출처입니다."}, 403)
if request.headers.get("x-duty-request") != "1" or not request.headers.get("content-type", "").startswith("application/json"):
return JSONResponse({"detail": "잘못된 요청 형식입니다."}, 403)
body = await request.body()
if len(body) > 262144:
return JSONResponse({"detail": "한 번에 저장할 수 있는 크기를 넘었습니다."}, 413)
response = await call_next(request)
response.headers["Cache-Control"] = "no-store"
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["Referrer-Policy"] = "no-referrer"
response.headers["Content-Security-Policy"] = "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"
return response
def identity(request, allow_password_change=False):
auth = request.headers.get("authorization", "")
token = auth[7:] if auth.startswith("Bearer ") else request.cookies.get(COOKIE, "")
if not re.fullmatch(r"[A-Za-z0-9_-]{43}", token):
raise HTTPException(401, "홈페이지 회원 로그인이 필요합니다.")
with db() as conn:
row = conn.execute("""SELECT c.*,m.username,m.display_name,m.role,m.must_change
FROM clients c JOIN members m ON m.id=c.member
WHERE c.hash=? AND c.expires>? AND m.active=1 AND c.calendar=m.calendar""",
(digest(token), int(time.time()))).fetchone()
if row is None:
raise HTTPException(401, "로그인이 만료됐거나 이용이 중지됐습니다. 다시 로그인해 주세요.")
result = dict(row)
if result["must_change"] and not allow_password_change:
raise HTTPException(403, "홈페이지에서 초기 비밀번호를 먼저 변경해 주세요.")
return result
async def payload(request):
try:
body = await request.json()
if not isinstance(body, dict):
raise ValueError()
return body
except (ValueError, UnicodeError):
raise HTTPException(400, "입력 내용을 확인해 주세요.")
def profile(row):
return {"id": row["member"] if "member" in row.keys() else row["id"], "username": row["username"],
"displayName": row["display_name"], "calendarId": row["calendar"], "role": row["role"], "mustChangePassword": bool(row["must_change"])}
def new_client(conn, member, kind):
token = secrets.token_urlsafe(32)
duration = (30 if kind == "web" else 365) * 86400
conn.execute("INSERT INTO clients(hash,calendar,expires,member,kind) VALUES(?,?,?,?,?)",
(digest(token), member["calendar"], int(time.time()) + duration, member["id"], kind))
response = JSONResponse({"connected": True, "member": profile(member), **({"token": token} if kind == "android" else {})})
if kind == "web":
response.set_cookie(COOKIE, token, max_age=duration, path=PREFIX + "/", secure=True, httponly=True, samesite="strict")
return response
def credentials(data, new_password=False):
username = data.get("username", "")
password = data.get("password", "")
if not isinstance(username, str) or not re.fullmatch(r"[a-z0-9_]{3,32}", username.strip().lower()):
raise HTTPException(400, "아이디는 영문 소문자와 숫자 및 밑줄로 3~32자 입력해 주세요.")
if not isinstance(password, str) or not (6 if new_password else 1) <= len(password) <= 128:
raise HTTPException(400, "비밀번호는 6~128자로 입력해 주세요.")
return username.strip().lower(), password
async def hash_password(value):
# 암호 계산은 별도 스레드에서 두 개까지만 수행한다. 접속이 몰려도 일정 조회를 막지 않는다.
async with password_gate:
return await asyncio.to_thread(passwords.hash, value)
async def verify_password(hashed, value):
def check():
try:
return passwords.verify(hashed, value)
except (VerificationError, InvalidHashError):
return False
async with password_gate:
return await asyncio.to_thread(check)
@app.post(PREFIX + "/api/register")
async def register(request: Request):
throttle(request, "register", 5, 3600)
data = await payload(request)
username, password = credentials(data, True)
name = data.get("displayName", "")
if not isinstance(name, str) or not 1 <= len(name.strip()) <= 40:
raise HTTPException(400, "이름은 1~40자로 입력해 주세요.")
hashed = await hash_password(password)
with db() as conn:
conn.execute("BEGIN IMMEDIATE")
if conn.execute("SELECT COUNT(*) FROM members").fetchone()[0] >= 1000:
raise HTTPException(503, "새 회원 가입이 잠시 중지되었습니다.")
if conn.execute("SELECT 1 FROM members WHERE username=?", (username,)).fetchone():
raise HTTPException(409, "이미 사용 중인 아이디입니다.")
calendar, member_id = secrets.token_hex(16), secrets.token_hex(16)
conn.execute("INSERT INTO calendars(id) VALUES(?)", (calendar,))
# 외부 입력으로 역할이나 활성 상태를 받지 않는다. 공개 가입은 항상 일반 회원이다.
conn.execute("INSERT INTO members(id,username,display_name,password_hash,created,last_login,calendar) VALUES(?,?,?,?,?,?,?)",
(member_id, username, name.strip(), hashed, int(time.time()), int(time.time()), calendar))
member = conn.execute("SELECT * FROM members WHERE id=?", (member_id,)).fetchone()
return new_client(conn, member, "web")
@app.post(PREFIX + "/api/login")
async def login(request: Request):
throttle(request, "login", 15, 900)
data = await payload(request)
username, password = credentials(data)
kind = data.get("kind", "web")
if kind not in ("web", "android"):
raise HTTPException(400, "로그인할 기기를 확인해 주세요.")
with db() as conn:
member = conn.execute("SELECT * FROM members WHERE username=?", (username,)).fetchone()
valid = await verify_password(member["password_hash"] if member else dummy_password, password)
if not valid or member is None or not member["active"]:
raise HTTPException(401, "아이디와 비밀번호를 확인해 주세요.")
if kind == "android" and member["must_change"]:
raise HTTPException(403, "홈페이지에서 초기 비밀번호를 먼저 변경해 주세요.")
if data.get("expectedCalendar") and data["expectedCalendar"] != member["calendar"]:
raise HTTPException(409, "이 기기에 저장된 일정의 원래 회원으로 로그인해 주세요.")
replacement = await hash_password(password) if passwords.check_needs_rehash(member["password_hash"]) else member["password_hash"]
with db() as conn:
conn.execute("BEGIN IMMEDIATE")
current = conn.execute("SELECT * FROM members WHERE id=?", (member["id"],)).fetchone()
# 암호 계산 중 관리자가 이용을 중지하거나 비밀번호를 바꿨다면 이전 검사 결과로 로그인하지 않는다.
if current is None or not current["active"] or current["password_hash"] != member["password_hash"]:
raise HTTPException(401, "회원 상태가 변경됐습니다. 다시 로그인해 주세요.")
conn.execute("UPDATE members SET password_hash=?,last_login=? WHERE id=?", (replacement, int(time.time()), member["id"]))
return new_client(conn, current, kind)
@app.get(PREFIX + "/api/me")
async def me(request: Request):
return {"member": profile(identity(request, True))}
@app.post(PREFIX + "/api/password")
async def change_password(request: Request):
client = identity(request, True)
throttle(request, "password", 8, 900)
data = await payload(request)
_, value = credentials({"username": client["username"], "password": data.get("password")}, True)
old = data.get("currentPassword")
if not isinstance(old, str) or len(old) > 128:
raise HTTPException(400, "현재 비밀번호를 확인해 주세요.")
with db() as conn:
member = conn.execute("SELECT * FROM members WHERE id=?", (client["member"],)).fetchone()
if not member or not await verify_password(member["password_hash"], old):
raise HTTPException(400, "현재 비밀번호를 확인해 주세요.")
if old == value:
raise HTTPException(400, "이전과 다른 비밀번호를 입력해 주세요.")
hashed = await hash_password(value)
with db() as conn:
conn.execute("BEGIN IMMEDIATE")
current = identity(request, True)
updated = conn.execute("UPDATE members SET password_hash=?,must_change=0,reset_hash=NULL,reset_expires=0 WHERE id=? AND password_hash=?",
(hashed, client["member"], member["password_hash"]))
if updated.rowcount != 1:
raise HTTPException(409, "회원 상태가 변경됐습니다. 다시 시도해 주세요.")
conn.execute("DELETE FROM clients WHERE member=?", (client["member"],))
member = conn.execute("SELECT * FROM members WHERE id=?", (client["member"],)).fetchone()
return new_client(conn, member, current["kind"])
@app.post(PREFIX + "/api/reset-password")
async def reset_password(request: Request):
throttle(request, "reset", 8, 900)
data = await payload(request)
username, password = credentials(data, True)
code = data.get("code", "")
if not isinstance(code, str) or not re.fullmatch(r"[A-Za-z0-9_-]{32}", code):
raise HTTPException(400, "관리자가 발급한 복구 코드를 확인해 주세요.")
with db() as conn:
row = conn.execute("SELECT * FROM members WHERE username=? AND active=1 AND reset_hash=? AND reset_expires>?",
(username, digest(code), int(time.time()))).fetchone()
if row is None:
raise HTTPException(400, "복구 코드가 만료됐거나 올바르지 않습니다.")
hashed = await hash_password(password)
with db() as conn:
conn.execute("BEGIN IMMEDIATE")
if conn.execute("UPDATE members SET password_hash=?,must_change=0,reset_hash=NULL,reset_expires=0 WHERE id=? AND active=1 AND reset_hash=? AND reset_expires>?",
(hashed, row["id"], digest(code), int(time.time()))).rowcount != 1:
raise HTTPException(400, "복구 코드가 만료됐거나 이미 사용되었습니다.")
conn.execute("DELETE FROM clients WHERE member=?", (row["id"],))
return {"reset": True}
@app.post(PREFIX + "/api/start")
@app.post(PREFIX + "/api/join")
@app.post(PREFIX + "/api/pair")
async def retired_anonymous_connection(request: Request):
raise HTTPException(410, "회원 로그인 방식으로 변경되었습니다. 앱을 업데이트하고 홈페이지 회원으로 로그인해 주세요.")
@app.post(PREFIX + "/api/logout")
async def logout(request: Request):
client = identity(request, True)
with db() as conn:
conn.execute("DELETE FROM clients WHERE hash=?", (client["hash"],))
response = JSONResponse({"connected": False})
response.delete_cookie(COOKIE, path=PREFIX + "/", secure=True, httponly=True, samesite="strict")
return response
def administrator(request):
client = identity(request)
if client["role"] != "admin":
raise HTTPException(403, "관리자만 사용할 수 있습니다.")
return client
@app.get(PREFIX + "/api/admin/members")
async def members(request: Request, q: str = "", page: int = 1):
administrator(request)
if len(q) > 40 or page < 1 or page > 100:
raise HTTPException(400, "검색 조건을 확인해 주세요.")
with db() as conn:
where = "instr(username,?)>0 OR instr(display_name,?)>0"
total = conn.execute("SELECT COUNT(*) FROM members WHERE " + where, (q.lower(), q)).fetchone()[0]
rows = conn.execute("SELECT id,username,display_name,role,active,must_change,created,last_login FROM members WHERE " + where + " ORDER BY created DESC,id LIMIT 50 OFFSET ?", (q.lower(), q, (page - 1) * 50)).fetchall()
return {"members": [dict(row) for row in rows], "total": total, "page": page}
@app.post(PREFIX + "/api/admin/members/{member_id}")
async def manage_member(request: Request, member_id: str):
actor = administrator(request)
throttle(request, "member-management", 60, 60)
data = await payload(request)
action = data.get("action")
if action not in ("update", "delete", "reset"):
raise HTTPException(400, "회원 관리 작업을 확인해 주세요.")
with db() as conn:
conn.execute("BEGIN IMMEDIATE")
administrator(request)
member = conn.execute("SELECT * FROM members WHERE id=?", (member_id,)).fetchone()
if member is None:
raise HTTPException(404, "회원을 찾을 수 없습니다.")
if actor["member"] == member_id:
raise HTTPException(400, "본인 계정은 내 정보에서 수정하세요. 본인의 권한과 이용 상태는 여기서 바꿀 수 없습니다.")
if action == "update":
name, role, active = data.get("displayName"), data.get("role"), data.get("active")
if not isinstance(name, str) or not 1 <= len(name.strip()) <= 40 or role not in ("admin", "member") or type(active) is not bool:
raise HTTPException(400, "이름과 권한 및 이용 상태를 확인해 주세요.")
if member["role"] == "admin" and member["active"] and (role != "admin" or not active) and conn.execute("SELECT COUNT(*) FROM members WHERE role='admin' AND active=1").fetchone()[0] <= 1:
raise HTTPException(400, "마지막 관리자는 이용 중지하거나 권한을 해제할 수 없습니다.")
if not active:
company.member_removed(conn, member_id, deleting=False)
conn.execute("UPDATE members SET display_name=?,role=?,active=? WHERE id=?", (name.strip(), role, int(active), member_id))
if not active or role != member["role"]:
conn.execute("DELETE FROM clients WHERE member=?", (member_id,))
result = {"updated": True}
elif action == "delete":
if member["role"] == "admin" and member["active"] and conn.execute("SELECT COUNT(*) FROM members WHERE role='admin' AND active=1").fetchone()[0] <= 1:
raise HTTPException(400, "마지막 관리자는 삭제할 수 없습니다.")
company.member_removed(conn, member_id)
conn.execute("DELETE FROM calendars WHERE id=?", (member["calendar"],))
result = {"deleted": True}
else:
code = secrets.token_urlsafe(24)
conn.execute("UPDATE members SET reset_hash=?,reset_expires=? WHERE id=?", (digest(code), int(time.time()) + 86400, member_id))
result = {"resetCode": code, "expiresIn": 86400}
conn.execute("INSERT INTO member_audit(actor,target,action,created) VALUES(?,?,?,?)", (actor["member"], member_id, action, int(time.time())))
async with changed:
changed.notify_all()
return result
def snapshot(conn, calendar):
revision = conn.execute("SELECT revision FROM calendars WHERE id=?", (calendar,)).fetchone()[0]
items = [{"id": row["id"], "kind": row["kind"], "version": row["version"], "deleted": bool(row["deleted"]), "data": json.loads(row["data"])}
for row in conn.execute("SELECT * FROM items WHERE calendar=? ORDER BY id", (calendar,))]
return {"calendarId": calendar, "revision": revision, "items": items,
"companyVersion": company.marker(conn, calendar), "company": company.shared_state(conn, calendar)}
@app.get(PREFIX + "/api/state")
async def state(request: Request):
client = identity(request)
with db() as conn:
return snapshot(conn, client["calendar"])
def validate(op):
"""형식뿐 아니라 날짜와 시간의 순서도 확인한다. 클라이언트 검사를 서버에서 다시 수행한다."""
if not isinstance(op, dict) or not re.fullmatch(r"[a-f0-9-]{36}", str(op.get("changeId", ""))):
raise ValueError("변경 식별자가 올바르지 않습니다.")
kind, key = op.get("kind"), op.get("id")
if kind not in ("event", "rotation", "person", "anniversary", "preferences") or (kind in ("rotation", "preferences") and key != kind) or (kind in ("event", "person", "anniversary") and not re.fullmatch(r"[a-f0-9-]{36}", str(key))):
raise ValueError("일정 식별자가 올바르지 않습니다.")
if type(op.get("baseVersion")) is not int or op["baseVersion"] < 0 or type(op.get("deleted")) is not bool:
raise ValueError("일정 버전이 올바르지 않습니다.")
data = op.get("data")
if not isinstance(data, dict):
raise ValueError("일정 내용을 확인해 주세요.")
if op["deleted"]:
if kind in ("rotation", "preferences"):
raise ValueError("반복 근무와 개인 설정은 삭제할 수 없습니다.")
op["data"] = {}
return
if kind in ("anniversary", "preferences"):
op["data"] = validate_personal(kind, data)
return
if kind in ("rotation", "person"):
date.fromisoformat(data["anchor"])
if not re.fullmatch(r"20\d{2}-\d{2}-\d{2}", data["anchor"]):
raise ValueError("기준 날짜는 2000년부터 2099년까지 지정해 주세요.")
if not isinstance(data["pattern"], list) or not 1 <= len(data["pattern"]) <= 366 or any(item not in ("DUTY", "OFF", "REGULAR", "DAY", "EVENING", "NIGHT", "REST") for item in data["pattern"]):
raise ValueError("근무 반복은 1일부터 366일까지 지정해 주세요.")
if kind == "person":
if not isinstance(data.get("name"), str) or not 1 <= len(data["name"].strip()) <= 30:
raise ValueError("이름은 1~30자로 입력해 주세요.")
if data.get("color") not in ("BLUE", "PURPLE", "ORANGE", "PINK", "TEAL", "BROWN"):
raise ValueError("이름 표시 색상을 선택해 주세요.")
data["name"] = data["name"].strip()
if "workWeek" in data and (type(data["workWeek"]) is not int or data["workWeek"] not in (5, 6)):
raise ValueError("주5일제 또는 주6일제를 선택해 주세요.")
if "dutyAsWeekday" in data and type(data["dutyAsWeekday"]) is not bool:
raise ValueError("당직일 날짜 표시 설정을 확인해 주세요.")
if "showLunar" in data and type(data["showLunar"]) is not bool:
raise ValueError("음력 표시 설정을 확인해 주세요.")
if "offAsHoliday" in data and type(data["offAsHoliday"]) is not bool:
raise ValueError("비번 표시 설정을 확인해 주세요.")
fields = ("anchor", "pattern", "name", "color") if kind == "person" else ("anchor", "pattern")
op["data"] = {key: data[key] for key in fields}
if "workWeek" in data:
op["data"]["workWeek"] = data["workWeek"]
if "dutyAsWeekday" in data:
op["data"]["dutyAsWeekday"] = data["dutyAsWeekday"]
if "showLunar" in data:
op["data"]["showLunar"] = data["showLunar"]
if "offAsHoliday" in data:
op["data"]["offAsHoliday"] = data["offAsHoliday"]
return
if not isinstance(data.get("title"), str) or not 1 <= len(data["title"].strip()) <= 120:
raise ValueError("제목은 1자부터 120자까지 입력해 주세요.")
if not isinstance(data.get("notes"), str) or len(data["notes"]) > 2000 or data.get("category") not in ("GENERAL", "WORK", "LEAVE", "PARTTIME"):
raise ValueError("메모와 일정 종류를 확인해 주세요.")
for field in ("date", "endDate"):
if not isinstance(data.get(field), str) or not re.fullmatch(r"20\d{2}-\d{2}-\d{2}", data[field]):
raise ValueError("일정 날짜는 2000년부터 2099년까지 지정해 주세요.")
begin, end = date.fromisoformat(data["date"]), date.fromisoformat(data["endDate"])
if not 0 <= (end - begin).days <= 366 or type(data.get("allDay")) is not bool:
raise ValueError("종료 날짜는 시작 이후 366일 이내로 지정해 주세요.")
if data["category"] == "PARTTIME" and data["allDay"]:
raise ValueError("알바·시간근무는 시작 시간과 종료 시간을 입력해 주세요.")
if not data["allDay"]:
for field in ("startTime", "endTime"):
if not re.fullmatch(r"(?:[01]\d|2[0-3]):[0-5]\d", str(data.get(field, ""))):
raise ValueError("시간을 시:분 형식으로 입력해 주세요.")
if datetime.fromisoformat(data["date"] + "T" + data["startTime"]) >= datetime.fromisoformat(data["endDate"] + "T" + data["endTime"]):
raise ValueError("종료 시간은 시작 시간보다 늦어야 합니다.")
else:
data["startTime"], data["endTime"] = "09:00", "10:00"
op["data"] = {key: data[key] for key in ("title", "notes", "category", "date", "endDate", "allDay", "startTime", "endTime")}
op["data"]["title"] = data["title"].strip()
extra = validate_event_options(data)
# 구버전의 생략과 사용자가 명시한 반복 해제를 구분한다. 생략된 항목은 저장 단계에서 보존한다.
op["data"].update({key:value for key,value in extra.items() if key in data})
@app.post(PREFIX + "/api/mutations")
async def mutations(request: Request):
client = identity(request)
throttle(request, "write", 120, 60)
body = await payload(request)
operations = body.get("operations")
if not isinstance(operations, list) or not 1 <= len(operations) <= 100:
raise HTTPException(400, "한 번에 저장할 일정 수를 확인해 주세요.")
try:
for op in operations:
validate(op)
if op["kind"] in ("anniversary", "preferences") and not client["member"]:
raise HTTPException(403, "회원 로그인 후 사용할 수 있습니다.")
except (ValueError, KeyError, TypeError) as error:
raise HTTPException(400, str(error) if isinstance(error, ValueError) else "일정 입력 항목이 잘못되었습니다.")
accepted, conflicts = [], []
with db() as conn:
# 같은 캘린더에서 동시에 저장해도 비교와 쓰기가 한 작업으로 처리되도록 쓰기 잠금을 먼저 잡는다.
conn.execute("BEGIN IMMEDIATE")
for op in operations:
if conn.execute("SELECT 1 FROM applied WHERE client=? AND change_id=?", (client["hash"], op["changeId"])).fetchone():
accepted.append(op["changeId"])
continue
current = conn.execute("SELECT version,data FROM items WHERE calendar=? AND id=?", (client["calendar"], op["id"])).fetchone()
old_kind = conn.execute("SELECT kind,deleted FROM items WHERE calendar=? AND id=?", (client["calendar"], op["id"])).fetchone()
if old_kind and old_kind["kind"] != op["kind"]:
raise HTTPException(400, "저장된 항목의 종류는 바꿀 수 없습니다.")
version = current[0] if current else 0
if version != op["baseVersion"]:
conflicts.append(op["changeId"])
continue
if not current and conn.execute("SELECT COUNT(*) FROM items WHERE calendar=?", (client["calendar"],)).fetchone()[0] >= 5000:
raise HTTPException(400, "캘린더의 일정 보관 한도에 도달했습니다.")
if op["kind"] == "person" and not op["deleted"] and (not old_kind or old_kind["deleted"]) and conn.execute("SELECT COUNT(*) FROM items WHERE calendar=? AND kind='person' AND deleted=0", (client["calendar"],)).fetchone()[0] >= 20:
raise HTTPException(400, "함께 볼 사람은 20명까지 등록할 수 있습니다.")
if op["kind"] == "anniversary" and not op["deleted"] and (not old_kind or old_kind["deleted"]) and conn.execute("SELECT COUNT(*) FROM items WHERE calendar=? AND kind='anniversary' AND deleted=0", (client["calendar"],)).fetchone()[0] >= 200:
raise HTTPException(400, "기념일은 200개까지 등록할 수 있습니다.")
if op["kind"] == "event" and not op["deleted"] and current:
saved=json.loads(current['data'])
for key in ('repeat','repeatUntil','reminderMinutes'):
if key not in op['data'] and key in saved:op['data'][key]=saved[key]
try:validate_event_options(op['data'])
except ValueError as error:raise HTTPException(400,str(error))
# 예전 앱은 토요일 기준을 보내지 않는다. 새 설정이 있으면 해당 값만 보존하고 나머지는 정상 저장한다.
if op["kind"] in ("rotation", "person") and not op["deleted"] and "workWeek" not in op["data"] and current:
previous_week = json.loads(current["data"]).get("workWeek")
if previous_week in (5, 6):
op["data"]["workWeek"] = previous_week
# 구버전에서 표시 옵션을 보내지 않더라도 이미 저장한 선택을 지우지 않는다.
if op["kind"] == "rotation" and not op["deleted"] and "offAsHoliday" not in op["data"] and current:
previous_off = json.loads(current["data"]).get("offAsHoliday")
if type(previous_off) is bool:
op["data"]["offAsHoliday"] = previous_off
if op["kind"] in ("rotation", "person") and not op["deleted"] and "showLunar" not in op["data"] and current:
previous_lunar = json.loads(current["data"]).get("showLunar")
if type(previous_lunar) is bool:
op["data"]["showLunar"] = previous_lunar
if op["kind"] in ("rotation", "person") and not op["deleted"] and "dutyAsWeekday" not in op["data"] and current:
previous_display = json.loads(current["data"]).get("dutyAsWeekday")
if type(previous_display) is bool:
op["data"]["dutyAsWeekday"] = previous_display
conn.execute("INSERT INTO items VALUES(?,?,?,?,?,?) ON CONFLICT(calendar,id) DO UPDATE SET version=excluded.version,deleted=excluded.deleted,data=excluded.data", (client["calendar"], op["id"], op["kind"], version + 1, int(op["deleted"]), json.dumps(op["data"], ensure_ascii=False)))
conn.execute("UPDATE calendars SET revision=revision+1 WHERE id=?", (client["calendar"],))
if not op["deleted"]:
mirror_display(conn, client["calendar"], op["kind"], op["data"])
conn.execute("INSERT INTO applied VALUES(?,?,?)", (client["hash"], op["changeId"], int(time.time())))
accepted.append(op["changeId"])
result = {"accepted": accepted, "conflicts": conflicts, "state": snapshot(conn, client["calendar"])}
async with changed:
changed.notify_all()
return result
@app.get(PREFIX + "/api/changes")
async def changes(request: Request, after: int = -1, company_after: str | None = None):
client = identity(request)
# 변경을 기다리는 동안 실행 스레드를 차지하지 않는다. 연결이 끊기면 다음 요청에서 최신 버전을 확인한다.
deadline = time.monotonic() + 25
async with changed:
while True:
identity(request)
with db() as conn:
revision = conn.execute("SELECT revision FROM calendars WHERE id=?", (client["calendar"],)).fetchone()[0]
company_version = company.marker(conn, client["calendar"]) if company_after is not None else ""
if revision != after or (company_after is not None and company_after != company_version) or time.monotonic() >= deadline:
return {"revision": revision, "companyVersion": company_version}
try:
await asyncio.wait_for(changed.wait(), max(0.1, deadline - time.monotonic()))
except TimeoutError:
return {"revision": revision, "companyVersion": company_version}
company.setup(app, identity, payload, db, throttle, changed, snapshot)
@app.get(PREFIX + "/health")
async def health():
return {"status": "ok", "version": "0.10.0"}
@app.get(PREFIX + "/download")
async def download(version: int | None = None):
# 검증한 배포 정보의 설치 파일 하나만 제공한다. 요청 입력으로 다른 서버 파일을 선택할 수 없다.
release = release_info()
if version is not None and version != release["appVersionCode"]:
raise HTTPException(409, "새 버전 정보를 다시 확인해 주세요.")
target = ROOT / "releases" / release["apkFile"]
if not target.is_file():
raise HTTPException(503, "새 설치 파일을 준비하고 있습니다. 잠시 후 다시 시도해 주세요.")
return FileResponse(target, media_type="application/vnd.android.package-archive", filename="당직근무-" + release["appVersion"] + ".apk")
def release_info():
# 검사 환경은 별도 배포 정보로 새 버전 알림을 재현한다. 운영은 소스와 함께 배포한 파일만 읽는다.
data = json.loads(Path(os.environ.get("DUTY_RELEASE_JSON", ROOT / "release.json")).read_text(encoding="utf8"))
if not isinstance(data.get("appVersion"), str) or not re.fullmatch(r"\d+\.\d+\.\d+", data["appVersion"]):
raise ValueError("앱 배포 버전을 확인해 주세요.")
if type(data.get("appVersionCode")) is not int or data["appVersionCode"] < 1:
raise ValueError("앱 배포 번호를 확인해 주세요.")
if data.get("apkFile") != "duty-calendar-" + data["appVersion"] + ".apk":
raise ValueError("설치 파일 이름을 확인해 주세요.")
if not isinstance(data.get("webVersion"), str) or not 1 <= len(data["webVersion"]) <= 80:
raise ValueError("웹 배포 버전을 확인해 주세요.")
if not isinstance(data.get("notes"), list) or len(data["notes"]) > 8 or any(not isinstance(note, str) or len(note) > 200 for note in data["notes"]):
raise ValueError("업데이트 안내를 확인해 주세요.")
if type(data.get("apkBytes")) is not int or not 1 <= data["apkBytes"] <= 67108864 or not re.fullmatch(r"[0-9a-f]{64}", data.get("apkSha256", "")):
raise ValueError("설치 파일 크기와 검증 정보를 확인해 주세요.")
return data
@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"]}
@app.get(PREFIX + "/")
async def index():
return FileResponse(ROOT / "web" / "index.html", media_type="text/html")
@app.get(PREFIX + "/assets/{name}")
async def asset(name: str):
if name not in ("app.js", "anniversary-dates.js", "anniversaries.js", "company.js", "updates.js", "style.css", "holidays.json", "holidays-LICENSE.txt", "work-patterns.json", "lunar-months.json", "lunar-LICENSE.txt"):
raise HTTPException(404)
if name == "holidays.json":
return holiday_response()
return FileResponse(ROOT / "web" / name)
def holiday_response():
data, state = holidays.read()
return JSONResponse(data, headers={"X-Holiday-Revision": state["revision"], "X-Holiday-Checked": str(state["checked"]), "X-Holiday-Saved": "1" if state["saved"] else "0", "Cache-Control": "no-store"})
@app.get(PREFIX + "/api/holidays")
async def holiday_data(refresh: bool = False):
if refresh:
await asyncio.to_thread(holidays.refresh, True)
return holiday_response()
+195
View File
@@ -0,0 +1,195 @@
"""회원의 소속과 공유 근무표를 관리한다. 개인 일정과 직접 등록한 다른 사람의 자료는 공유하지 않는다."""
import hashlib
import json
import re
import secrets
import time
from fastapi import HTTPException, Request
COLORS = ("BLUE", "PURPLE", "ORANGE", "PINK", "TEAL", "BROWN")
def init_schema(conn):
conn.executescript("""
CREATE TABLE IF NOT EXISTS companies(
id TEXT PRIMARY KEY, name TEXT NOT NULL,
owner TEXT REFERENCES members(id) ON DELETE SET NULL,
invite_hash TEXT UNIQUE, invite_expires INTEGER NOT NULL DEFAULT 0,
created INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS company_members(
member TEXT PRIMARY KEY REFERENCES members(id) ON DELETE CASCADE,
company TEXT NOT NULL REFERENCES companies(id) ON DELETE CASCADE,
color TEXT NOT NULL DEFAULT 'BLUE', joined INTEGER NOT NULL);
CREATE INDEX IF NOT EXISTS company_members_company ON company_members(company);
""")
def membership(conn, member):
return conn.execute("""SELECT c.*,cm.color FROM company_members cm
JOIN companies c ON c.id=cm.company WHERE cm.member=?""", (member,)).fetchone()
def group_rows(conn, calendar):
member = conn.execute("SELECT id FROM members WHERE calendar=?", (calendar,)).fetchone()
group = membership(conn, member[0]) if member else None
if group is None:
return None, None, []
# 개인 캘린더 전체를 읽지 않는다. 본인 반복 근무 한 항목과 소속에서 보여 줄 이름만 조회한다.
rows = conn.execute("""SELECT m.id,m.display_name,cm.color,i.version,i.data
FROM company_members cm JOIN members m ON m.id=cm.member
LEFT JOIN items i ON i.calendar=m.calendar AND i.id='rotation' AND i.kind='rotation' AND i.deleted=0
WHERE cm.company=? AND m.active=1 ORDER BY m.id""", (group["id"],)).fetchall()
return member[0], group, rows
def marker(conn, calendar):
own, group, rows = group_rows(conn, calendar)
if group is None:
return ""
# 실제 공유 내용이 바뀐 경우에만 표식이 달라진다. 개인 메모 수정과 로그인은 영향을 주지 않는다.
values = [group["id"], group["name"], group["owner"],
[(row["id"], row["display_name"], row["color"], row["version"]) for row in rows]]
return hashlib.sha256(json.dumps(values, ensure_ascii=False, separators=(",", ":")).encode()).hexdigest()
def shared_state(conn, calendar):
own, group, rows = group_rows(conn, calendar)
if group is None:
return None
people = []
for row in rows:
# 소속에는 근무 계산 기준만 전달한다. 개인의 달력 표시 선택은 계정 안에 보관한다.
rotation = {key:value for key,value in json.loads(row["data"]).items() if key in ('anchor','pattern','workWeek')} if row["data"] else None
people.append({"id": row["id"], "name": row["display_name"], "color": row["color"],
"isSelf": row["id"] == own, "rotation": rotation})
return {"id": group["id"], "name": group["name"], "ownerId": group["owner"], "ownMemberId": own,
"canManage": own == group["owner"], "members": people}
def member_removed(conn, member, deleting=True):
"""관리자가 회원을 삭제하거나 중지할 때 회사 관리 권한이 끊기지 않도록 후임을 정한다."""
group = membership(conn, member)
if group is None or group["owner"] != member:
return
successor = conn.execute("""SELECT m.id FROM company_members cm JOIN members m ON m.id=cm.member
WHERE cm.company=? AND m.id<>? AND m.active=1 ORDER BY cm.joined,m.id LIMIT 1""", (group["id"], member)).fetchone()
if successor:
conn.execute("UPDATE companies SET owner=?,invite_hash=NULL,invite_expires=0 WHERE id=?", (successor[0], group["id"]))
elif deleting:
# 회사 연결만 정리한다. 남은 회원의 개인 캘린더는 삭제하지 않는다.
conn.execute("DELETE FROM companies WHERE id=?", (group["id"],))
def setup(app, identity, payload, db, throttle, changed, snapshot):
def checked_name(value):
if not isinstance(value, str) or not 1 <= len(value.strip()) <= 60:
raise HTTPException(400, "소속 이름은 1~60자로 입력해 주세요.")
return value.strip()
def checked_color(value):
if value not in COLORS:
raise HTTPException(400, "공유 근무표의 표시 색상을 선택해 주세요.")
return value
def new_invite(conn, company):
code = secrets.token_urlsafe(24)
conn.execute("UPDATE companies SET invite_hash=?,invite_expires=? WHERE id=?",
(hashlib.sha256(code.encode()).hexdigest(), int(time.time()) + 7 * 86400, company))
return code
async def finish(result):
async with changed:
changed.notify_all()
return result
@app.post("/calendar/api/company/create")
async def create(request: Request):
actor = identity(request)
throttle(request, "company-create", 5, 3600)
data = await payload(request)
name, color = checked_name(data.get("name")), checked_color(data.get("color", "BLUE"))
with db() as conn:
conn.execute("BEGIN IMMEDIATE")
identity(request)
if membership(conn, actor["member"]):
raise HTTPException(409, "이미 소속된 회사가 있습니다. 먼저 현재 소속을 나와 주세요.")
company = secrets.token_hex(16)
conn.execute("INSERT INTO companies(id,name,owner,created) VALUES(?,?,?,?)", (company, name, actor["member"], int(time.time())))
conn.execute("INSERT INTO company_members(member,company,color,joined) VALUES(?,?,?,?)", (actor["member"], company, color, int(time.time())))
code = new_invite(conn, company)
result = {"state": snapshot(conn, actor["calendar"]), "inviteCode": code, "expiresIn": 7 * 86400}
return await finish(result)
@app.post("/calendar/api/company/join")
async def join(request: Request):
actor = identity(request)
throttle(request, "company-join", 10, 900)
data = await payload(request)
code, color = data.get("code", ""), checked_color(data.get("color", "BLUE"))
if not isinstance(code, str) or not re.fullmatch(r"[A-Za-z0-9_-]{32}", code.strip()):
raise HTTPException(400, "초대코드를 확인해 주세요.")
with db() as conn:
conn.execute("BEGIN IMMEDIATE")
identity(request)
if membership(conn, actor["member"]):
raise HTTPException(409, "이미 소속된 회사가 있습니다. 먼저 현재 소속을 나와 주세요.")
group = conn.execute("""SELECT c.id FROM companies c JOIN members m ON m.id=c.owner
WHERE c.invite_hash=? AND c.invite_expires>? AND m.active=1""",
(hashlib.sha256(code.strip().encode()).hexdigest(), int(time.time()))).fetchone()
if group is None:
raise HTTPException(400, "초대코드가 올바르지 않거나 만료됐습니다.")
if conn.execute("SELECT COUNT(*) FROM company_members WHERE company=?", (group[0],)).fetchone()[0] >= 200:
raise HTTPException(400, "한 소속에는 200명까지 가입할 수 있습니다.")
conn.execute("INSERT INTO company_members(member,company,color,joined) VALUES(?,?,?,?)", (actor["member"], group[0], color, int(time.time())))
result = {"state": snapshot(conn, actor["calendar"])}
return await finish(result)
@app.post("/calendar/api/company/manage")
async def manage(request: Request):
actor = identity(request)
throttle(request, "company-manage", 60, 60)
data = await payload(request)
action = data.get("action")
if action not in ("invite", "rename", "color", "leave", "remove", "transfer", "delete"):
raise HTTPException(400, "소속 관리 작업을 확인해 주세요.")
with db() as conn:
conn.execute("BEGIN IMMEDIATE")
identity(request)
group = membership(conn, actor["member"])
if group is None:
raise HTTPException(404, "소속된 회사가 없습니다.")
owner = group["owner"] == actor["member"]
if action not in ("color", "leave") and not owner:
raise HTTPException(403, "소속 관리자만 사용할 수 있습니다.")
extra = {}
if action == "invite":
extra = {"inviteCode": new_invite(conn, group["id"]), "expiresIn": 7 * 86400}
elif action == "rename":
conn.execute("UPDATE companies SET name=? WHERE id=?", (checked_name(data.get("name")), group["id"]))
elif action == "color":
conn.execute("UPDATE company_members SET color=? WHERE member=?", (checked_color(data.get("color")), actor["member"]))
elif action == "leave":
count = conn.execute("SELECT COUNT(*) FROM company_members WHERE company=?", (group["id"],)).fetchone()[0]
if owner and count > 1:
raise HTTPException(400, "소속 관리자 권한을 다른 회원에게 넘긴 뒤 나갈 수 있습니다.")
if owner:
conn.execute("DELETE FROM companies WHERE id=?", (group["id"],))
else:
conn.execute("DELETE FROM company_members WHERE member=?", (actor["member"],))
elif action in ("remove", "transfer"):
target = conn.execute("""SELECT cm.member,m.active FROM company_members cm JOIN members m ON m.id=cm.member
WHERE cm.company=? AND cm.member=?""", (group["id"], data.get("memberId"))).fetchone()
if target is None or target[0] == actor["member"]:
raise HTTPException(400, "다른 소속 회원을 선택해 주세요.")
if action == "transfer":
if not target["active"]:
raise HTTPException(400, "이용 중인 회원에게만 권한을 넘길 수 있습니다.")
conn.execute("UPDATE companies SET owner=?,invite_hash=NULL,invite_expires=0 WHERE id=?", (target[0], group["id"]))
else:
conn.execute("DELETE FROM company_members WHERE member=?", (target[0],))
# 내보낸 회원이 보관한 초대코드로 즉시 재가입하지 못하게 기존 코드를 종료한다.
conn.execute("UPDATE companies SET invite_hash=NULL,invite_expires=0 WHERE id=?", (group["id"],))
elif action == "delete":
conn.execute("DELETE FROM companies WHERE id=?", (group["id"],))
result = {"state": snapshot(conn, actor["calendar"]), **extra}
return await finish(result)
+98
View File
@@ -0,0 +1,98 @@
"""공개 공휴일 API의 정상 자료를 별도 DB에 보관한다. 회원 DB와 갱신 수명을 분리한다.
빈 응답과 일부 날짜만 담긴 응답은 저장하지 않는다. 통신 실패 때는 직전 정상 자료를
계속 제공한다. 서버는 하루마다 확인하지만 기기는 월별·수동·변경 확인 때만 전체 자료를 받는다.
"""
from contextlib import closing
from datetime import date
import hashlib
import json
from pathlib import Path
import sqlite3
import threading
import time
from urllib.request import Request, urlopen
SOURCE = 'https://holidays.hyunbin.page/basic.json'
LIMIT = 1_048_576
def validate(raw, require_current=True):
if len(raw) > LIMIT:
raise ValueError('공휴일 응답 크기 초과')
data = json.loads(raw)
if not isinstance(data, dict) or not data:
raise ValueError('공휴일 연도 누락')
for year, days in data.items():
if not year.isdigit() or len(year) != 4 or not 2000 <= int(year) <= 2099 or not isinstance(days, dict) or not 15 <= len(days) <= 80:
raise ValueError('공휴일 연도 범위 또는 날짜 누락')
for key, names in days.items():
if str(date.fromisoformat(key).year) != year or not isinstance(names, list) or not 1 <= len(names) <= 8 or any(not isinstance(name, str) or not 1 <= len(name.strip()) <= 100 for name in names):
raise ValueError('공휴일 날짜 또는 이름 오류')
# 월력 자료가 중간에 잘려도 JSON 형식은 맞을 수 있다. 고정 공휴일과 두 명절을 함께 확인한다.
if any(f'{year}-{day}' not in days for day in ('01-01', '03-01', '05-05', '06-06', '08-15', '10-03', '10-09', '12-25')):
raise ValueError('고정 공휴일 누락')
names = [name for values in days.values() for name in values]
if sum('설날' in name for name in names) < 3 or sum('추석' in name for name in names) < 3:
raise ValueError('명절 자료 누락')
if require_current and str(date.today().year) not in data:
raise ValueError('올해 공휴일 누락')
return data
class HolidayStore:
def __init__(self, directory, bundled):
self.path = Path(directory) / 'holiday-cache.sqlite3'
self.gate = threading.Lock()
with closing(sqlite3.connect(self.path, timeout=10)) as conn, conn:
conn.execute('CREATE TABLE IF NOT EXISTS snapshot(id INTEGER PRIMARY KEY CHECK(id=1), body TEXT NOT NULL, revision TEXT NOT NULL, checked INTEGER NOT NULL, attempted INTEGER NOT NULL, saved INTEGER NOT NULL)')
if not conn.execute('SELECT 1 FROM snapshot').fetchone():
legacy = Path(directory) / 'holidays.json'
try:
data = validate(legacy.read_bytes(), False)
except Exception:
data = validate(Path(bundled).read_bytes(), False)
body = self.encode(data)
conn.execute('INSERT INTO snapshot VALUES(1,?,?,0,0,1)', (body, self.revision(body)))
self.path.chmod(0o600)
@staticmethod
def encode(data):
return json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
@staticmethod
def revision(body):
return hashlib.sha256(body.encode()).hexdigest()[:24]
def read(self):
with closing(sqlite3.connect(self.path, timeout=10)) as conn:
body, revision, checked, attempted, saved = conn.execute('SELECT body,revision,checked,attempted,saved FROM snapshot WHERE id=1').fetchone()
return json.loads(body), {'revision': revision, 'checked': checked, 'attempted': attempted, 'saved': bool(saved)}
def refresh(self, force=False, fetch=None):
# 여러 수동 요청이 겹쳐도 외부 API는 한 번만 조회한다. 실패 시 재시도 간격은 1시간이다.
if not self.gate.acquire(blocking=False):
return False
try:
old, state = self.read()
now = int(time.time())
if now - state['attempted'] < 3600 or (not force and now - state['checked'] < 86400):
return not state['saved']
try:
if fetch is None:
with urlopen(Request(SOURCE, headers={'Accept': 'application/json', 'User-Agent': 'DutyCalendar/0.7 (+https://duty.itosm.co.kr/calendar/)'}), timeout=10) as response:
raw = response.read(LIMIT + 1)
else:
raw = fetch()
data = validate(raw)
# 제공처가 과거 연도를 목록에서 빼더라도 이미 검증한 과거 기록은 남긴다.
body = self.encode({**old, **data})
with closing(sqlite3.connect(self.path, timeout=10)) as conn, conn:
conn.execute('UPDATE snapshot SET body=?,revision=?,checked=?,attempted=?,saved=0 WHERE id=1', (body, self.revision(body), now, now))
return True
except Exception:
with closing(sqlite3.connect(self.path, timeout=10)) as conn, conn:
conn.execute('UPDATE snapshot SET attempted=?,saved=1 WHERE id=1', (now,))
return False
finally:
self.gate.release()
+48
View File
@@ -0,0 +1,48 @@
"""최초 관리자만 서버에서 등록한다. 공개 회원가입에 관리자 승격 경로를 만들지 않는다.
표준 입력으로 아이디와 이름 및 임시 비밀번호를 받는다. 비밀번호는 명령 인수와 출력에 남기지 않는다.
기존 관리자가 있으면 새 초기 계정을 만들거나 기존 암호를 덮어쓰지 않는다.
"""
import json
import getpass
import re
import secrets
import sys
import time
import app
def bootstrap(data, must_change=True):
username, password = app.credentials(data, True)
name = data.get("displayName", "")
if not isinstance(name, str) or not 1 <= len(name.strip()) <= 40:
raise ValueError("이름을 확인해 주세요.")
hashed = app.passwords.hash(password)
with app.db() as conn:
conn.execute("BEGIN IMMEDIATE")
if conn.execute("SELECT 1 FROM members WHERE role='admin'").fetchone():
raise ValueError("이미 관리자가 등록되어 있습니다. 초기 계정을 덮어쓰지 않습니다.")
if conn.execute("SELECT 1 FROM members WHERE username=?", (username,)).fetchone():
raise ValueError("이미 사용 중인 아이디입니다.")
calendar, member = secrets.token_hex(16), secrets.token_hex(16)
conn.execute("INSERT INTO calendars(id) VALUES(?)", (calendar,))
conn.execute("INSERT INTO members(id,username,display_name,password_hash,role,must_change,created,calendar) VALUES(?,?,?,?,?,?,?,?)",
(member, username, name.strip(), hashed, "admin", int(must_change), int(time.time()), calendar))
print("최초 관리자를 등록했습니다." + (" 첫 로그인에서 비밀번호를 변경해야 합니다." if must_change else " 홈페이지에서 로그인할 수 있습니다."))
if __name__ == "__main__":
try:
if "--interactive" in sys.argv:
username = input("관리자 아이디 [bleear]: ").strip() or "bleear"
name = input("표시 이름 [블리어 (이창현)]: ").strip() or "블리어 (이창현)"
password = getpass.getpass("사용할 비밀번호를 입력하세요. 6자 이상: ")
if password != getpass.getpass("비밀번호 확인: "):
raise ValueError("비밀번호 확인이 일치하지 않습니다.")
bootstrap({"username": username, "displayName": name, "password": password}, must_change=False)
else:
bootstrap(json.load(sys.stdin))
except Exception:
print("초기 관리자 등록을 완료하지 못했습니다. 기존 계정과 입력 조건을 확인하세요.", file=sys.stderr)
sys.exit(1)
+64
View File
@@ -0,0 +1,64 @@
"""회원의 기념일과 표시 설정을 검증한다. 모든 조회와 쓰기의 소유 범위는 인증된 캘린더다."""
from datetime import date
import json
DISPLAY_FIELDS = ('dutyAsWeekday', 'showLunar', 'offAsHoliday')
REMINDER_MINUTES = (-1, 0, 10, 30, 60, 1440)
def validate_reminder(data):
value=data.get('reminderMinutes',-1)
if type(value) is not int or value not in REMINDER_MINUTES:
raise ValueError('알림 시간을 확인해 주세요.')
return value
def validate_event_options(data):
frequency=data.get('repeat','NONE');until=data.get('repeatUntil','')
if frequency not in ('NONE','DAILY','WEEKLY','MONTHLY','YEARLY') or not isinstance(until,str):
raise ValueError('일정 반복 종류와 종료일을 확인해 주세요.')
if until:
parsed=date.fromisoformat(until)
if parsed.isoformat()!=until or not 2000<=parsed.year<=2099 or parsed<date.fromisoformat(data['date']):
raise ValueError('반복 종료일은 시작 날짜 이후로 지정해 주세요.')
return {'repeat':frequency,'repeatUntil':until if frequency!='NONE' else '', 'reminderMinutes':validate_reminder(data)}
def validate_personal(kind, data):
if kind == 'preferences':
if any(type(data.get(key)) is not bool for key in DISPLAY_FIELDS):
raise ValueError('개인 표시 설정을 확인해 주세요.')
return {key: data[key] for key in DISPLAY_FIELDS}
if not isinstance(data.get('title'), str) or not 1 <= len(data['title'].strip()) <= 60:
raise ValueError('기념일 이름은 1~60자로 입력해 주세요.')
if data.get('category') not in ('BIRTHDAY', 'ANNIVERSARY') or data.get('calendar') not in ('SOLAR', 'LUNAR'):
raise ValueError('기념일 종류와 양력·음력을 선택해 주세요.')
if type(data.get('month')) is not int or not 1 <= data['month'] <= 12 or type(data.get('day')) is not int or not 1 <= data['day'] <= 31:
raise ValueError('기념일의 월과 일을 확인해 주세요.')
if type(data.get('leapMonth')) is not bool or (data['calendar'] == 'SOLAR' and data['leapMonth']):
raise ValueError('윤달은 음력 기념일에서만 선택할 수 있습니다.')
if data['calendar'] == 'SOLAR':
date(2000, data['month'], data['day'])
elif data['day'] > 30:
raise ValueError('음력 날짜는 1~30일로 입력해 주세요.')
if not isinstance(data.get('notes'), str) or len(data['notes']) > 1000:
raise ValueError('메모는 1000자까지 입력할 수 있습니다.')
return {**{key: data[key].strip() if key == 'title' else data[key] for key in ('title','category','calendar','month','day','leapMonth','notes')}, 'reminderMinutes':validate_reminder(data)}
def mirror_display(conn, calendar, kind, data):
"""구버전의 근무표 안 표시 항목과 별도 개인 설정을 같은 트랜잭션에서 맞춘다.
반대 항목도 버전을 올려 오래된 기기가 새 선택을 덮어쓰지 못하게 한다.
기존 회원에게 일괄 기본값을 넣지 않는다. 실제 저장한 선택만 복제한다.
"""
if kind not in ('rotation', 'preferences'):
return
target = 'rotation' if kind == 'preferences' else 'preferences'
current = conn.execute('SELECT data,version FROM items WHERE calendar=? AND id=? AND deleted=0', (calendar,target)).fetchone()
# 구버전의 기존 근무 저장만으로 별도 설정을 새로 만들지 않는다.
if not current:
return
saved = json.loads(current['data'])
values = {key: data[key] for key in DISPLAY_FIELDS if type(data.get(key)) is bool}
if not values or all(saved.get(key) == value for key,value in values.items()):
return
saved.update(values)
conn.execute('UPDATE items SET data=?,version=version+1 WHERE calendar=? AND id=?', (json.dumps(saved,ensure_ascii=False),calendar,target))
conn.execute('UPDATE calendars SET revision=revision+1 WHERE id=?', (calendar,))
+14
View File
@@ -0,0 +1,14 @@
{
"appVersion": "0.10.0",
"appVersionCode": 14,
"webVersion": "2026-11-20.10",
"apkFile": "duty-calendar-0.10.0.apk",
"notes": [
"위젯 배경 투명도와 밝은·어두운 색상 및 글자 크기를 조절할 수 있습니다.",
"위젯마다 모양을 따로 저장하거나 모든 위젯에 함께 적용합니다.",
"작은 위젯의 간단한 배치와 음력·공휴일·함께 근무·기념일 표시를 선택합니다.",
"공식 앱과 소스 및 제작 매뉴얼은 포럼의 웹·앱 자료실 → 당직근무에서 제공합니다."
],
"apkBytes": 1040735,
"apkSha256": "a1e5f0da7b2d82d4a7be2a533bb79480947407b70339bf0d7242b424cbe2b977"
}
+2
View File
@@ -0,0 +1,2 @@
-r requirements.txt
httpx==0.28.1
+18
View File
@@ -0,0 +1,18 @@
annotated-doc==0.0.7
annotated-types==0.8.0
anyio==4.16.0
argon2-cffi==25.1.0
argon2-cffi-bindings==26.2.0
cffi==2.1.1
click==8.5.1
fastapi==0.165.0
h11==0.16.0
idna==3.20
opentelemetry-api==1.45.2
pycparser==3.12
pydantic==2.14.4
pydantic_core==2.50.5
starlette==1.10.0
typing-inspection==0.4.5
typing_extensions==4.16.0
uvicorn==0.54.0
+3
View File
@@ -0,0 +1,3 @@
fastapi==0.165.0
uvicorn==0.54.0
argon2-cffi==25.1.0
+21
View File
@@ -0,0 +1,21 @@
const assert=require('node:assert/strict'),fs=require('node:fs');
const {annualMatches,koreanLunarDay}=require('./web/anniversary-dates.js');
const table=JSON.parse(fs.readFileSync(__dirname+'/web/lunar-months.json','utf8'));
const solar={calendar:'SOLAR',month:2,day:29,leapMonth:false};
assert(annualMatches(solar,'2026-02-28',table));assert(!annualMatches(solar,'2028-02-28',table));assert(annualMatches(solar,'2028-02-29',table));
assert(annualMatches({calendar:'LUNAR',month:1,day:1,leapMonth:false},'2026-02-17',table));
assert(annualMatches({calendar:'LUNAR',month:8,day:15,leapMonth:false},'2026-09-25',table));
const leap={calendar:'LUNAR',month:6,day:1,leapMonth:true};
assert(annualMatches(leap,'2025-07-25',table));
assert(!annualMatches({...leap,leapMonth:false},'2025-07-25',table));
for(const year of [2025,2026]){let count=0;for(let d=new Date(Date.UTC(year,0,1));d.getUTCFullYear()===year;d.setUTCDate(d.getUTCDate()+1))if(annualMatches(leap,d.toISOString().slice(0,10),table))count++;assert.equal(count,1);}
assert.equal(koreanLunarDay('2051-01-01',table),null);assert(koreanLunarDay('2050-12-31',table));
console.log('양력 윤년·한국 음력 명절·윤달과 평달·범위 검사 통과');
const {eventOccurrence}=require('./web/anniversary-dates.js');
const monthly={date:'2026-01-31',endDate:'2026-01-31',repeat:'MONTHLY',repeatUntil:''};
assert.equal(eventOccurrence(monthly,'2026-02-28'),'2026-02-28');assert.equal(eventOccurrence(monthly,'2026-03-31'),'2026-03-31');assert.equal(eventOccurrence(monthly,'2026-03-28'),null);
const weekly={date:'2026-11-20',endDate:'2026-11-22',repeat:'WEEKLY',repeatUntil:'2026-11-27'};
assert.equal(eventOccurrence(weekly,'2026-11-29'),'2026-11-27');assert.equal(eventOccurrence(weekly,'2026-12-04'),null);
assert.equal(eventOccurrence({date:'2024-02-29',endDate:'2024-02-29',repeat:'YEARLY'},'2025-02-28'),'2025-02-28');
assert.equal(eventOccurrence({...weekly,repeat:'NONE'},'2026-11-22'),'2026-11-20');
console.log('반복 일정의 말일·윤년·종료일과 여러 날 일정 검사 통과');
+591
View File
@@ -0,0 +1,591 @@
"""개인 캘린더 격리와 입력 검증 및 재전송·동시 수정의 데이터 보존을 검사한다."""
import asyncio
from concurrent.futures import ThreadPoolExecutor
import os
from pathlib import Path
import tempfile
import time
import unittest
import uuid
temporary = tempfile.TemporaryDirectory(prefix="duty-calendar-test-")
os.environ["DUTY_DATA"] = temporary.name
os.environ["DUTY_REFRESH"] = "0"
from fastapi.testclient import TestClient
import app as service
class CalendarTests(unittest.TestCase):
def personal_op(self, kind='anniversary', version=0, key=None, **values):
data={'title':'개인 생일','category':'BIRTHDAY','calendar':'LUNAR','month':1,'day':1,'leapMonth':False,'notes':'개인 메모'} if kind=='anniversary' else {'dutyAsWeekday':True,'showLunar':True,'offAsHoliday':True}
data.update(values)
return {'id':key or ('preferences' if kind=='preferences' else str(uuid.uuid4())), 'kind':kind,'changeId':str(uuid.uuid4()),'baseVersion':version,'deleted':False,'data':data}
def test_anniversary_and_preferences_restore_on_new_login(self):
self.assertEqual(self.write([self.personal_op(),self.personal_op('preferences')]).status_code,200)
before=self.state()['items']
response=self.client.post('/calendar/api/login',json={'kind':'android','username':self.username,'password':self.password},headers=self.headers)
self.assertEqual(self.state(response.json()['token'])['items'],before)
other=self.other_member();self.assertEqual(self.state(other)['items'],[])
self.assertEqual(self.write([self.personal_op('preferences',showLunar=False)],other).status_code,200)
self.assertTrue(next(i for i in self.state()['items'] if i['kind']=='preferences')['data']['showLunar'])
def test_anniversary_private_even_in_same_company(self):
self.write_rotation();private=self.personal_op();self.write([private,self.personal_op('preferences')])
company=self.create_company();other=self.other_member()
self.assertEqual(self.company_call('join',{'code':company['inviteCode'],'color':'BLUE'},other).status_code,200)
state=self.state(other);self.assertNotIn(private['id'],str(state));self.assertNotIn('개인 메모',str(state))
shared=next(p for p in state['company']['members'] if not p['isSelf'])['rotation']
self.assertEqual(set(shared),{'anchor','pattern'})
def test_preferences_mirror_legacy_rotation_and_detect_stale_writes(self):
self.write_rotation();self.write([self.personal_op('preferences')])
rows={i['id']:i for i in self.state()['items']};self.assertTrue(rows['rotation']['data']['showLunar']);self.assertEqual(rows['rotation']['version'],2)
stale=self.write_rotation(version=1).json();self.assertEqual(len(stale['conflicts']),1)
operation={'id':'rotation','kind':'rotation','changeId':str(uuid.uuid4()),'baseVersion':2,'deleted':False,'data':{**rows['rotation']['data'],'showLunar':False}}
self.write([operation]);rows={i['id']:i for i in self.state()['items']};self.assertFalse(rows['preferences']['data']['showLunar']);self.assertEqual(rows['preferences']['version'],2)
stale=self.write([self.personal_op('preferences',version=1)]).json();self.assertEqual(len(stale['conflicts']),1)
def test_anniversary_invalid_dates_and_preferences_are_rejected(self):
for values in ({'calendar':'SOLAR','month':2,'day':30},{'calendar':'LUNAR','day':31},{'month':True},{'day':1.5},{'leapMonth':'true'},{'calendar':'SOLAR','leapMonth':True},{'notes':'x'*1001}):
self.assertEqual(self.write([self.personal_op(**values)]).status_code,400)
for value in (1,None,'true'):
self.assertEqual(self.write([self.personal_op('preferences',showLunar=value)]).status_code,400)
def test_anniversary_edit_delete_and_replay(self):
op=self.personal_op();self.write([op]);replay=self.write([op]).json();self.assertEqual(replay['state']['items'][0]['version'],1)
edit=self.personal_op(key=op['id'],version=1,title='변경한 기념일');self.write([edit])
delete=self.personal_op(key=op['id'],version=2);delete.update(deleted=True,data={});self.write([delete])
self.assertTrue(self.state()['items'][0]['deleted']);self.assertEqual(self.state()['items'][0]['version'],3)
def test_recurring_event_and_reminder_survive_old_client(self):
op=self.operation();op['data'].update(repeat='MONTHLY',repeatUntil='2028-11-20',reminderMinutes=1440)
self.assertEqual(self.write([op]).status_code,200)
old=self.operation(key=op['id'],version=1);self.assertEqual(self.write([old]).status_code,200)
data=self.state()['items'][0]['data'];self.assertEqual(data['repeat'],'MONTHLY');self.assertEqual(data['reminderMinutes'],1440)
old=self.operation(key=op['id'],version=2);old['data'].update(repeat='NONE',repeatUntil='',reminderMinutes=-1)
self.assertEqual(self.write([old]).status_code,200);self.assertEqual(self.state()['items'][0]['data']['repeat'],'NONE')
def test_invalid_repetition_and_reminder_rejected(self):
for extra in ({'repeat':'HOURLY'},{'repeat':'DAILY','repeatUntil':'2025-01-01'},{'repeatUntil':'2026-2-3'},{'reminderMinutes':True},{'reminderMinutes':2}):
op=self.operation();op['data'].update(extra);self.assertEqual(self.write([op]).status_code,400)
def company_call(self, path, data, token=None):
return self.client.post('/calendar/api/company/' + path, json=data, headers=self.auth(token))
def create_company(self, token=None):
result = self.company_call('create', {'name': '검증 회사', 'color': 'TEAL'}, token)
self.assertEqual(result.status_code, 200)
return result.json()
def write_rotation(self, token=None, pattern=None, version=0):
return self.write([{'id': 'rotation', 'kind': 'rotation', 'changeId': str(uuid.uuid4()), 'baseVersion': version,
'deleted': False, 'data': {'anchor': '2026-11-20', 'pattern': pattern or ['DAY','NIGHT','OFF','REST']}}], token)
def test_company_requires_login(self):
for path in ('create', 'join', 'manage'):
self.assertEqual(self.client.post('/calendar/api/company/'+path, json={}, headers=self.headers).status_code, 401)
def test_public_release_matches_web_and_android_build(self):
import json
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(response.json()['appVersion'], release['appVersion'])
script = (Path(__file__).parent / 'web/updates.js').read_text(encoding='utf8')
self.assertIn("const WEB_BUILD = '" + release['webVersion'] + "'", script)
gradle = Path(__file__).parents[1] / 'app/build.gradle.kts'
if gradle.is_file():
self.assertIn('versionCode = ' + str(release['appVersionCode']), gradle.read_text(encoding='utf8'))
self.assertIn('versionName = "' + release['appVersion'] + '"', gradle.read_text(encoding='utf8'))
def test_download_rejects_stale_release(self):
import json
release = json.loads((Path(__file__).parent/'release.json').read_text(encoding='utf8'))
self.assertEqual(self.client.get('/calendar/download?version='+str(release['appVersionCode']-1)).status_code, 409)
self.assertEqual(len(release['apkSha256']),64)
self.assertGreater(release['apkBytes'],0)
def test_display_options_roundtrip_and_old_client(self):
operation = {'id':'rotation', 'kind':'rotation', 'changeId':str(uuid.uuid4()), 'baseVersion':0,
'deleted':False, 'data':{'anchor':'2026-11-20', 'pattern':['DUTY','REGULAR'], 'dutyAsWeekday':True, 'showLunar':True, 'offAsHoliday':True}}
self.assertEqual(self.write([operation]).status_code, 200)
self.assertEqual(self.write_rotation(version=1).status_code, 200)
data = self.state()['items'][0]['data']
self.assertTrue(data['dutyAsWeekday'])
self.assertTrue(data['showLunar'])
self.assertTrue(data['offAsHoliday'])
operation.update(baseVersion=2, changeId=str(uuid.uuid4()))
operation['data'].update(dutyAsWeekday=False, showLunar=False, offAsHoliday=False)
self.assertEqual(self.write([operation]).status_code, 200)
self.assertFalse(self.state()['items'][0]['data']['showLunar'])
for field in ('showLunar', 'dutyAsWeekday', 'offAsHoliday'):
for value in ('true', 1, None):
operation.update(baseVersion=3, changeId=str(uuid.uuid4()))
operation['data'][field]=value
self.assertEqual(self.write([operation]).status_code, 400)
operation['data'][field]=False
def test_public_holiday_db_and_lunar_assets(self):
result=self.client.get('/calendar/api/holidays')
self.assertEqual(result.status_code, 200)
self.assertIn('2026-02-17', result.json()['2026'])
self.assertEqual(result.headers['X-Holiday-Revision'], self.client.get('/calendar/api/version').json()['holidayRevision'])
self.assertEqual(result.json(), self.client.get('/calendar/assets/holidays.json').json())
lunar=self.client.get('/calendar/assets/lunar-months.json').json()
self.assertEqual(lunar['end'], '2050-12-31')
self.assertEqual(len(lunar['months']), len({row[0] for row in lunar['months']}))
def test_work_week_shared_and_preserved_for_old_clients(self):
self.create_company()
other = self.other_member()
invite = self.company_call('manage', {'action':'invite'}).json()['inviteCode']
self.company_call('join', {'code':invite}, other)
operation = {'id':'rotation', 'kind':'rotation', 'changeId':str(uuid.uuid4()), 'baseVersion':0,
'deleted':False, 'data':{'anchor':'2026-11-20', 'pattern':['DUTY','REGULAR'], 'workWeek':5}}
self.assertEqual(self.write([operation]).status_code, 200)
shared = self.state(other)['company']['members']
self.assertEqual(next(person for person in shared if not person['isSelf'])['rotation']['workWeek'], 5)
self.assertEqual(self.write_rotation(version=1).status_code, 200)
self.assertEqual(self.state()['items'][0]['data']['workWeek'], 5)
operation.update(baseVersion=2, changeId=str(uuid.uuid4()))
operation['data']['workWeek']=6
self.assertEqual(self.write([operation]).status_code, 200)
self.assertEqual(self.state()['items'][0]['data']['workWeek'], 6)
def test_work_week_validation_and_person_storage(self):
operation = {'id':str(uuid.uuid4()), 'kind':'person', 'changeId':str(uuid.uuid4()), 'baseVersion':0,
'deleted':False, 'data':{'anchor':'2026-11-20', 'pattern':['DUTY','REGULAR'], 'name':'토요일 검증', 'color':'TEAL', 'workWeek':5}}
for invalid in [4, 7, '5', True, None, 5.0]:
operation['data']['workWeek']=invalid
self.assertEqual(self.write([operation]).status_code, 400)
operation['data']['workWeek']=5
self.assertEqual(self.write([operation]).status_code, 200)
self.assertEqual(self.state()['items'][0]['data']['workWeek'], 5)
def test_company_shares_only_own_rotation_with_members(self):
self.write_rotation()
private = self.operation('공유하지 않는 개인 일정')
self.write([private])
created = self.create_company()
other, outsider = self.other_member(), self.other_member()
self.assertEqual(self.company_call('join', {'code':created['inviteCode'],'color':'PURPLE'}, other).status_code, 200)
shared = self.state(other)['company']
self.assertEqual(len(shared['members']), 2)
owner = next(row for row in shared['members'] if not row['isSelf'])
self.assertEqual(owner['rotation']['pattern'], ['DAY','NIGHT','OFF','REST'])
self.assertNotIn('공유하지 않는 개인 일정', str(shared))
self.assertNotIn(private['id'], str(shared))
self.assertNotIn('invite', str(shared))
self.assertNotIn('username', str(shared))
self.assertIsNone(self.state(outsider)['company'])
self.assertEqual(self.state(other)['items'], [])
def test_company_markers_ignore_private_notes_and_notice_rotation(self):
created=self.create_company(); other=self.other_member()
self.company_call('join', {'code':created['inviteCode']}, other)
old=self.state(other)
self.write([self.operation('개인 메모')])
self.assertEqual(self.state(other)['companyVersion'], old['companyVersion'])
self.write_rotation()
new=self.state(other)
self.assertEqual(new['revision'], old['revision'])
self.assertNotEqual(new['companyVersion'], old['companyVersion'])
notice=self.client.get('/calendar/api/changes', params={'after':old['revision'],'company_after':old['companyVersion']}, headers=self.auth(other)).json()
self.assertEqual(notice['companyVersion'], new['companyVersion'])
self.assertNotIn('items', notice)
self.assertNotIn('members', notice)
def test_company_member_cannot_manage_or_change_another_member(self):
created=self.create_company(); other=self.other_member()
self.company_call('join', {'code':created['inviteCode']}, other)
for action in ('invite','rename','delete','transfer','remove'):
self.assertEqual(self.company_call('manage', {'action':action,'name':'변경','memberId':self.member_id()}, other).status_code,403)
before=self.state()['companyVersion']
self.assertEqual(self.company_call('manage', {'action':'color','color':'PINK','memberId':self.member_id()}, other).status_code,200)
rows=self.state()['company']['members']
self.assertEqual(next(row['color'] for row in rows if row['isSelf']), 'TEAL')
self.assertEqual(next(row['color'] for row in rows if not row['isSelf']), 'PINK')
self.assertNotEqual(before,self.state()['companyVersion'])
def test_company_invite_expiry_rotation_and_removal(self):
created=self.create_company(); other=self.other_member()
new=self.company_call('manage', {'action':'invite'}).json()['inviteCode']
self.assertEqual(self.company_call('join', {'code':created['inviteCode']},other).status_code,400)
self.assertEqual(self.company_call('join', {'code':new},other).status_code,200)
self.assertEqual(self.company_call('manage', {'action':'remove','memberId':self.member_id(other)}).status_code,200)
self.assertIsNone(self.state(other)['company'])
self.assertEqual(self.company_call('join', {'code':new},other).status_code,400)
expired=self.company_call('manage', {'action':'invite'}).json()['inviteCode']
with service.db() as conn:
row=conn.execute('SELECT invite_hash FROM companies WHERE id=?',(created['state']['company']['id'],)).fetchone()
self.assertNotEqual(row[0],expired)
conn.execute('UPDATE companies SET invite_expires=0 WHERE id=?',(created['state']['company']['id'],))
self.assertEqual(self.company_call('join', {'code':expired},other).status_code,400)
def test_company_owner_transfers_before_leaving_and_private_data_survives(self):
created=self.create_company(); other=self.other_member()
self.company_call('join', {'code':created['inviteCode']},other)
self.write_rotation(other)
self.assertEqual(self.company_call('manage', {'action':'leave'}).status_code,400)
self.assertEqual(self.company_call('manage', {'action':'transfer','memberId':self.member_id(other)}).status_code,200)
self.assertTrue(self.state(other)['company']['canManage'])
self.assertEqual(self.company_call('manage', {'action':'leave'}).status_code,200)
self.assertIsNone(self.state()['company'])
self.assertEqual(len(self.state(other)['items']),1)
self.assertEqual(self.company_call('manage', {'action':'delete'},other).status_code,200)
self.assertIsNone(self.state(other)['company'])
self.assertEqual(len(self.state(other)['items']),1)
def test_company_cross_company_member_management_is_rejected(self):
self.create_company();other=self.other_member();self.create_company(other)
for action in ('remove','transfer'):
self.assertEqual(self.company_call('manage',{'action':action,'memberId':self.member_id(other)}).status_code,400)
self.assertEqual(self.company_call('create',{'name':'중복'}).status_code,409)
self.assertIsNotNone(self.state(other)['company'])
def test_company_deleted_owner_passes_management_without_deleting_member_calendar(self):
self.make_admin();other=self.other_member();created=self.create_company(other)
self.company_call('join',{'code':created['inviteCode']})
self.write_rotation()
result=self.client.post('/calendar/api/admin/members/'+self.member_id(other),json={'action':'delete'},headers=self.auth())
self.assertEqual(result.status_code,200)
self.assertTrue(self.state()['company']['canManage'])
self.assertEqual(len(self.state()['company']['members']),1)
self.assertEqual(len(self.state()['items']),1)
def test_company_bad_codes_and_invalid_values_are_rejected(self):
self.assertEqual(self.company_call('join', {'code':'not-a-code'}).status_code,400)
self.assertEqual(self.company_call('create', {'name':''}).status_code,400)
self.assertEqual(self.company_call('create', {'name':'가'*61}).status_code,400)
self.assertEqual(self.company_call('create', {'name':'검증','color':'INVALID'}).status_code,400)
def test_new_domain_accepts_writes_and_old_origin_is_rejected(self):
for origin, expected in [("https://duty.itosm.co.kr", 200), ("https://sub.itosm.co.kr", 403)]:
result = self.client.post("/calendar/api/mutations", json={"operations": [self.operation()]}, headers={**self.auth(), "Origin": origin})
self.assertEqual(result.status_code, expected)
def test_extended_shift_pattern_roundtrip_and_boundaries(self):
pattern = ["DUTY", "OFF", "REGULAR", "DAY", "EVENING", "NIGHT", "REST"]
for kind in ("rotation", "person"):
key = "rotation" if kind == "rotation" else str(uuid.uuid4())
data = {"anchor": "2026-11-20", "pattern": pattern + ["REST"] * 359}
if kind == "person": data.update(name="교대 검증", color="PURPLE")
op = {"id": key, "kind": kind, "changeId": str(uuid.uuid4()), "baseVersion": 0, "deleted": False, "data": data}
response = self.write([op])
self.assertEqual(response.status_code, 200)
saved = next(item for item in response.json()["state"]["items"] if item["id"] == key)
self.assertEqual(saved["data"]["pattern"], data["pattern"])
for invalid in (["DAY"] * 367, ["UNKNOWN"]):
op.update(changeId=str(uuid.uuid4()), baseVersion=1)
op["data"]["pattern"] = invalid
self.assertEqual(self.write([op]).status_code, 400)
self.assertEqual(next(item for item in self.state()["items"] if item["id"] == key)["version"], 1)
def test_web_and_android_share_valid_pattern_templates(self):
path = Path(__file__).parent / "web/work-patterns.json"
android = path.parents[2] / "app/src/main/assets/work-patterns.json"
if android.is_file():
self.assertEqual(path.read_bytes(), android.read_bytes())
result = self.client.get("/calendar/assets/work-patterns.json")
self.assertEqual(result.status_code, 200)
self.assertEqual(len(result.json()), 12)
for item in result.json():
op = {"id": "rotation", "kind": "rotation", "changeId": str(uuid.uuid4()), "baseVersion": 0, "deleted": False,
"data": {"anchor": "2026-11-20", "pattern": item["pattern"]}}
service.validate(op)
def setUp(self):
service.limits.clear()
service.changed = asyncio.Condition()
self.client = TestClient(service.app, base_url="https://duty.itosm.co.kr")
self.client.__enter__()
self.headers = {"X-Duty-Request": "1"}
self.username = "test_" + uuid.uuid4().hex[:12]
self.password = "Verification-Only-7291"
self.client.post("/calendar/api/register", json={"username": self.username, "password": self.password, "displayName": "검증 회원"}, headers=self.headers)
result = self.client.post("/calendar/api/login", json={"kind": "android", "username": self.username, "password": self.password}, headers=self.headers)
self.client.cookies.clear()
self.assertEqual(result.status_code, 200)
self.token = result.json()["token"]
def tearDown(self):
self.client.__exit__(None, None, None)
def auth(self, token=None):
return {**self.headers, "Authorization": "Bearer " + (token or self.token)}
def state(self, token=None):
return self.client.get("/calendar/api/state", headers=self.auth(token)).json()
def operation(self, title="회의", key=None, version=0):
return {"changeId": str(uuid.uuid4()), "id": key or str(uuid.uuid4()), "kind": "event", "baseVersion": version, "deleted": False,
"data": {"title": title, "date": "2026-11-20", "endDate": "2026-11-20", "allDay": False, "startTime": "09:00", "endTime": "10:00", "notes": "장소 확인", "category": "WORK"}}
def write(self, operations, token=None):
return self.client.post("/calendar/api/mutations", json={"operations": operations}, headers=self.auth(token))
def test_multiple_parttime_and_overnight_schedules(self):
first=self.operation('카페 오전');second=self.operation('편의점 야간')
first['data'].update(category='PARTTIME',startTime='08:00',endTime='12:00',repeat='WEEKLY',repeatUntil='',reminderMinutes=30)
second['data'].update(category='PARTTIME',startTime='22:00',endTime='06:00',endDate='2026-11-21',repeat='WEEKLY',repeatUntil='',reminderMinutes=10)
self.assertEqual(self.write([first,second]).status_code,200)
items=self.state()['items'];self.assertEqual(len(items),2)
self.assertTrue(all(item['data']['category']=='PARTTIME' for item in items))
invalid=self.operation();invalid['data'].update(category='PARTTIME',allDay=True)
self.assertEqual(self.write([invalid]).status_code,400)
self.assertEqual(len(self.state()['items']),2)
def test_authentication_is_required(self):
self.assertEqual(self.client.get("/calendar/api/state").status_code, 401)
def test_calendar_isolation(self):
self.write([self.operation()])
other = self.other_member()
self.assertEqual(self.state(other)["items"], [])
def test_edit_and_delete_keep_versions(self):
first = self.operation()
self.assertEqual(self.write([first]).status_code, 200)
update = self.operation("수정 회의", first["id"], 1)
self.write([update])
deletion = self.operation(key=first["id"], version=2)
deletion.update(deleted=True, data={})
result = self.write([deletion]).json()
self.assertEqual(result["state"]["items"][0]["version"], 3)
self.assertTrue(result["state"]["items"][0]["deleted"])
def test_retransmission_is_idempotent(self):
op = self.operation()
self.write([op])
result = self.write([op]).json()
self.assertEqual(result["state"]["revision"], 1)
self.assertEqual(result["accepted"], [op["changeId"]])
def test_stale_edit_does_not_overwrite(self):
first = self.operation()
self.write([first])
self.write([self.operation("먼저 저장한 내용", first["id"], 1)])
stale = self.operation("오래된 화면의 내용", first["id"], 1)
result = self.write([stale]).json()
self.assertEqual(result["conflicts"], [stale["changeId"]])
self.assertEqual(result["state"]["items"][0]["data"]["title"], "먼저 저장한 내용")
def test_deleted_event_is_not_resurrected_by_old_edit(self):
first = self.operation()
self.write([first])
removal = self.operation(key=first["id"], version=1)
removal.update(deleted=True, data={})
self.write([removal])
stale = self.operation(key=first["id"], version=1)
self.assertEqual(self.write([stale]).json()["conflicts"], [stale["changeId"]])
self.assertTrue(self.state()["items"][0]["deleted"])
def test_invalid_dates_and_times_are_rejected(self):
for invalid in ({"endTime": "08:00"}, {"date": "2026-02-30"}, {"title": " "}, {"category": "UNKNOWN"}, {"allDay": "true"}):
op = self.operation()
op["data"].update(invalid)
self.assertEqual(self.write([op]).status_code, 400)
self.assertEqual(self.state()["revision"], 0)
def test_batch_validation_prevents_partial_save(self):
invalid = self.operation()
invalid["data"]["title"] = ""
self.assertEqual(self.write([self.operation(), invalid]).status_code, 400)
self.assertEqual(self.state()["items"], [])
def test_rotation_validates_pattern(self):
op = {"changeId": str(uuid.uuid4()), "id": "rotation", "kind": "rotation", "baseVersion": 0, "deleted": False, "data": {"anchor": "2026-11-20", "pattern": ["DUTY", "OFF", "REGULAR"]}}
self.assertEqual(self.write([op]).status_code, 200)
op["data"]["pattern"] = []
self.assertEqual(self.write([op]).status_code, 400)
def other_member(self):
username = "test_" + uuid.uuid4().hex[:12]
self.client.post("/calendar/api/register", json={"username": username, "password": self.password, "displayName": "다른 회원"}, headers=self.headers)
result = self.client.post("/calendar/api/login", json={"kind": "android", "username": username, "password": self.password}, headers=self.headers)
self.client.cookies.clear()
return result.json()["token"]
def test_same_member_login_shares_calendar(self):
self.write([self.operation()])
result = self.client.post("/calendar/api/login", json={"kind": "android", "username": self.username, "password": self.password}, headers=self.headers)
self.assertEqual(self.state(result.json()["token"])["calendarId"], self.state()["calendarId"])
self.assertEqual(len(self.state(result.json()["token"])["items"]), 1)
def test_anonymous_endpoints_are_closed(self):
for path in ("start", "join", "pair"):
self.assertEqual(self.client.post("/calendar/api/"+path, json={"kind": "android"}, headers=self.headers).status_code, 410)
def test_web_cookie_is_secure_and_token_not_in_body(self):
response = self.client.post("/calendar/api/login", json={"kind": "web", "username": self.username, "password": self.password}, headers={**self.headers, "Origin": service.ORIGIN})
self.assertNotIn("token", response.json())
cookie = response.headers["set-cookie"]
for expected in ("HttpOnly", "Secure", "SameSite=strict", "Path=/calendar/"):
self.assertIn(expected, cookie)
self.assertEqual(self.client.get("/calendar/api/state").status_code, 200)
def test_cross_origin_write_and_missing_header_are_rejected(self):
self.assertEqual(self.client.post("/calendar/api/login", json={"kind": "web", "username": self.username, "password": self.password}, headers={**self.headers, "Origin": "https://invalid.example"}).status_code, 403)
self.assertEqual(self.client.post("/calendar/api/login", json={"kind": "web", "username": self.username, "password": self.password}).status_code, 403)
def test_long_poll_notifies_after_write(self):
with ThreadPoolExecutor(max_workers=1) as executor:
wait = executor.submit(self.client.get, "/calendar/api/changes?after=0", headers=self.auth())
time.sleep(0.15)
self.write([self.operation()])
self.assertEqual(wait.result(timeout=3).json()["revision"], 1)
def test_logout_revokes_client(self):
self.assertEqual(self.client.post("/calendar/api/logout", json={}, headers=self.auth()).status_code, 200)
self.assertEqual(self.client.get("/calendar/api/state", headers=self.auth()).status_code, 401)
def member_id(self, token=None):
return self.client.get("/calendar/api/me", headers=self.auth(token)).json()["member"]["id"]
def make_admin(self):
key = self.member_id()
with service.db() as conn:
conn.execute("UPDATE members SET role='admin' WHERE id=?", (key,))
return key
def manage(self, target, body):
return self.client.post("/calendar/api/admin/members/" + target, json=body, headers=self.auth())
def test_registration_cannot_assign_admin_and_password_is_hashed(self):
response = self.client.post("/calendar/api/register", json={"username": "role_"+uuid.uuid4().hex[:10], "password": self.password, "displayName": "검증", "role": "admin"}, headers=self.headers)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["member"]["role"], "member")
with service.db() as conn:
row = conn.execute("SELECT password_hash FROM members WHERE id=?", (response.json()["member"]["id"],)).fetchone()
self.assertTrue(row["password_hash"].startswith("$argon2id$"))
self.assertNotEqual(row["password_hash"], self.password)
def test_duplicate_and_weak_registration_rejected(self):
for password, expected in (("short", 400), (self.password, 409)):
result = self.client.post("/calendar/api/register", json={"username": self.username, "password": password, "displayName": "검증"}, headers=self.headers)
self.assertEqual(result.status_code, expected)
def test_wrong_password_and_unknown_member_have_same_error(self):
results = [self.client.post("/calendar/api/login", json={"username": name, "password": "wrong-password", "kind": "android"}, headers=self.headers) for name in (self.username, "does_not_exist")]
self.assertEqual([r.status_code for r in results], [401, 401])
self.assertEqual(results[0].json(), results[1].json())
def test_six_character_password_for_register_change_and_recovery(self):
username = "six_" + uuid.uuid4().hex[:12]
response = self.client.post("/calendar/api/register", json={"username": username, "password": "abc123", "displayName": "여섯 자리 검사"}, headers=self.headers)
self.assertEqual(response.status_code, 200)
target = response.json()["member"]["id"]
self.assertEqual(self.client.post("/calendar/api/password", json={"currentPassword": "abc123", "password": "def456"}, headers=self.headers).status_code, 200)
self.make_admin()
code = self.manage(target, {"action": "reset"}).json()["resetCode"]
self.assertEqual(self.client.post("/calendar/api/reset-password", json={"username": username, "code": code, "password": "ghi789"}, headers=self.headers).status_code, 200)
self.assertEqual(self.client.post("/calendar/api/login", json={"username": username, "password": "ghi789", "kind": "android"}, headers=self.headers).status_code, 200)
self.assertEqual(service.credentials({"username": "bleear", "password": "abc123"}, True)[1], "abc123")
def test_login_throttle(self):
service.limits.clear()
for _ in range(15):
self.client.post("/calendar/api/login", json={"username": self.username, "password": "wrong", "kind": "android"}, headers=self.headers)
self.assertEqual(self.client.post("/calendar/api/login", json={"username": self.username, "password": self.password}, headers=self.headers).status_code, 429)
def test_wrong_calendar_login_is_rejected(self):
result = self.client.post("/calendar/api/login", json={"username": self.username, "password": self.password, "kind": "android", "expectedCalendar": "wrong"}, headers=self.headers)
self.assertEqual(result.status_code, 409)
self.assertNotIn("token", result.json())
def test_regular_member_cannot_manage_members(self):
self.assertEqual(self.client.get("/calendar/api/admin/members", headers=self.auth()).status_code, 403)
for action in ("update", "reset", "delete"):
self.assertEqual(self.manage(self.member_id(), {"action": action}).status_code, 403)
def test_admin_list_excludes_secrets_and_escapes_search(self):
self.make_admin()
response = self.client.get("/calendar/api/admin/members", headers=self.auth())
self.assertEqual(response.status_code, 200)
self.assertNotIn("password_hash", response.text)
self.assertNotIn("reset_hash", response.text)
self.assertEqual(self.client.get("/calendar/api/admin/members", params={"q": "' OR 1=1 --"}, headers=self.auth()).json()["total"], 0)
def test_admin_cannot_remove_or_demote_self(self):
key = self.make_admin()
for action in ("delete", "reset", "update"):
self.assertEqual(self.manage(key, {"action": action, "role": "member", "active": False, "displayName": "본인"}).status_code, 400)
def test_disable_member_revokes_sessions_and_blocks_login(self):
self.make_admin(); other = self.other_member(); key = self.member_id(other)
self.assertEqual(self.manage(key, {"action": "update", "displayName": "중지 회원", "role": "member", "active": False}).status_code, 200)
self.assertEqual(self.client.get("/calendar/api/state", headers=self.auth(other)).status_code, 401)
with service.db() as conn:
username = conn.execute("SELECT username FROM members WHERE id=?", (key,)).fetchone()[0]
self.assertEqual(self.client.post("/calendar/api/login", json={"username": username, "password": self.password}, headers=self.headers).status_code, 401)
self.assertEqual(self.manage(key, {"action": "update", "displayName": "복구 회원", "role": "member", "active": True}).status_code, 200)
self.assertEqual(self.client.post("/calendar/api/login", json={"username": username, "password": self.password}, headers=self.headers).status_code, 200)
def test_delete_removes_only_target_calendar(self):
self.make_admin(); other = self.other_member(); target = self.member_id(other)
self.write([self.operation("내 일정")]); self.write([self.operation("삭제 대상 일정")], other)
self.assertEqual(self.manage(target, {"action": "delete"}).status_code, 200)
self.assertEqual(self.client.get("/calendar/api/state", headers=self.auth(other)).status_code, 401)
self.assertEqual(self.state()["items"][0]["data"]["title"], "내 일정")
def test_password_change_revokes_old_devices(self):
result = self.client.post("/calendar/api/password", json={"currentPassword": self.password, "password": "Changed-Password-9283"}, headers=self.auth())
self.assertEqual(result.status_code, 200)
self.assertEqual(self.client.get("/calendar/api/state", headers=self.auth()).status_code, 401)
self.assertEqual(self.client.get("/calendar/api/state", headers=self.auth(result.json()["token"])).status_code, 200)
def test_force_password_change_blocks_data_and_admin(self):
key = self.make_admin()
with service.db() as conn:
conn.execute("UPDATE members SET must_change=1 WHERE id=?", (key,))
self.assertEqual(self.client.get("/calendar/api/state", headers=self.auth()).status_code, 403)
self.assertEqual(self.client.get("/calendar/api/admin/members", headers=self.auth()).status_code, 403)
self.assertTrue(self.client.get("/calendar/api/me", headers=self.auth()).json()["member"]["mustChangePassword"])
self.assertEqual(self.client.post("/calendar/api/login", json={"kind": "android", "username": self.username, "password": self.password}, headers=self.headers).status_code, 403)
result = self.client.post("/calendar/api/password", json={"currentPassword": self.password, "password": "New-Initial-Password-123"}, headers=self.auth())
self.assertEqual(self.client.get("/calendar/api/state", headers=self.auth(result.json()["token"])).status_code, 200)
def test_reset_code_is_expiring_single_use_and_revokes_devices(self):
self.make_admin(); other = self.other_member(); key = self.member_id(other)
username = self.client.get("/calendar/api/me", headers=self.auth(other)).json()["member"]["username"]
code = self.manage(key, {"action": "reset"}).json()["resetCode"]
body = {"username": username, "code": code, "password": "Reset-Password-234567"}
self.assertEqual(self.client.post("/calendar/api/reset-password", json=body, headers=self.headers).status_code, 200)
self.assertEqual(self.client.post("/calendar/api/reset-password", json=body, headers=self.headers).status_code, 400)
self.assertEqual(self.client.get("/calendar/api/state", headers=self.auth(other)).status_code, 401)
body["code"] = self.manage(key, {"action": "reset"}).json()["resetCode"]
with service.db() as conn:
conn.execute("UPDATE members SET reset_expires=0 WHERE id=?", (key,))
self.assertEqual(self.client.post("/calendar/api/reset-password", json=body, headers=self.headers).status_code, 400)
def test_person_schedule_edit_color_validation_and_delete(self):
op = self.operation(); op.update(kind="person", data={"name": "동료 가", "color": "PURPLE", "anchor": "2026-11-20", "pattern": ["DUTY", "OFF", "REGULAR"]})
self.assertEqual(self.write([op]).status_code, 200)
op["baseVersion"] = 1; op["changeId"] = str(uuid.uuid4()); op["data"]["color"] = "BLUE"
self.assertEqual(self.write([op]).json()["state"]["items"][0]["data"]["color"], "BLUE")
for key, value in (("color", "<script>"), ("name", " "), ("pattern", [])):
invalid = dict(op, data=dict(op["data"], **{key: value}), changeId=str(uuid.uuid4()), baseVersion=2)
self.assertEqual(self.write([invalid]).status_code, 400)
op.update(baseVersion=2, changeId=str(uuid.uuid4()), deleted=True, data={})
self.assertTrue(self.write([op]).json()["state"]["items"][0]["deleted"])
def test_person_limit_and_entity_kind_cannot_change(self):
ops=[]
for i in range(20):
op=self.operation(); op.update(kind="person",data={"name": str(i), "color": "BLUE", "anchor": "2026-11-20", "pattern": ["DUTY", "OFF"]});ops.append(op)
self.assertEqual(self.write(ops).status_code, 200)
extra=dict(ops[0],id=str(uuid.uuid4()),changeId=str(uuid.uuid4()))
self.assertEqual(self.write([extra]).status_code, 400)
self.assertEqual(self.write([self.operation(key=ops[0]["id"],version=1)]).status_code, 400)
def test_legacy_anonymous_token_cannot_access_members(self):
token = service.secrets.token_urlsafe(32)
with service.db() as conn:
conn.execute("INSERT INTO clients(hash,calendar,expires) VALUES(?,?,?)", (service.digest(token), self.state()["calendarId"], int(time.time())+9999))
self.assertEqual(self.client.get("/calendar/api/state", headers=self.auth(token)).status_code, 401)
if __name__ == "__main__":
unittest.main(verbosity=2)
+69
View File
@@ -0,0 +1,69 @@
"""API 실패와 불완전한 응답이 정상 공휴일 DB를 지우지 않는지 검사한다."""
import json
from pathlib import Path
from contextlib import closing
import sqlite3
import tempfile
import unittest
from unittest.mock import patch
from holiday_store import HolidayStore, validate
class HolidayTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.raw = (Path(__file__).parent / 'web/holidays.json').read_bytes()
self.store = HolidayStore(self.temp.name, Path(__file__).parent / 'web/holidays.json')
def test_offline_seed_and_restart(self):
original = self.store.read()
self.assertTrue(original[1]['saved'])
self.assertFalse(self.store.refresh(fetch=lambda: (_ for _ in ()).throw(TimeoutError())))
self.assertEqual(self.store.read()[0], original[0])
reloaded = HolidayStore(self.temp.name, Path(__file__).parent / 'web/holidays.json')
self.assertEqual(reloaded.read(), self.store.read())
def test_bad_response_preserves_revision(self):
for raw in (b'{}', b'<html>error</html>', b'x' * 1048577, b'{"2026":{"2026-01-01":["new"]}}'):
with self.subTest(raw=raw[:30]):
before = self.store.read()
with patch('holiday_store.time.time', return_value=before[1]['attempted'] + 90000):
self.assertFalse(self.store.refresh(fetch=lambda: raw))
after = self.store.read()
self.assertEqual(before[0], after[0])
self.assertEqual(before[1]['revision'], after[1]['revision'])
def test_success_changed_data_and_month_history(self):
data = json.loads(self.raw)
year = str(__import__('datetime').date.today().year)
incoming = {year: data[year]}
incoming[year][year + '-11-20'] = ['검증 공휴일']
old = self.store.read()
self.assertTrue(self.store.refresh(fetch=lambda: json.dumps(incoming).encode()))
new = self.store.read()
self.assertNotEqual(old[1]['revision'], new[1]['revision'])
self.assertFalse(new[1]['saved'])
self.assertEqual(new[0]['2018'], old[0]['2018'])
with closing(sqlite3.connect(self.store.path)) as conn:
self.assertEqual(conn.execute('PRAGMA integrity_check').fetchone()[0], 'ok')
def test_rate_limit_and_daily_check(self):
calls = []
def fetch():
calls.append(1)
return self.raw
self.assertTrue(self.store.refresh(fetch=fetch))
self.assertTrue(self.store.refresh(True, fetch))
self.assertEqual(len(calls), 1)
with patch('holiday_store.time.time', return_value=self.store.read()[1]['checked'] + 86401):
self.assertTrue(self.store.refresh(fetch=fetch))
self.assertEqual(len(calls), 2)
def test_missing_lunar_festival_rejected(self):
data = json.loads(self.raw)
for day in list(data['2026']):
if '추석' in ' '.join(data['2026'][day]):
del data['2026'][day]
with self.assertRaises(ValueError):
validate(json.dumps(data).encode())
+20
View File
@@ -0,0 +1,20 @@
// 새로 접속한 화면과 열어 둔 화면의 업데이트 안내를 분리해 검사한다.
const fs=require('node:fs'),vm=require('node:vm'),assert=require('node:assert/strict');
const source=fs.readFileSync(__dirname+'/web/updates.js','utf8');
async function setup(seen=''){
const storage=new Map([['duty-web-update-seen',seen]]),nodes=new Map();
let release={webVersion:'2026-11-20.10',appVersion:'0.10.0',notes:['검증']},reloaded=0,editing=false;
const node=id=>{if(!nodes.has(id))nodes.set(id,{textContent:'',open:false,showModal(){this.open=true;},close(){this.open=false;},addEventListener(){}});return nodes.get(id);};
const context={console,$:node,localStorage:{getItem:k=>storage.get(k)||null,setItem:(k,v)=>storage.set(k,v),removeItem:k=>storage.delete(k)},document:{visibilityState:'visible',querySelector:()=>editing||node('update-dialog').open,addEventListener(){}},pending:[],saving:false,connected:false,notify(){},setInterval(){},location:{reload(){reloaded++;}},fetch:async()=>({ok:true,json:async()=>release})};
vm.createContext(context);vm.runInContext(source,context);await new Promise(setImmediate);
return {context,node,storage,setRelease:v=>release=v,setEditing:v=>editing=v,reloaded:()=>reloaded,check:async()=>{await vm.runInContext('checkWebVersion()',context);}};
}
(async()=>{
const first=await setup();assert.equal(first.node('update-dialog').open,true);assert.equal(first.node('update-apply').textContent,'확인');first.node('update-apply').onclick();assert.equal(first.reloaded(),0);assert.equal(first.storage.get('duty-web-update-seen'),'2026-11-20.10');
const returning=await setup('2026-11-20.4');assert.equal(returning.node('update-dialog').open,true);
const latest=await setup('2026-11-20.10');assert.equal(latest.node('update-dialog').open,false);
latest.setEditing(true);latest.setRelease({webVersion:'2026-11-20.11',appVersion:'0.10.0',notes:['검증']});await latest.check();assert.equal(latest.node('update-dialog').open,false);
latest.setEditing(false);await latest.check();assert.equal(latest.node('update-dialog').open,true);assert.equal(latest.node('update-apply').textContent,'업데이트 적용');latest.node('update-later').onclick();await latest.check();assert.equal(latest.node('update-dialog').open,false);
latest.storage.delete('duty-web-update-later');await latest.check();latest.node('update-apply').onclick();assert.equal(latest.reloaded(),1);assert.equal(latest.storage.get('duty-web-update-seen'),'2026-11-20.11');
console.log('웹 업데이트: 첫 안내, 재접속, 현재 버전, 편집 보호, 나중에, 동의 후 적용 통과');
})().catch(error=>{console.error(error);process.exitCode=1;});
+34
View File
@@ -0,0 +1,34 @@
'use strict';
let anniversaryId=null;
function personalAnniversaries(){return connected?effective().filter(item=>item.kind==='anniversary').sort((a,b)=>a.data.title.localeCompare(b.data.title)):[];}
function anniversariesOn(key){return personalAnniversaries().filter(item=>annualMatches(item.data,key,lunarData));}
function anniversaryOccurrences(key){return anniversariesOn(key).map(item=>({...item,data:{...item.data,date:key,endDate:key,allDay:true,startTime:'',endTime:''}}));}
function openAnniversaryList(){
$('anniversary-list').replaceChildren();const items=personalAnniversaries();
if(!items.length)$('anniversary-list').append(text('p','아직 등록한 생일과 기념일이 없습니다.','small'));
for(const item of items){const button=text('button',item.data.title,'anniversary-row');button.append(text('small',annualDescription(item.data)));button.onclick=()=>{$('anniversary-list-dialog').close();openAnniversary(item);};$('anniversary-list').append(button);}
$('anniversary-list-dialog').showModal();
}
function anniversaryDateFields(){
const lunar=$('anniversary-calendar').value==='LUNAR';$('anniversary-leap-label').hidden=!lunar;
if(!lunar)$('anniversary-leap').checked=false;
const month=Number($('anniversary-month').value);$('anniversary-day').max=lunar?30:month>=1&&month<=12?new Date(Date.UTC(2000,month,0)).getUTCDate():31;
}
function openAnniversary(item){
if(!connected)return;anniversaryId=item?.id??null;
const d=item?.data??{title:'',category:'BIRTHDAY',calendar:'SOLAR',month:Number(selected.slice(5,7)),day:Number(selected.slice(8)),leapMonth:false,notes:''};
$('anniversary-heading').textContent=item?'생일·기념일 수정':'생일·기념일 추가';
for(const key of ['title','category','calendar','month','day','notes'])$('anniversary-'+key).value=d[key];
$('anniversary-reminder').value=String(d.reminderMinutes??-1);$('anniversary-leap').checked=d.leapMonth;$('anniversary-error').textContent='';$('anniversary-delete').hidden=!item;
anniversaryDateFields();$('anniversary-dialog').showModal();
}
$('anniversary-calendar').onchange=anniversaryDateFields;$('anniversary-month').oninput=anniversaryDateFields;
$('anniversary-open').onclick=openAnniversaryList;
$('anniversary-add').onclick=()=>{$('anniversary-list-dialog').close();openAnniversary();};
$('anniversary-form').onsubmit=event=>{
event.preventDefault();const d={title:$('anniversary-title').value.trim(),category:$('anniversary-category').value,calendar:$('anniversary-calendar').value,month:Number($('anniversary-month').value),day:Number($('anniversary-day').value),leapMonth:$('anniversary-calendar').value==='LUNAR'&&$('anniversary-leap').checked,notes:$('anniversary-notes').value,reminderMinutes:Number($('anniversary-reminder').value)};
if(!d.title||!Number.isInteger(d.month)||!Number.isInteger(d.day)||d.day>Number($('anniversary-day').max)){$('anniversary-error').textContent='기념일 이름과 날짜를 확인해 주세요.';return;}
if(!anniversaryId&&personalAnniversaries().length>=200){$('anniversary-error').textContent='기념일은 200개까지 등록할 수 있습니다.';return;}
queue(anniversaryId??crypto.randomUUID(),'anniversary',d);$('anniversary-dialog').close();notify('기기에 저장했습니다. 화면 위에서 서버 저장 상태를 확인하세요.');
};
$('anniversary-delete').onclick=async()=>{if(await confirmAction('이 기념일을 삭제할까요? 내 계정의 앱과 웹에도 반영됩니다.','기념일 삭제')){queue(anniversaryId,'anniversary',{},true);$('anniversary-dialog').close();notify('기념일 삭제를 저장했습니다.');}};
+36
View File
@@ -0,0 +1,36 @@
'use strict';
// 한국 음력 월 시작일을 해별로 묶어 윤달이 있는 해와 없는 해를 구분한다.
// 계산 범위 밖에서는 음력 기념일을 양력처럼 임의 표시하지 않는다.
const annualTableCache=new WeakMap();
function koreanLunarDay(key,data){
if(!data||key<data.start||key>data.end)return null;
let table=annualTableCache.get(data);
if(!table){let year=1899;const leap=new Set();const rows=data.months.map(row=>{if(row[1]===1&&row[2]===0)year=new Date(row[0]*86400000).getUTCFullYear();if(row[2])leap.add(year+':'+row[1]);return [...row,year];});table={rows,leap};annualTableCache.set(data,table);}
const epoch=Math.floor(Date.parse(key+'T00:00:00Z')/86400000),rows=table.rows;
let low=0,high=rows.length;while(low<high){const mid=(low+high)>>>1;if(rows[mid][0]<=epoch)low=mid+1;else high=mid;}
const index=low-1;if(index<0)return null;const row=rows[index];
return {month:row[1],day:epoch-row[0]+1,leap:row[2]===1,length:rows[index+1]?rows[index+1][0]-row[0]:null,yearHasLeapMonth:table.leap.has(row[3]+':'+row[1])};
}
function annualMatches(data,key,lunar){
const date=new Date(key+'T00:00:00Z');
if(data.calendar==='SOLAR'){const last=new Date(Date.UTC(date.getUTCFullYear(),data.month,0)).getUTCDate();return date.getUTCMonth()+1===data.month&&date.getUTCDate()===Math.min(data.day,last);}
const day=koreanLunarDay(key,lunar);if(!day)return false;
return day.month===data.month&&day.leap===(data.leapMonth&&day.yearHasLeapMonth)&&day.day===(day.length===null?data.day:Math.min(data.day,day.length));
}
function annualDescription(data){return (data.category==='BIRTHDAY'?'생일':'기념일')+' · '+(data.calendar==='SOLAR'?'양력':'음력')+' '+(data.leapMonth?'윤':'')+data.month+'월 '+data.day+'일 · 매년';}
function eventOccurrence(data,key){
const parse=value=>new Date(value+'T00:00:00Z'),start=parse(data.date),end=parse(data.endDate),day=parse(key);
if(day<start)return null;
const limit=data.repeatUntil&&parse(data.repeatUntil)<day?parse(data.repeatUntil):day;
if(limit<start)return null;
const shiftMonth=gap=>{const first=new Date(Date.UTC(start.getUTCFullYear(),start.getUTCMonth()+gap,1));const last=new Date(Date.UTC(first.getUTCFullYear(),first.getUTCMonth()+1,0)).getUTCDate();return new Date(Date.UTC(first.getUTCFullYear(),first.getUTCMonth(),Math.min(start.getUTCDate(),last)));};
let candidate=start;
switch(data.repeat||'NONE'){
case 'DAILY':candidate=limit;break;
case 'WEEKLY':candidate=new Date(start.getTime()+Math.floor((limit-start)/604800000)*604800000);break;
case 'MONTHLY':{let gap=(limit.getUTCFullYear()-start.getUTCFullYear())*12+limit.getUTCMonth()-start.getUTCMonth();if(shiftMonth(gap)>limit)gap--;candidate=shiftMonth(gap);break;}
case 'YEARLY':{let gap=limit.getUTCFullYear()-start.getUTCFullYear();if(shiftMonth(gap*12)>limit)gap--;candidate=shiftMonth(gap*12);break;}
}
return candidate>=start&&day<=new Date(candidate.getTime()+(end-start))?candidate.toISOString().slice(0,10):null;
}
if(typeof module!=='undefined')module.exports={annualMatches,koreanLunarDay,eventOccurrence};
+207
View File
@@ -0,0 +1,207 @@
'use strict';
/* 웹과 휴대폰은 같은 일정 구조를 사용한다. 화면은 서버 원본 위에 아직 전송하지 못한
* 변경을 덧씌워 표시한다. 저장 응답을 놓쳐도 같은 변경 번호를 다시 보내면 중복 적용되지 않는다.
* 충돌한 내용은 별도로 보관하며 사용자가 선택하기 전에는 서버 값을 덮어쓰지 않는다. */
const $ = id => document.getElementById(id);
const labels = {DUTY:'당직',OFF:'비번',REGULAR:'일반근무',DAY:'주간',EVENING:'오후',NIGHT:'야간',REST:'휴무'};
const classes = {DUTY:'duty',OFF:'off',REGULAR:'regular',DAY:'daytime',EVENING:'evening',NIGHT:'night',REST:'rest'};
const categories = {GENERAL:'개인 일정',WORK:'업무',PARTTIME:'알바·시간근무',LEAVE:'휴가·휴무',BIRTHDAY:'생일',ANNIVERSARY:'기념일'};
const todayKey = () => new Intl.DateTimeFormat('sv-SE',{timeZone:'Asia/Seoul',year:'numeric',month:'2-digit',day:'2-digit'}).format(new Date());
const dayDate = key => new Date(key+'T00:00:00Z');
const dateKey = date => date.toISOString().slice(0,10);
let member=null, watchGeneration=0, refreshedAt=0;
const MONTH_MS=30*24*60*60*1000;
const stateCacheKey=()=> 'duty-calendar-state:'+member.id;
const personColors={BLUE:'파랑',PURPLE:'보라',ORANGE:'주황',PINK:'분홍',TEAL:'청록',BROWN:'갈색'};
let selected=todayKey(), month=selected.slice(0,7), model={calendarId:'',revision:0,items:[]}, pending=[], conflicts=[], connected=false, saving=false, editId=null, holidayData={}, lunarData=null;
const cacheKey=()=> 'duty-calendar:'+model.calendarId;
// 서버 원본 전체를 브라우저 저장 공간에 복제하지 않는다. 재전송에 필요한 미완료 변경만 보관한다.
function persist(){if(model.calendarId){localStorage.setItem(cacheKey(),JSON.stringify({pending,conflicts}));if(member){try{localStorage.setItem(stateCacheKey(),JSON.stringify({state:model,refreshedAt}));}catch{localStorage.removeItem(stateCacheKey());}}}}
function effective(){const result=new Map(model.items.map(item=>[item.id,item]));for(const op of pending)result.set(op.id,{...op,version:op.baseVersion});return [...result.values()].filter(item=>!item.deleted);}
function displaySettings(){return effective().find(item=>item.kind==='preferences')?.data??effective().find(item=>item.kind==='rotation')?.data??{dutyAsWeekday:false,showLunar:false,offAsHoliday:false};}
function rotation(){const base=effective().find(item=>item.kind==='rotation')?.data;return base?{...base,...displaySettings()}:undefined;}
// 토요일 휴무로 바꾸어도 다음 날의 반복 순서는 그대로 이어진다. 자료에 기준이 없으면 기존 주6일제로 읽는다.
function shiftFor(data,key){
if(!data)return null;
const date=dayDate(key),distance=Math.round((date-dayDate(data.anchor))/86400000);
const planned=data.pattern[((distance%data.pattern.length)+data.pattern.length)%data.pattern.length];
return data.workWeek===5&&date.getUTCDay()===6&&planned!=='DUTY'?'REST':planned;
}
function shiftOn(key){return shiftFor(rotation(),key);}
function personalPeople(){return effective().filter(item=>item.kind==='person');}
function people(){const shared=(model.company?.members||[]).filter(person=>!person.isSelf&&person.rotation).map(person=>({id:'company:'+person.id,kind:'person',shared:true,data:{name:person.name,color:person.color,...person.rotation}}));return [...personalPeople(),...shared].sort((a,b)=>a.data.name.localeCompare(b.data.name));}
function personShift(item,key){return shiftFor(item.data,key);}
function eventsOn(key){return effective().filter(item=>item.kind==='event'&&eventOccurrence(item.data,key)!==null).concat(anniversaryOccurrences(key)).sort((a,b)=>Number(b.data.allDay)-Number(a.data.allDay)||a.data.startTime.localeCompare(b.data.startTime)||a.data.title.localeCompare(b.data.title));}
function holiday(key){return holidayData[key.slice(0,4)]?.[key]?.join(' · ')||'';}
function text(tag,value,cls){const node=document.createElement(tag);node.textContent=value;if(cls)node.className=cls;return node;}
function notify(message){$('toast').textContent=message;$('toast').hidden=false;clearTimeout(notify.timer);notify.timer=setTimeout(()=>$('toast').hidden=true,4000);}
// 브라우저 전체를 막는 기본 확인 창 대신 페이지 안에서 취소와 실행을 선택한다.
// 취소하거나 뒤로 닫으면 원래 편집 내용은 유지하고 삭제나 연결 해제를 실행하지 않는다.
function confirmAction(message,label){return new Promise(resolve=>{const dialog=$('confirm-dialog');$('confirm-message').textContent=message;$('confirm-accept').textContent=label;const finish=value=>{dialog.close();resolve(value);};$('confirm-cancel').onclick=()=>finish(false);$('confirm-accept').onclick=()=>finish(true);dialog.oncancel=event=>{event.preventDefault();finish(false);};dialog.showModal();});}
function updateStatus(message){$('status').textContent=message||(conflicts.length?'수정 내용 확인 필요':pending.length?'기기에 저장 · 전송 대기':'서버 저장 완료 · 변경 시 갱신');$('conflict-notice').hidden=conflicts.length===0;}
async function api(path,body){const options={headers:{'X-Duty-Request':'1'},cache:'no-store'};if(body!==undefined){options.method='POST';options.headers['Content-Type']='application/json';options.body=JSON.stringify(body);}const response=await fetch('api/'+path,options);const result=await response.json();if(!response.ok){const error=new Error(typeof result.detail==='string'?result.detail:'요청을 처리하지 못했습니다.');error.status=response.status;throw error;}return result;}
function queue(id,kind,data,deleted=false){const existing=pending.find(op=>op.id===id);const remote=model.items.find(item=>item.id===id);pending=pending.filter(op=>op.id!==id);if(existing)conflicts=conflicts.filter(changeId=>changeId!==existing.changeId);pending.push({id,kind,data,deleted,baseVersion:existing?.baseVersion??remote?.version??0,changeId:crypto.randomUUID()});persist();render();sync();}
async function sync(force=false){if(saving||!connected)return;saving=true;try{const toSend=pending.filter(op=>!conflicts.includes(op.changeId)).slice(0,100);if(toSend.length){const result=await api('mutations',{operations:toSend});model=result.state;refreshedAt=Date.now();pending=pending.filter(op=>!result.accepted.includes(op.changeId));conflicts=[...new Set([...conflicts,...result.conflicts])].filter(id=>pending.some(op=>op.changeId===id));}else if(force||!refreshedAt||Date.now()-refreshedAt>=MONTH_MS){model=await api('state');refreshedAt=Date.now();}persist();render();return true;}catch(error){if(error.status===401)showWelcome('다시 로그인해 주세요.');else updateStatus('연결 대기 · 작성 내용 보관 중');if(error.status===400||error.status===429)notify(error.message);return false;}finally{saving=false;} }
async function watch(run){while(connected&&run===watchGeneration){try{const result=await api('changes?after='+model.revision+'&company_after='+encodeURIComponent(model.companyVersion||''));if(run!==watchGeneration)break;if(result.revision!==model.revision||(result.companyVersion||'')!==(model.companyVersion||'')||pending.some(op=>!conflicts.includes(op.changeId)))await sync(true);}catch(error){if(run!==watchGeneration)break;updateStatus('연결 대기 · 작성 내용 보관 중');await new Promise(resolve=>setTimeout(resolve,5000));if(error.status===401){showWelcome('다시 로그인해 주세요.');notify('로그인이 만료됐습니다. 다시 로그인해 주세요.');}}}}
// 공개 화면은 앱 소개와 설치 안내만 제공한다. 회원 자료와 편집 화면은 인증 확인 뒤 연다.
// 로그인 만료 때도 같은 전환을 사용하므로 이전 회원 화면이 계속 남지 않는다.
function showWelcome(message='로그인 없이 앱 설치 가능'){
connected=false;watchGeneration++;
document.querySelectorAll('dialog[open]').forEach(dialog=>dialog.close());
$('welcome').hidden=false;$('workspace').hidden=true;$('public-auth').hidden=false;
for(const id of ['connect','logout','admin-open','company-open','refresh-data'])$(id).hidden=true;
document.body.classList.remove('with-people','five-day');updateStatus(message);
}
async function enter(){
member=(await api('me')).member;
$('public-auth').hidden=true;$('connect').hidden=false;$('logout').hidden=false;
$('admin-open').hidden=member.role!=='admin'||member.mustChangePassword;
if(member.mustChangePassword){connected=false;$('welcome').hidden=false;$('workspace').hidden=true;$('account-notice').textContent='초기 비밀번호를 변경한 뒤 사용할 수 있습니다.';openPassword();return;}
$('account-notice').textContent='';
let stored;try{stored=JSON.parse(localStorage.getItem(stateCacheKey())||'null');}catch{}
if(stored?.state?.calendarId===member.calendarId&&Array.isArray(stored.state.items)&&stored.refreshedAt<=Date.now()&&Date.now()-stored.refreshedAt<MONTH_MS){model=stored.state;refreshedAt=stored.refreshedAt;}
else{model=await api('state');refreshedAt=Date.now();}
let cached;try{cached=JSON.parse(localStorage.getItem(cacheKey())||'null');}catch{}
pending=Array.isArray(cached?.pending)?cached.pending:[];conflicts=Array.isArray(cached?.conflicts)?cached.conflicts:[];
connected=true;$('company-open').hidden=false;$('refresh-data').hidden=false;
$('welcome').hidden=true;$('workspace').hidden=false;
loadPlannerAssets();render();await sync();watch(++watchGeneration);
}
function render(){
if(typeof renderCompany==='function')renderCompany();
const today=todayKey(),day=dayDate(today),r=rotation(),display=displaySettings(),current=shiftOn(today);
document.body.classList.toggle('five-day',r?.workWeek===5);
$('today-date').textContent=new Intl.DateTimeFormat('ko-KR',{month:'long',day:'numeric',weekday:'long',timeZone:'UTC'}).format(day);
$('today-duty').textContent=current?'오늘은 '+labels[current]:'근무표를 설정해 주세요';
$('today-caption').textContent=eventsOn(today).length?`오늘 예정된 일정 ${eventsOn(today).length}개`:'여유 있게 하루를 계획하세요.';
$('rotation-label').textContent=r?'주'+(r.workWeek||6)+'일제 · '+r.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=dayDate(month+'-01');first.setUTCDate(1-first.getUTCDay());
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?' sat':'')+(name?' holiday':'')+(display.dutyAsWeekday===true&&shift==='DUTY'?' duty-weekday':'')+(display.offAsHoliday===true&&shift==='OFF'?' off-red':'');button.setAttribute('aria-label',`${key} ${shift?labels[shift]:''} ${name} 일정 ${events.length}개`);button.append(text('span',String(date.getUTCDate()),'day-number'));const lunar=display.showLunar?lunarLabel(key):null;if(lunar){button.classList.add('with-lunar');button.append(text('span',lunar,'lunar-date'));button.setAttribute('aria-label',button.getAttribute('aria-label')+' '+lunar);}if(shift)button.append(text('span',shift==='REGULAR'?'일반':labels[shift],'shift '+classes[shift]));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=>!['OFF','REST'].includes(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')+' 함께 근무 '+duties.map(item=>item.data.name).join(' '));button.onclick=()=>{selected=key;render();};$('grid').append(button);}
const selectedDay=dayDate(selected);$('selected-date').textContent=new Intl.DateTimeFormat('ko-KR',{month:'long',day:'numeric',weekday:'short',timeZone:'UTC'}).format(selectedDay);$('day-detail').textContent=[labels[shiftOn(selected)],holiday(selected)].filter(Boolean).join(' · ')||'등록한 일정을 확인하고 새로 추가하세요.';
$('agenda').replaceChildren();const events=eventsOn(selected);if(!events.length)$('agenda').append(text('div','등록된 일정이 없습니다.\n가벼운 메모부터 시작해 보세요.','empty'));for(const item of events){const node=document.createElement('button');node.className='event-item '+(item.data.category==='PARTTIME'?'parttime':item.data.category==='WORK'?'work':item.data.category==='LEAVE'?'leave':'');node.append(text('strong',item.data.title),text('span',eventTimeSummary(item.data)),text('span',categories[item.data.category]));node.onclick=()=>openEvent(item);$('agenda').append(node);}
$('people-list').replaceChildren();if(!companions.length)$('people-list').append(text('p','이름과 근무 주기를 등록해 함께 볼 수 있습니다.','small'));for(const item of companions){const node=text('button',item.data.name+' · '+labels[personShift(item,selected)],'person-row person-'+item.data.color.toLowerCase());node.append(text('small','주'+(item.data.workWeek||6)+'일제 · '+item.data.pattern.length+'일 반복 · '+personColors[item.data.color]));if(item.shared)node.append(text('small','소속 공유 · 본인만 수정 가능'));node.onclick=()=>item.shared?openCompany():openPerson(item);$('people-list').append(node);}
$('holiday-note').textContent=holidayData[month.slice(0,4)]?(localStorage.getItem('duty-holiday-saved')==='1'?' · 서버에 보관된 정상 자료 사용':''):'이 연도의 공휴일 자료가 아직 없습니다.';updateStatus();
}
function eventTimeSummary(d){if(d.allDay)return '하루 종일';const days=(dayDate(d.endDate)-dayDate(d.date))/86400000;return d.startTime+' – '+(days===1?'다음 날 ':days>1?days+'일 뒤 ':'')+d.endTime;}
function openEvent(item,partTime=false){if(item?.kind==='anniversary'){openAnniversary(item);return;}editId=item?.id??null;const d=item?.data??{title:'',date:selected,endDate:selected,allDay:!partTime,startTime:'09:00',endTime:'10:00',notes:'',category:partTime?'PARTTIME':'GENERAL'};$('event-heading').textContent=item?'일정 수정':'일정 추가';$('event-title').value=d.title;$('event-category').value=d.category;$('event-date').value=d.date;$('event-end').value=d.endDate;$('event-all-day').checked=d.allDay;$('time-fields').hidden=d.allDay;$('event-start-time').value=d.startTime;$('event-end-time').value=d.endTime;$('event-notes').value=d.notes;$('event-repeat').value=d.repeat||'NONE';$('event-repeat-until').value=d.repeatUntil||'';$('event-repeat-until-label').hidden=$('event-repeat').value==='NONE';$('event-reminder').value=String(d.reminderMinutes??-1);$('event-error').textContent='';$('event-delete').hidden=!item;$('event-all-day').disabled=d.category==='PARTTIME';$('event-dialog').showModal();}
$('parttime-add').onclick=()=>openEvent(null,true);
$('event-category').onchange=()=>{const timed=$('event-category').value==='PARTTIME';$('event-all-day').disabled=timed;if(timed){$('event-all-day').checked=false;$('time-fields').hidden=false;}};
$('event-repeat').onchange=()=>$('event-repeat-until-label').hidden=$('event-repeat').value==='NONE';
$('event-all-day').onchange=()=>$('time-fields').hidden=$('event-all-day').checked;
$('event-date').onchange=()=>{if($('event-end').value<$('event-date').value)$('event-end').value=$('event-date').value;};
$('event-form').onsubmit=event=>{event.preventDefault();const d={title:$('event-title').value.trim(),category:$('event-category').value,date:$('event-date').value,endDate:$('event-end').value,allDay:$('event-all-day').checked,startTime:$('event-start-time').value,endTime:$('event-end-time').value,notes:$('event-notes').value,repeat:$('event-repeat').value,repeatUntil:$('event-repeat').value==='NONE'?'':$('event-repeat-until').value,reminderMinutes:Number($('event-reminder').value)};const duration=(dayDate(d.endDate)-dayDate(d.date))/86400000;if(!d.title||(d.repeatUntil&&d.repeatUntil<d.date)||duration<0||duration>366||(!d.allDay&&d.date+'T'+d.startTime>=d.endDate+'T'+d.endTime)){$('event-error').textContent='제목과 기간을 확인해 주세요. 종료 시간은 시작 이후여야 합니다.';return;}queue(editId??crypto.randomUUID(),'event',d);$('event-dialog').close();notify('일정을 저장했습니다.');};
$('event-delete').onclick=async()=>{if(await confirmAction('이 일정을 삭제할까요? 연결된 기기에도 반영됩니다.','일정 삭제')){queue(editId,'event',{},true);$('event-dialog').close();notify('일정을 삭제했습니다.');}};
$('add').onclick=()=>openEvent();$('day-add').onclick=()=>openEvent();
function moveMonth(step){const d=dayDate(month+'-01');d.setUTCMonth(d.getUTCMonth()+step);month=dateKey(d).slice(0,7);render();}
$('prev').onclick=()=>moveMonth(-1);$('next').onclick=()=>moveMonth(1);$('today').onclick=()=>{selected=todayKey();month=selected.slice(0,7);render();};
function drawRotation(pattern){$('rotation-count').value=pattern.length;$('rotation-days').replaceChildren();pattern.forEach((shift,index)=>{const label=text('label',(index+1)+'일째');const select=document.createElement('select');for(const [value,name] of Object.entries(labels)){const option=text('option',name);option.value=value;select.append(option);}select.value=shift;label.append(select);$('rotation-days').append(label);});}
$('rotation').onclick=()=>{const r=rotation()??{anchor:todayKey(),pattern:['DUTY','OFF']};$('rotation-anchor').value=r.anchor;$('rotation-work-week').value=String(r.workWeek||6);resetPatternMode('rotation');drawRotation(r.pattern);$('rotation-error').textContent='';$('rotation-dialog').showModal();};
$('rotation-form').onsubmit=event=>{event.preventDefault();const pattern=[...$('rotation-days').querySelectorAll('select')].map(node=>node.value);if(pattern.length!==Number($('rotation-count').value)){$('rotation-error').textContent='반복 일수를 확인해 주세요.';return;}queue('rotation','rotation',{...rotation(),...displaySettings(),anchor:$('rotation-anchor').value,pattern,workWeek:Number($('rotation-work-week').value)});$('rotation-dialog').close();notify('반복 근무를 저장했습니다.');};
// 저장 시 최신 근무표에서 표시 항목만 바꾼다. 기초 설정과 옵션이 서로의 값을 되돌리지 않게 한다.
$('display-options').onclick=()=>{
const r=displaySettings();
$('rotation-duty-weekday').checked=r.dutyAsWeekday===true;
$('rotation-show-lunar').checked=r.showLunar===true;
$('rotation-off-red').checked=r.offAsHoliday===true;
$('options-dialog').showModal();
};
$('options-form').onsubmit=event=>{
event.preventDefault();queue('preferences','preferences',{dutyAsWeekday:$('rotation-duty-weekday').checked,showLunar:$('rotation-show-lunar').checked,offAsHoliday:$('rotation-off-red').checked});
$('options-dialog').close();notify('개인 설정을 저장했습니다.');
};
let authMode='login', memberPage=1, editingMember=null, personId=null;
function openAuth(mode){authMode=mode;$('auth-form').reset();$('auth-error').textContent='';const joining=mode==='register',resetting=mode==='reset';$('auth-heading').textContent=joining?'회원가입':resetting?'비밀번호 복구':'회원 로그인';$('auth-submit').textContent=joining?'가입하고 시작':resetting?'비밀번호 재설정':'로그인';$('auth-help').textContent=joining?'아이디는 영문과 숫자 및 밑줄 3~32자입니다. 비밀번호는 6자 이상으로 입력해 주세요.':resetting?'관리자가 본인 확인 후 발급한 복구 코드를 입력하세요.':'홈페이지와 앱에서 같은 회원으로 로그인하세요.';$('auth-name-label').hidden=!joining;$('auth-name').required=joining;$('auth-code-label').hidden=!resetting;$('auth-code').required=resetting;$('auth-repeat-label').hidden=mode==='login';$('auth-repeat').required=mode!=='login';$('auth-password').minLength=mode==='login'?1:6;$('auth-password').autocomplete=mode==='login'?'current-password':'new-password';$('auth-recovery').hidden=mode!=='login';if(!$('auth-dialog').open)$('auth-dialog').showModal();}
$('create').onclick=()=>openAuth('register');$('join').onclick=()=>openAuth('login');$('auth-recovery').onclick=()=>openAuth('reset');
$('auth-dialog').addEventListener('close',()=>{$('auth-password').value='';$('auth-repeat').value='';$('auth-code').value='';});
$('auth-form').onsubmit=async event=>{event.preventDefault();$('auth-error').textContent='';if(authMode!=='login'&&$('auth-password').value!==$('auth-repeat').value){$('auth-error').textContent='비밀번호 확인이 일치하지 않습니다.';return;}$('auth-submit').disabled=true;try{const data={username:$('auth-username').value.trim().toLowerCase(),password:$('auth-password').value,kind:'web'};if(authMode==='register')data.displayName=$('auth-name').value.trim();if(authMode==='reset')data.code=$('auth-code').value.trim();await api(authMode==='reset'?'reset-password':authMode,data);if(authMode==='reset'){openAuth('login');notify('비밀번호를 바꿨습니다. 새 비밀번호로 로그인하세요.');}else{$('auth-dialog').close();await enter();}}catch(error){$('auth-error').textContent=error.message;}finally{$('auth-submit').disabled=false;}};
$('connect').onclick=()=>{$('account-description').textContent=member.displayName+' · '+member.username+' · '+(member.role==='admin'?'관리자':'일반 회원');$('account-dialog').showModal();};
function openPassword(){$('password-form').reset();$('password-error').textContent='';if(!$('password-dialog').open)$('password-dialog').showModal();}
$('password-open').onclick=()=>{$('account-dialog').close();openPassword();};
$('password-dialog').addEventListener('close',()=>$('password-form').reset());
$('password-form').onsubmit=async event=>{event.preventDefault();if($('password-new').value!==$('password-repeat').value){$('password-error').textContent='새 비밀번호 확인이 일치하지 않습니다.';return;}const button=event.submitter;button.disabled=true;try{await api('password',{currentPassword:$('password-current').value,password:$('password-new').value});$('password-dialog').close();watchGeneration++;await enter();notify('비밀번호를 변경했습니다. 다른 기기는 다시 로그인하세요.');}catch(error){$('password-error').textContent=error.message;}finally{button.disabled=false;}};
$('logout').onclick=async()=>{if(pending.length){notify('전송 대기 중인 내용이 있습니다. 동기화를 마친 뒤 로그아웃해 주세요.');return;}if(!await confirmAction('이 브라우저에서 로그아웃할까요? 다시 로그인하면 저장한 일정을 볼 수 있습니다.','로그아웃'))return;try{await api('logout',{});connected=false;watchGeneration++;localStorage.removeItem(cacheKey());localStorage.removeItem(stateCacheKey());location.reload();}catch(error){notify(error.message);}};
function drawPerson(pattern){$('person-count').value=pattern.length;$('person-days').replaceChildren();pattern.forEach((shift,index)=>{const label=text('label',(index+1)+'일째'),select=document.createElement('select');for(const [value,name] of Object.entries(labels)){const option=text('option',name);option.value=value;select.append(option);}select.value=shift;label.append(select);$('person-days').append(label);});}
function openPerson(item){if(!item&&personalPeople().length>=20){notify('함께 볼 사람은 20명까지 등록할 수 있습니다.');return;}personId=item?.id??null;const d=item?.data??{name:'',color:'BLUE',anchor:selected,pattern:['DUTY','OFF','REGULAR']};$('person-heading').textContent=item?'함께 보는 근무표 수정':'함께 볼 사람 추가';$('person-name').value=d.name;$('person-color').value=d.color;$('person-anchor').value=d.anchor;$('person-work-week').value=String(d.workWeek||6);$('person-duty-weekday').checked=d.dutyAsWeekday===true;resetPatternMode('person');drawPerson(d.pattern);$('person-delete').hidden=!item;$('person-error').textContent='';$('person-dialog').showModal();}
$('person-add').onclick=()=>openPerson();
$('person-form').onsubmit=event=>{event.preventDefault();const pattern=[...$('person-days').querySelectorAll('select')].map(node=>node.value),name=$('person-name').value.trim();if(!name||pattern.length!==Number($('person-count').value)){$('person-error').textContent='이름과 반복 일수를 확인해 주세요.';return;}queue(personId??crypto.randomUUID(),'person',{name,color:$('person-color').value,anchor:$('person-anchor').value,pattern,workWeek:Number($('person-work-week').value),dutyAsWeekday:$('person-duty-weekday').checked});$('person-dialog').close();notify('함께 보는 근무표를 저장했습니다.');};
$('person-delete').onclick=async()=>{if(await confirmAction('이 캘린더에 등록한 사람의 근무표를 삭제할까요?','근무표 삭제')){queue(personId,'person',{},true);$('person-dialog').close();}};
async function loadMembers(){try{const result=await api('admin/members?q='+encodeURIComponent($('member-query').value.trim())+'&page='+memberPage);$('member-total').textContent='회원 '+result.total+'명 · '+result.page+'페이지';$('member-list').replaceChildren();for(const row of result.members){const card=document.createElement('article');card.className='member-row';const info=document.createElement('div');info.append(text('strong',row.display_name+' · '+row.username),text('p',(row.role==='admin'?'관리자':'일반 회원')+' · '+(row.active?'정상':'이용 중지'),'small'),text('p','가입 '+new Date(row.created*1000).toLocaleDateString('ko-KR')+' · 최근 로그인 '+(row.last_login?new Date(row.last_login*1000).toLocaleDateString('ko-KR'):'없음'),'small'));const edit=text('button',row.id===member.id?'본인':'관리','secondary');edit.disabled=row.id===member.id;edit.onclick=()=>editMember(row);card.append(info,edit);$('member-list').append(card);}$('member-prev').disabled=memberPage===1;$('member-next').disabled=memberPage*50>=result.total;$('member-error').textContent='';}catch(error){$('member-error').textContent=error.message;}}
$('admin-open').onclick=()=>{memberPage=1;$('member-query').value='';$('members-dialog').showModal();loadMembers();};
$('member-search').onsubmit=event=>{event.preventDefault();memberPage=1;loadMembers();};$('member-prev').onclick=()=>{memberPage--;loadMembers();};$('member-next').onclick=()=>{memberPage++;loadMembers();};
function editMember(row){editingMember=row;$('member-heading').textContent=row.username+' 회원 관리';$('member-name').value=row.display_name;$('member-role').value=row.role;$('member-active').value=row.active?'yes':'no';$('member-edit-error').textContent='';$('member-reset-result').hidden=true;$('member-reset-code').value='';$('member-dialog').showModal();}
$('member-dialog').addEventListener('close',()=>{$('member-reset-code').value='';});
$('member-form').onsubmit=async event=>{event.preventDefault();const button=event.submitter;button.disabled=true;try{await api('admin/members/'+editingMember.id,{action:'update',displayName:$('member-name').value.trim(),role:$('member-role').value,active:$('member-active').value==='yes'});$('member-dialog').close();await loadMembers();notify('회원 정보를 저장했습니다.');}catch(error){$('member-edit-error').textContent=error.message;}finally{button.disabled=false;}};
$('member-reset').onclick=async()=>{if(!await confirmAction('이 회원의 일회용 비밀번호 복구 코드를 발급할까요? 기존 복구 코드는 만료됩니다.','복구 코드 발급'))return;try{const result=await api('admin/members/'+editingMember.id,{action:'reset'});$('member-reset-code').value=result.resetCode;$('member-reset-result').hidden=false;}catch(error){$('member-edit-error').textContent=error.message;}};
$('member-delete').onclick=async()=>{if(!await confirmAction(editingMember.username+' 회원과 해당 회원의 일정 및 함께 보는 근무표를 모두 삭제합니다. 되돌릴 수 없습니다. 계속할까요?','회원과 일정 삭제'))return;try{await api('admin/members/'+editingMember.id,{action:'delete'});$('member-dialog').close();await loadMembers();}catch(error){$('member-edit-error').textContent=error.message;}};
function describe(item){if(!item||item.deleted)return '삭제된 일정';const d=item.data;if(item.kind==='anniversary')return d.title+'\n'+annualDescription(d)+'\n'+d.notes;if(item.kind==='preferences')return '당직일 평일색: '+(d.dutyAsWeekday?'켜짐':'꺼짐')+'\n비번 빨간색: '+(d.offAsHoliday?'켜짐':'꺼짐')+'\n음력 표시: '+(d.showLunar?'켜짐':'꺼짐');if(item.kind==='person')return `${d.name} · ${personColors[d.color]}\n첫째 날: ${d.anchor}\n${d.pattern.map(key=>labels[key]).join(' → ')}`;if(item.kind==='rotation')return `첫째 날: ${d.anchor}\n${d.pattern.map(key=>labels[key]).join(' → ')}`;return `${d.title}\n${d.date} ~ ${d.endDate}\n${d.allDay?'하루 종일':d.startTime+' ~ '+d.endTime}\n${categories[d.category]}\n${d.notes}`;}
function showConflict(){const op=pending.find(item=>conflicts.includes(item.changeId));if(!op){$('conflict-dialog').close();return;}$('conflict-local').textContent=describe(op);$('conflict-remote').textContent=describe(model.items.find(item=>item.id===op.id));if(!$('conflict-dialog').open)$('conflict-dialog').showModal();}
$('resolve').onclick=showConflict;
function resolveConflict(useLocal){const op=pending.find(item=>conflicts.includes(item.changeId));if(!op)return;pending=pending.filter(item=>item.changeId!==op.changeId);conflicts=conflicts.filter(id=>id!==op.changeId);if(useLocal)pending.push({...op,baseVersion:model.items.find(item=>item.id===op.id)?.version??0,changeId:crypto.randomUUID()});persist();render();showConflict();sync();}
$('use-remote').onclick=()=>resolveConflict(false);$('use-local').onclick=()=>resolveConflict(true);
document.querySelectorAll('.close').forEach(button=>button.onclick=()=>button.closest('dialog').close());
window.addEventListener('online',()=>sync());window.addEventListener('beforeunload',event=>{if(pending.length){event.preventDefault();event.returnValue='';}});
// 공휴일은 서버와 함께 배포한 자료를 읽는다. 서버의 갱신 작업이 원본을 확인한 뒤 파일을 교체한다.
enter().catch(error=>showWelcome(error.status===401?'로그인 없이 앱 설치 가능':'연결을 확인해 주세요. 앱 설치는 바로 할 수 있습니다.'));
// 유형은 앱과 같은 자료에서 읽는다. 기존 자료를 열 때는 직접 설정으로 시작해 원래 순서를 보존한다.
let workPatterns=[];
function resetPatternMode(prefix){$(prefix+'-mode').value='custom';$(prefix+'-remainder-label').hidden=true;$(prefix+'-count').min='1';}
function resizePattern(prefix){
const duty=$(prefix+'-mode').value==='duty', input=$(prefix+'-count'),count=Number(input.value),minimum=duty?2:1;
if(!Number.isInteger(count)||count<minimum||count>366){$(prefix+'-error').textContent=`${minimum}~366 사이의 숫자를 입력해 주세요.`;return;}
$(prefix+'-error').textContent='';
const old=[...$(prefix+'-days').querySelectorAll('select')].map(node=>node.value);
const pattern=Array.from({length:count},(_,i)=>duty?(i===0?'DUTY':i===1?'OFF':$(prefix+'-remainder').value):(old[i]??'REGULAR'));
(prefix==='rotation'?drawRotation:drawPerson)(pattern);
}
for(const prefix of ['rotation','person']){
$(prefix+'-count').addEventListener('input',()=>resizePattern(prefix));
$(prefix+'-remainder').onchange=()=>resizePattern(prefix);
$(prefix+'-mode').onchange=()=>{
const choice=$(prefix+'-mode').value,duty=choice==='duty';
$(prefix+'-remainder-label').hidden=!duty;$(prefix+'-count').min=duty?'2':'1';
if(duty){if(Number($(prefix+'-count').value)<2)$(prefix+'-count').value='2';resizePattern(prefix);}
else if(choice!=='custom'){const pattern=workPatterns.find(item=>item.id===choice)?.pattern;if(pattern)(prefix==='rotation'?drawRotation:drawPerson)(pattern);}
$(prefix+'-error').textContent='';
};
}
let plannerAssetsStarted=false;
function loadPlannerAssets(){
// 소개 화면을 보는 동안에는 달력 자료를 받지 않는다. 로그인 후 필요한 자료만 한 번 준비한다.
if(plannerAssetsStarted)return;plannerAssetsStarted=true;
cachedAsset('lunar-months.json').then(data=>{lunarData=data;if(connected)render();}).catch(()=>notify('음력 자료를 불러오지 못했습니다. 연결 후 다시 확인해 주세요.'));
cachedAsset('holidays.json').then(data=>{holidayData=data;if(connected)render();}).catch(()=>{});
cachedAsset('work-patterns.json').then(data=>{
if(!Array.isArray(data)||data.some(item=>!Array.isArray(item.pattern)||!item.pattern.length||item.pattern.length>366||item.pattern.some(key=>!labels[key])))throw new Error();
workPatterns=data;
for(const prefix of ['rotation','person'])for(const item of data){const option=text('option',item.name);option.value=item.id;$(prefix+'-mode').append(option);}
}).catch(()=>notify('근무 유형 예시를 불러오지 못했습니다. 직접 설정은 사용할 수 있습니다.'));
}
// 전체 자료는 최초 연결과 변경 알림 및 월별 갱신과 수동 요청에서만 받는다.
// 공개 자료도 같은 주기로 보관한다. 인증이 필요한 개인·소속 자료는 회원별 키로 분리하고 로그아웃 때 지운다.
async function cachedAsset(name,force=false,refreshSource=force){
const key='duty-public-0.5:'+name;let cached;try{cached=JSON.parse(localStorage.getItem(key)||'null');}catch{}
if(!force&&cached&&Date.now()-cached.at<MONTH_MS)return cached.data;
try{const response=await fetch(name==='holidays.json'?'api/holidays'+(refreshSource?'?refresh=true':''):'assets/'+name);if(!response.ok)throw new Error();const data=await response.json();if(name==='holidays.json'){
if(!data||!Object.values(data).every(days=>days&&typeof days==='object'&&Object.entries(days).every(([day,names])=>/^20\d{2}-\d{2}-\d{2}$/.test(day)&&Array.isArray(names)&&names.length&&names.every(value=>typeof value==='string'))))throw new Error();
localStorage.setItem('duty-holiday-revision',response.headers.get('X-Holiday-Revision')||'');
localStorage.setItem('duty-holiday-saved',response.headers.get('X-Holiday-Saved')||'1');
}localStorage.setItem(key,JSON.stringify({at:Date.now(),data}));return data;}
catch(error){if(cached)return cached.data;throw error;}
}
$('refresh-data').onclick=async()=>{const success=await sync(true);if(success){try{holidayData=await cachedAsset('holidays.json',true);render();}catch{}notify('새로 불러왔습니다.');}else notify('서버에 연결하지 못했습니다. 저장된 자료를 유지합니다.');};
// 한국 음력 월 시작일 사이의 날짜 차이를 사용한다. 지원 범위 밖은 추측해 표시하지 않는다.
function lunarLabel(key){
if(!lunarData||key<lunarData.start||key>lunarData.end)return null;
const day=Math.floor(dayDate(key).getTime()/86400000),rows=lunarData.months;
let low=0,high=rows.length;
while(low<high){const mid=(low+high)>>>1;if(rows[mid][0]<=day)low=mid+1;else high=mid;}
if(!low)return null;const row=rows[low-1];return (row[2]?'윤':'음')+row[1]+'.'+(day-row[0]+1);
}
+60
View File
@@ -0,0 +1,60 @@
'use strict';
// 소속 생성과 가입은 로그인한 회원만 진행한다. 화면 권한과 별개로 서버에서도 소속과 관리자 권한을 검사한다.
function renderCompany(){
const group=model.company;
$('company-open').textContent=group?'소속 · '+group.name:'소속 만들기·가입';
$('company-start').hidden=!!group;
$('company-none').hidden=!!group;$('company-current').hidden=!group;
if(!group)return;
$('company-title').textContent=group.name;
$('company-description').textContent=`${group.members.length}명 · ${group.canManage?'소속 관리자':'소속 회원'}`;
$('company-rename').value=group.name;
$('company-owner').hidden=!group.canManage;
$('company-color').value=group.members.find(item=>item.isSelf)?.color||'BLUE';
$('company-members').replaceChildren();
for(const person of group.members){
const row=text('div','','company-member');
const details=text('div','','person-'+person.color.toLowerCase());
details.append(text('strong',person.name+(person.isSelf?' (나)':'')+(person.id===group.ownerId?' · 소속 관리자':'')));
details.append(text('p',person.rotation?'주'+(person.rotation.workWeek||6)+'일제 · '+person.rotation.pattern.map(key=>labels[key]).join(' → '):'근무표 미등록','small'));
row.append(details);
if(group.canManage&&!person.isSelf){
const actions=text('div','','company-actions');
const transfer=text('button','관리자 넘기기','secondary');transfer.type='button';
transfer.onclick=async()=>{if(await confirmAction(person.name+' 회원에게 소속 관리자 권한을 넘길까요? 기존 초대코드도 종료됩니다.','권한 넘기기'))await companyRequest('manage',{action:'transfer',memberId:person.id});};
const remove=text('button','내보내기','danger');remove.type='button';
remove.onclick=async()=>{if(await confirmAction(person.name+' 회원을 소속에서 내보낼까요? 개인 근무표와 일정은 유지됩니다. 기존 초대코드는 종료됩니다.','내보내기'))await companyRequest('manage',{action:'remove',memberId:person.id});};
actions.append(transfer,remove);row.append(actions);
}
$('company-members').append(row);
}
}
function openCompany(){
if(!connected){notify('회원 로그인 후 이용할 수 있습니다.');return;}
$('company-error').textContent='';$('company-code-box').hidden=true;$('company-invite-code').value='';
renderCompany();if(!$('company-dialog').open)$('company-dialog').showModal();
}
let companySaving=false;
async function companyRequest(path,data){
if(companySaving)return;companySaving=true;$('company-error').textContent='';
$('company-dialog').querySelectorAll('button').forEach(button=>button.disabled=true);
try{
const result=await api('company/'+path,data);model=result.state;refreshedAt=Date.now();persist();render();renderCompany();
$('company-code-box').hidden=!result.inviteCode;$('company-invite-code').value=result.inviteCode||'';
$('company-join-code').value='';notify('소속 정보를 반영했습니다.');
}catch(error){$('company-error').textContent=error.message;}
finally{companySaving=false;$('company-dialog').querySelectorAll('button').forEach(button=>button.disabled=false);}
}
for(const id of ['company-create-color','company-join-color','company-color']){
for(const [value,name] of Object.entries(personColors)){const option=text('option',name);option.value=value;$(id).append(option);}
}
$('company-open').onclick=openCompany;
$('company-start-open').onclick=openCompany;
$('company-create-form').onsubmit=event=>{event.preventDefault();companyRequest('create',{name:$('company-create-name').value,color:$('company-create-color').value});};
$('company-join-form').onsubmit=event=>{event.preventDefault();companyRequest('join',{code:$('company-join-code').value.trim(),color:$('company-join-color').value});};
$('company-color-form').onsubmit=event=>{event.preventDefault();companyRequest('manage',{action:'color',color:$('company-color').value});};
$('company-rename-form').onsubmit=event=>{event.preventDefault();companyRequest('manage',{action:'rename',name:$('company-rename').value});};
$('company-invite').onclick=()=>companyRequest('manage',{action:'invite'});
$('company-leave').onclick=async()=>{if(await confirmAction('소속에서 나갈까요? 소속 근무표 공유는 종료되며 개인 근무표와 일정은 유지됩니다.','소속 나가기'))await companyRequest('manage',{action:'leave'});};
$('company-delete').onclick=async()=>{if(await confirmAction('소속을 해산할까요? 전체 회원의 소속 연결만 해제되며 각자의 근무표와 일정은 유지됩니다.','소속 해산'))await companyRequest('manage',{action:'delete'});};
$('company-dialog').addEventListener('close',()=>{$('company-invite-code').value='';$('company-code-box').hidden=true;$('company-join-code').value='';});
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Hyunbin Seo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+213
View File
@@ -0,0 +1,213 @@
{
"2018": {
"2018-01-01": ["1월 1일"],
"2018-02-15": ["설날 전날"],
"2018-02-16": ["설날"],
"2018-02-17": ["설날 다음 날"],
"2018-03-01": ["3ㆍ1절"],
"2018-05-05": ["어린이날"],
"2018-05-07": ["대체공휴일(어린이날)"],
"2018-05-22": ["부처님 오신 날"],
"2018-06-06": ["현충일"],
"2018-06-13": ["전국동시지방선거"],
"2018-08-15": ["광복절"],
"2018-09-23": ["추석 전날"],
"2018-09-24": ["추석"],
"2018-09-25": ["추석 다음 날"],
"2018-09-26": ["대체공휴일(추석)"],
"2018-10-03": ["개천절"],
"2018-10-09": ["한글날"],
"2018-12-25": ["기독탄신일"]
},
"2019": {
"2019-01-01": ["1월 1일"],
"2019-02-04": ["설날 전날"],
"2019-02-05": ["설날"],
"2019-02-06": ["설날 다음 날"],
"2019-03-01": ["3ㆍ1절"],
"2019-05-05": ["어린이날"],
"2019-05-06": ["대체공휴일(어린이날)"],
"2019-05-12": ["부처님 오신 날"],
"2019-06-06": ["현충일"],
"2019-08-15": ["광복절"],
"2019-09-12": ["추석 전날"],
"2019-09-13": ["추석"],
"2019-09-14": ["추석 다음 날"],
"2019-10-03": ["개천절"],
"2019-10-09": ["한글날"],
"2019-12-25": ["기독탄신일"]
},
"2020": {
"2020-01-01": ["1월 1일"],
"2020-01-24": ["설날 전날"],
"2020-01-25": ["설날"],
"2020-01-26": ["설날 다음 날"],
"2020-01-27": ["대체공휴일(설날)"],
"2020-03-01": ["3ㆍ1절"],
"2020-04-15": ["제21대 국회의원선거"],
"2020-04-30": ["부처님 오신 날"],
"2020-05-05": ["어린이날"],
"2020-06-06": ["현충일"],
"2020-08-15": ["광복절"],
"2020-08-17": ["임시공휴일"],
"2020-09-30": ["추석 전날"],
"2020-10-01": ["추석"],
"2020-10-02": ["추석 다음 날"],
"2020-10-03": ["개천절"],
"2020-10-09": ["한글날"],
"2020-12-25": ["기독탄신일"]
},
"2021": {
"2021-01-01": ["1월 1일"],
"2021-02-11": ["설날 전날"],
"2021-02-12": ["설날"],
"2021-02-13": ["설날 다음 날"],
"2021-03-01": ["3ㆍ1절"],
"2021-05-05": ["어린이날"],
"2021-05-19": ["부처님 오신 날"],
"2021-06-06": ["현충일"],
"2021-08-15": ["광복절"],
"2021-08-16": ["대체공휴일(광복절)"],
"2021-09-20": ["추석 전날"],
"2021-09-21": ["추석"],
"2021-09-22": ["추석 다음 날"],
"2021-10-03": ["개천절"],
"2021-10-04": ["대체공휴일(개천절)"],
"2021-10-09": ["한글날"],
"2021-10-11": ["대체공휴일(한글날)"],
"2021-12-25": ["기독탄신일"]
},
"2022": {
"2022-01-01": ["1월 1일"],
"2022-01-31": ["설날 전날"],
"2022-02-01": ["설날"],
"2022-02-02": ["설날 다음 날"],
"2022-03-01": ["3ㆍ1절"],
"2022-03-09": ["대통령선거"],
"2022-05-05": ["어린이날"],
"2022-05-08": ["부처님 오신 날"],
"2022-06-01": ["전국동시지방선거"],
"2022-06-06": ["현충일"],
"2022-08-15": ["광복절"],
"2022-09-09": ["추석 전날"],
"2022-09-10": ["추석"],
"2022-09-11": ["추석 다음 날"],
"2022-09-12": ["대체공휴일(추석)"],
"2022-10-03": ["개천절"],
"2022-10-09": ["한글날"],
"2022-10-10": ["대체공휴일(한글날)"],
"2022-12-25": ["기독탄신일"]
},
"2023": {
"2023-01-01": ["1월 1일"],
"2023-01-21": ["설날 전날"],
"2023-01-22": ["설날"],
"2023-01-23": ["설날 다음 날"],
"2023-01-24": ["대체공휴일(설날)"],
"2023-03-01": ["3ㆍ1절"],
"2023-05-05": ["어린이날"],
"2023-05-27": ["부처님 오신 날"],
"2023-05-29": ["대체공휴일(부처님 오신 날)"],
"2023-06-06": ["현충일"],
"2023-08-15": ["광복절"],
"2023-09-28": ["추석 전날"],
"2023-09-29": ["추석"],
"2023-09-30": ["추석 다음 날"],
"2023-10-02": ["임시공휴일"],
"2023-10-03": ["개천절"],
"2023-10-09": ["한글날"],
"2023-12-25": ["기독탄신일"]
},
"2024": {
"2024-01-01": ["1월 1일"],
"2024-02-09": ["설날 전날"],
"2024-02-10": ["설날"],
"2024-02-11": ["설날 다음 날"],
"2024-02-12": ["대체공휴일(설날)"],
"2024-03-01": ["3ㆍ1절"],
"2024-04-10": ["제22대국회의원선거"],
"2024-05-05": ["어린이날"],
"2024-05-06": ["대체공휴일(어린이날)"],
"2024-05-15": ["부처님 오신 날"],
"2024-06-06": ["현충일"],
"2024-08-15": ["광복절"],
"2024-09-16": ["추석 전날"],
"2024-09-17": ["추석"],
"2024-09-18": ["추석 다음 날"],
"2024-10-01": ["임시공휴일"],
"2024-10-03": ["개천절"],
"2024-10-09": ["한글날"],
"2024-12-25": ["기독탄신일"]
},
"2025": {
"2025-01-01": ["1월 1일"],
"2025-01-27": ["임시공휴일"],
"2025-01-28": ["설날 전날"],
"2025-01-29": ["설날"],
"2025-01-30": ["설날 다음 날"],
"2025-03-01": ["3ㆍ1절"],
"2025-03-03": ["대체공휴일(3ㆍ1절)"],
"2025-05-05": ["어린이날", "부처님 오신 날"],
"2025-05-06": ["대체공휴일(부처님 오신 날)"],
"2025-06-03": ["임시공휴일(대통령선거)"],
"2025-06-06": ["현충일"],
"2025-08-15": ["광복절"],
"2025-10-03": ["개천절"],
"2025-10-05": ["추석 전날"],
"2025-10-06": ["추석"],
"2025-10-07": ["추석 다음 날"],
"2025-10-08": ["대체공휴일(추석)"],
"2025-10-09": ["한글날"],
"2025-12-25": ["기독탄신일"]
},
"2026": {
"2026-01-01": ["1월 1일"],
"2026-02-16": ["설날 전날"],
"2026-02-17": ["설날"],
"2026-02-18": ["설날 다음 날"],
"2026-03-01": ["3ㆍ1절"],
"2026-03-02": ["대체공휴일(3ㆍ1절)"],
"2026-05-01": ["노동절"],
"2026-05-05": ["어린이날"],
"2026-05-24": ["부처님 오신 날"],
"2026-05-25": ["대체공휴일(부처님 오신 날)"],
"2026-06-03": ["전국동시지방선거"],
"2026-06-06": ["현충일"],
"2026-07-17": ["제헌절"],
"2026-08-15": ["광복절"],
"2026-08-17": ["대체공휴일(광복절)"],
"2026-09-24": ["추석 전날"],
"2026-09-25": ["추석"],
"2026-09-26": ["추석 다음 날"],
"2026-10-03": ["개천절"],
"2026-10-05": ["대체공휴일(개천절)"],
"2026-10-09": ["한글날"],
"2026-12-25": ["기독탄신일"]
},
"2027": {
"2027-01-01": ["1월 1일"],
"2027-02-06": ["설날 전날"],
"2027-02-07": ["설날"],
"2027-02-08": ["설날 다음 날"],
"2027-02-09": ["대체공휴일(설날)"],
"2027-03-01": ["3ㆍ1절"],
"2027-05-01": ["노동절"],
"2027-05-03": ["대체공휴일(노동절)"],
"2027-05-05": ["어린이날"],
"2027-05-13": ["부처님 오신 날"],
"2027-06-06": ["현충일"],
"2027-07-17": ["제헌절"],
"2027-07-19": ["대체공휴일(제헌절)"],
"2027-08-15": ["광복절"],
"2027-08-16": ["대체공휴일(광복절)"],
"2027-09-14": ["추석 전날"],
"2027-09-15": ["추석"],
"2027-09-16": ["추석 다음 날"],
"2027-10-03": ["개천절"],
"2027-10-04": ["대체공휴일(개천절)"],
"2027-10-09": ["한글날"],
"2027-10-11": ["대체공휴일(한글날)"],
"2027-12-25": ["기독탄신일"],
"2027-12-27": ["대체공휴일(기독탄신일)"]
}
}
+48
View File
@@ -0,0 +1,48 @@
<!doctype html>
<html lang="ko">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#26364d"><title>당직근무 · 블리어</title><link rel="stylesheet" href="assets/style.css"><script src="assets/anniversary-dates.js" defer></script><script src="assets/app.js" defer></script><script src="assets/anniversaries.js" defer></script><script src="assets/company.js" defer></script><script src="assets/updates.js" defer></script></head>
<body>
<header class="topbar"><a class="brand" href="./"><svg class="brand-mark" viewBox="0 0 40 44" aria-hidden="true"><path d="M5 6H35V40H5Z" fill="#fffdf8" stroke="currentColor" stroke-width="2"/><path d="M5 6H35V15H5Z" fill="currentColor"/><path d="M12 2V9M28 2V9" stroke="currentColor" stroke-width="3"/><path d="M12 22H17V27H12ZM23 22H28V27H23ZM12 31H17V36H12Z" fill="#b65b3c"/><path d="M23 31H28V36H23Z" fill="currentColor"/></svg><span>당직근무<small>나의 근무 기록</small></span></a><div class="top-actions"><span id="status" role="status">연결 확인 중</span><a class="download-small" href="https://forum.itosm.co.kr/c/web-apps/duty-calendar/47">앱 다운로드</a><nav id="public-auth" aria-label="회원 이용"><button id="join" class="secondary">로그인</button><button id="create" class="text-button">회원가입</button></nav><button id="admin-open" class="secondary" hidden>회원 관리</button><button id="refresh-data" class="secondary" hidden>새로 불러오기</button><button id="company-open" class="secondary" hidden>소속 회사</button><button id="connect" class="secondary" hidden>내 정보</button></div></header>
<main>
<section id="welcome" class="welcome">
<div class="welcome-hero">
<div class="welcome-copy"><p class="eyebrow">당직 · 교대근무 · 개인 일정</p><h1>다음 당직,<br>달력에서 바로.</h1><p class="intro">내 근무 순서대로 채워지는 달력.<br>휴대폰을 켜면 홈 화면에서 바로 확인하세요.</p><div class="welcome-actions"><a class="download-button" 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>안드로이드 앱 받기</a><a class="install-link" href="#install-guide">설치 안내</a></div><p class="download-meta"><a href="https://forum.itosm.co.kr/c/web-apps/duty-calendar/47">공식 배포 · 소스 · 제작 매뉴얼</a><br>Android 8.0 이상 · 미리보기 0.10.0</p><div class="welcome-caption"><strong>내 달력은 로그인 없이.</strong><p>함께 보는 근무표와 소속 공유는<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>
<div class="preview-detail"><span class="detail-index">21</span><div><strong>토요일은 당직</strong><p>내일은 비번입니다.</p></div><span class="detail-tag">24시간</span></div>
</figure>
</div>
<section class="feature-ledger" aria-label="앱 주요 기능"><div class="ledger-heading"><span>나에게 맞는 근무 달력</span><p>필요한 기능을 한곳에 담았습니다.</p></div><div class="feature-rows"><article><span class="feature-number">01</span><div><h2>내 근무 주기 그대로</h2><p>2당직부터 원하는 숫자까지. 교대 유형과 주5일·주6일제를 설정하세요.</p></div><span class="feature-label">반복 근무</span></article><article><span class="feature-number">02</span><div><h2>휴일과 약속도 한 달력에</h2><p>한국 공휴일과 개인 일정을 함께 표시하고 홈 화면 위젯으로 확인합니다.</p></div><span class="feature-label">개인 일정</span></article><article><span class="feature-number">03</span><div><h2>같이 일하는 사람들의 근무표</h2><p>이름과 색상으로 구분하고 같은 소속의 당직을 함께 확인하세요.</p></div><span class="feature-label">회원 전용</span></article></div></section>
<section id="install-guide" class="install-guide" aria-labelledby="install-heading"><div><p class="eyebrow">설치 안내</p><h2 id="install-heading">내 휴대폰에 <br>당직근무.</h2><p>안드로이드 휴대폰에서<br>이 페이지를 열어 주세요.</p><a class="install-link" href="https://forum.itosm.co.kr/c/web-apps/duty-calendar/47">설치 파일 내려받기</a></div><div><ol><li><strong>앱 다운로드</strong><span>위의 앱 받기로 포럼을 열고 최신 배포 글의 APK를 저장합니다.</span></li><li><strong>받은 파일 열기</strong><span>설치 허용 안내가 나오면 다운로드에 사용한 브라우저에 한해 허용한 뒤 설치합니다.</span></li><li><strong>근무표 설정과 위젯 추가</strong><span>반복 근무와 기준일을 저장하고 ‘홈 화면에 달력 추가’를 누르세요.</span></li></ol><p class="install-notice">기존 앱은 삭제하지 말고 업데이트하세요. 설치 후 브라우저의 앱 설치 허용은 다시 꺼도 됩니다.</p></div></section><p id="account-notice" class="form-error"></p>
</section>
<section id="workspace" hidden>
<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="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"><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>
</section>
</main><footer><span>당직근무</span><span>제작자 블리어 (이창현)</span><button id="web-update-check">업데이트 확인</button><button id="logout" class="text-button" hidden>로그아웃</button></footer>
<dialog id="anniversary-list-dialog"><div class="dialog-heading"><h2>내 생일·기념일</h2><button type="button" class="icon-button close" aria-label="닫기">×</button></div><p class="small">내 계정에만 보관합니다. 같은 소속의 다른 회원에게 공유하지 않습니다.</p><div id="anniversary-list"></div><div class="dialog-actions"><button type="button" class="secondary close">닫기</button><button id="anniversary-add">추가</button></div></dialog>
<dialog id="anniversary-dialog"><form id="anniversary-form"><div class="dialog-heading"><h2 id="anniversary-heading">생일·기념일 추가</h2><button type="button" class="icon-button close" aria-label="닫기">×</button></div><label>기념일 이름<input id="anniversary-title" maxlength="60" required placeholder="내 생일 · 결혼기념일"></label><div class="field-row"><label>종류<select id="anniversary-category"><option value="BIRTHDAY">생일</option><option value="ANNIVERSARY">기념일</option></select></label><label>날짜 기준<select id="anniversary-calendar"><option value="SOLAR">양력</option><option value="LUNAR">음력</option></select></label></div><div class="field-row"><label>월<input id="anniversary-month" type="number" min="1" max="12" required></label><label>일<input id="anniversary-day" type="number" min="1" max="31" required></label></div><label id="anniversary-leap-label" class="check-label" hidden><input id="anniversary-leap" type="checkbox">음력 윤달</label><p class="small">매년 반복됩니다. 양력 2월 29일과 음력 30일이 없는 해에는 그달 말일에 표시합니다. 윤달이 없는 해에는 같은 일반 월에 표시합니다. 음력은 1900~2050년 자료를 사용합니다.</p><label>휴대폰 알림<select id="anniversary-reminder"><option value="-1">알림 없음</option><option value="0">시작 시간</option><option value="10">10분 전</option><option value="30">30분 전</option><option value="60">1시간 전</option><option value="1440">하루 전</option></select></label><p class="small">기념일 오전 9시를 기준으로 알립니다. 안드로이드 앱의 알림 허용이 필요합니다.</p><label>메모<textarea id="anniversary-notes" maxlength="1000" rows="2"></textarea></label><p class="small">인터넷이 끊기면 기기에 보관한 뒤 연결될 때 서버에 전송합니다. 재설치 전 서버 저장 완료를 확인해 주세요.</p><p id="anniversary-error" class="form-error" role="alert"></p><div class="dialog-actions"><button id="anniversary-delete" type="button" class="danger" hidden>삭제</button><button type="button" class="secondary close">취소</button><button type="submit">저장</button></div></form></dialog>
<dialog id="event-dialog"><form id="event-form"><div class="dialog-heading"><h2 id="event-heading">일정 추가</h2><button type="button" class="icon-button close" aria-label="닫기">×</button></div><p class="small">알바는 근무지와 시간대별로 각각 추가하세요. 밤을 넘기면 종료 날짜를 다음 날로 정합니다.</p><label>제목·근무지<input id="event-title" maxlength="120" required placeholder="어떤 일정인가요?"></label><label>일정 종류<select id="event-category"><option value="GENERAL">개인 일정</option><option value="WORK">업무</option><option value="PARTTIME">알바·시간근무</option><option value="LEAVE">휴가·휴무</option></select></label><div class="field-row"><label>시작 날짜<input id="event-date" type="date" min="2000-01-01" max="2099-12-31" required></label><label>종료 날짜<input id="event-end" type="date" min="2000-01-01" max="2099-12-31" required></label></div><label class="check-label"><input id="event-all-day" type="checkbox" checked>하루 종일</label><div id="time-fields" class="field-row" hidden><label>시작 시간<input id="event-start-time" type="time" value="09:00"></label><label>종료 시간<input id="event-end-time" type="time" value="10:00"></label></div><label>반복<select id="event-repeat"><option value="NONE">반복 없음</option><option value="DAILY">매일</option><option value="WEEKLY">매주</option><option value="MONTHLY">매월</option><option value="YEARLY">매년</option></select></label><label id="event-repeat-until-label">반복 종료일 (선택)<input id="event-repeat-until" type="date" min="2000-01-01" max="2099-12-31"></label><p class="small">반복 수정과 삭제는 전체 반복에 적용합니다. 해당 날짜가 없는 달에는 그달 말일에 표시합니다.</p><label>휴대폰 알림<select id="event-reminder"><option value="-1">알림 없음</option><option value="0">시작 시간</option><option value="10">10분 전</option><option value="30">30분 전</option><option value="60">1시간 전</option><option value="1440">하루 전</option></select></label><p class="small">하루 종일 일정은 오전 9시 기준입니다. 안드로이드 앱에서 알림을 허용해야 하며 절전 중에는 늦게 울릴 수 있습니다. 웹에서는 알림 선택만 저장합니다.</p><label>메모<textarea id="event-notes" maxlength="2000" rows="3" placeholder="장소나 기억할 내용을 적어 주세요."></textarea></label><p id="event-error" class="form-error" role="alert"></p><div class="dialog-actions"><button id="event-delete" type="button" class="danger" hidden>삭제</button><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 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><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="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="members-dialog" class="wide-dialog"><div class="dialog-heading"><h2>회원 관리</h2><button class="icon-button close" aria-label="닫기">×</button></div><form id="member-search" class="field-row"><input id="member-query" aria-label="회원 검색" maxlength="40" placeholder="아이디 또는 이름"><button type="submit">검색</button></form><p id="member-total" class="small"></p><div id="member-list"></div><div class="dialog-actions"><button id="member-prev" class="secondary">이전</button><button id="member-next" class="secondary">다음</button></div><p id="member-error" class="form-error" role="alert"></p></dialog>
<dialog id="member-dialog"><form id="member-form"><div class="dialog-heading"><h2 id="member-heading">회원 수정</h2><button type="button" class="icon-button close" aria-label="닫기">×</button></div><label>이름<input id="member-name" maxlength="40" required></label><label>회원 권한<select id="member-role"><option value="member">일반 회원</option><option value="admin">관리자</option></select></label><label>이용 상태<select id="member-active"><option value="yes">정상</option><option value="no">이용 중지</option></select></label><p class="small">권한을 바꾸거나 이용을 중지하면 해당 회원의 모든 기기 로그인이 해제됩니다. 회원의 개인 일정은 이 관리 화면에서 열람하지 않습니다.</p><div class="dialog-actions"><button id="member-reset" type="button" class="secondary">복구 코드 발급</button><button type="submit">저장</button></div><button id="member-delete" type="button" class="danger">회원과 일정 삭제</button><p id="member-edit-error" class="form-error" role="alert"></p><div id="member-reset-result" hidden><label>일회용 복구 코드<input id="member-reset-code" readonly></label><p class="small">24시간 안에 한 번만 사용할 수 있습니다. 회원 본인을 확인한 뒤 전달하세요. 새 코드를 받으면 이전 코드는 만료됩니다.</p></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>
<dialog id="company-dialog" class="wide-dialog"><div class="dialog-heading"><h2>소속 회사</h2><button type="button" class="icon-button close" aria-label="닫기">×</button></div>
<p class="small">회원 전용입니다. 한 회원은 한 회사에 소속됩니다. 가입하면 본인의 반복 근무표를 소속원과 공유합니다. 개인 일정과 메모 및 직접 등록한 다른 사람의 근무표는 공유하지 않습니다.</p>
<section id="company-none"><form id="company-create-form"><h3>새 소속 만들기</h3><label>회사·소속 이름<input id="company-create-name" maxlength="60" required></label><label>내 근무 표시 색상<select id="company-create-color"></select></label><button type="submit">소속 만들기</button></form><hr><form id="company-join-form"><h3>초대코드로 가입</h3><label>초대코드<input id="company-join-code" maxlength="32" minlength="32" autocomplete="off" required></label><label>내 근무 표시 색상<select id="company-join-color"></select></label><button type="submit">소속 가입</button></form></section>
<section id="company-current" hidden><h3 id="company-title"></h3><p id="company-description" class="small"></p><form id="company-color-form"><label>내 근무 표시 색상<select id="company-color"></select></label><button type="submit" class="secondary">내 색상 저장</button></form><div id="company-owner" hidden><form id="company-rename-form"><label>회사·소속 이름<input id="company-rename" maxlength="60" required></label><button type="submit" class="secondary">이름 변경</button></form><button type="button" id="company-invite">새 초대코드 발급</button><p class="small">초대코드는 7일 동안 사용할 수 있습니다. 새 코드를 발급하면 이전 코드는 종료됩니다. 소속원에게만 전달해 주세요.</p><button type="button" id="company-delete" class="danger">소속 해산</button></div><div id="company-code-box" hidden><label>초대코드 · 이 창에서만 표시<input id="company-invite-code" readonly autocomplete="off"></label></div><h3>소속 회원의 근무표</h3><div id="company-members"></div><button type="button" id="company-leave" class="secondary">소속 나가기</button></section><p id="company-error" class="form-error" role="alert"></p></dialog>
<dialog id="update-dialog" aria-labelledby="update-heading"><h2 id="update-heading">새 버전이 준비됐습니다</h2><p id="update-description"></p><pre id="update-notes"></pre><div class="dialog-actions"><button id="update-later" class="secondary">나중에</button><button id="update-apply">새로고침하고 업데이트</button></div></dialog>
</body></html>
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2018-2020 Jinil Lee <usingsky@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+1
View File
@@ -0,0 +1 @@
{"start":"1900-01-01","end":"2050-12-31","months":[[-25892,1,0],[-25862,2,0],[-25833,3,0],[-25803,4,0],[-25774,5,0],[-25744,6,0],[-25715,7,0],[-25685,8,0],[-25655,9,0],[-25626,10,0],[-25596,11,0],[-25567,12,0],[-25537,1,0],[-25508,2,0],[-25478,3,0],[-25449,4,0],[-25420,5,0],[-25390,6,0],[-25361,7,0],[-25331,8,0],[-25301,8,1],[-25272,9,0],[-25242,10,0],[-25212,11,0],[-25183,12,0],[-25153,1,0],[-25124,2,0],[-25094,3,0],[-25065,4,0],[-25036,5,0],[-25006,6,0],[-24977,7,0],[-24947,8,0],[-24918,9,0],[-24888,10,0],[-24858,11,0],[-24828,12,0],[-24799,1,0],[-24769,2,0],[-24740,3,0],[-24710,4,0],[-24681,5,0],[-24652,6,0],[-24622,7,0],[-24593,8,0],[-24563,9,0],[-24534,10,0],[-24504,11,0],[-24474,12,0],[-24444,1,0],[-24415,2,0],[-24385,3,0],[-24356,4,0],[-24326,5,0],[-24297,5,1],[-24268,6,0],[-24238,7,0],[-24209,8,0],[-24180,9,0],[-24150,10,0],[-24120,11,0],[-24091,12,0],[-24061,1,0],[-24031,2,0],[-24001,3,0],[-23972,4,0],[-23942,5,0],[-23913,6,0],[-23884,7,0],[-23854,8,0],[-23825,9,0],[-23796,10,0],[-23766,11,0],[-23736,12,0],[-23707,1,0],[-23677,2,0],[-23647,3,0],[-23618,4,0],[-23588,5,0],[-23558,6,0],[-23529,7,0],[-23500,8,0],[-23470,9,0],[-23441,10,0],[-23411,11,0],[-23382,12,0],[-23352,1,0],[-23323,2,0],[-23293,3,0],[-23263,4,0],[-23234,4,1],[-23204,5,0],[-23175,6,0],[-23145,7,0],[-23116,8,0],[-23086,9,0],[-23057,10,0],[-23027,11,0],[-22998,12,0],[-22968,1,0],[-22939,2,0],[-22909,3,0],[-22880,4,0],[-22850,5,0],[-22821,6,0],[-22791,7,0],[-22761,8,0],[-22732,9,0],[-22702,10,0],[-22673,11,0],[-22643,12,0],[-22614,1,0],[-22584,2,0],[-22555,3,0],[-22526,4,0],[-22496,5,0],[-22466,6,0],[-22437,7,0],[-22407,8,0],[-22378,9,0],[-22348,10,0],[-22318,11,0],[-22289,12,0],[-22259,1,0],[-22230,2,0],[-22200,2,1],[-22171,3,0],[-22142,4,0],[-22112,5,0],[-22083,6,0],[-22053,7,0],[-22024,8,0],[-21994,9,0],[-21964,10,0],[-21934,11,0],[-21905,12,0],[-21875,1,0],[-21846,2,0],[-21816,3,0],[-21787,4,0],[-21758,5,0],[-21728,6,0],[-21699,7,0],[-21669,8,0],[-21640,9,0],[-21610,10,0],[-21580,11,0],[-21550,12,0],[-21521,1,0],[-21491,2,0],[-21462,3,0],[-21432,4,0],[-21403,5,0],[-21374,6,0],[-21344,6,1],[-21315,7,0],[-21286,8,0],[-21256,9,0],[-21226,10,0],[-21197,11,0],[-21167,12,0],[-21137,1,0],[-21107,2,0],[-21078,3,0],[-21048,4,0],[-21019,5,0],[-20990,6,0],[-20960,7,0],[-20931,8,0],[-20902,9,0],[-20872,10,0],[-20842,11,0],[-20813,12,0],[-20783,1,0],[-20753,2,0],[-20723,3,0],[-20694,4,0],[-20664,5,0],[-20635,6,0],[-20606,7,0],[-20576,8,0],[-20547,9,0],[-20518,10,0],[-20488,11,0],[-20459,12,0],[-20429,1,0],[-20399,2,0],[-20369,3,0],[-20340,4,0],[-20310,5,0],[-20280,5,1],[-20251,6,0],[-20222,7,0],[-20192,8,0],[-20163,9,0],[-20133,10,0],[-20104,11,0],[-20075,12,0],[-20045,1,0],[-20015,2,0],[-19986,3,0],[-19956,4,0],[-19926,5,0],[-19897,6,0],[-19867,7,0],[-19838,8,0],[-19808,9,0],[-19779,10,0],[-19749,11,0],[-19720,12,0],[-19690,1,0],[-19661,2,0],[-19631,3,0],[-19602,4,0],[-19572,5,0],[-19543,6,0],[-19513,7,0],[-19483,8,0],[-19454,9,0],[-19424,10,0],[-19395,11,0],[-19365,12,0],[-19336,1,0],[-19306,2,0],[-19277,2,1],[-19248,3,0],[-19218,4,0],[-19189,5,0],[-19159,6,0],[-19129,7,0],[-19100,8,0],[-19070,9,0],[-19040,10,0],[-19011,11,0],[-18981,12,0],[-18952,1,0],[-18922,2,0],[-18893,3,0],[-18864,4,0],[-18834,5,0],[-18805,6,0],[-18775,7,0],[-18746,8,0],[-18716,9,0],[-18686,10,0],[-18656,11,0],[-18627,12,0],[-18597,1,0],[-18568,2,0],[-18538,3,0],[-18509,4,0],[-18480,5,0],[-18450,6,0],[-18421,7,0],[-18391,7,1],[-18362,8,0],[-18332,9,0],[-18302,10,0],[-18273,11,0],[-18243,12,0],[-18213,1,0],[-18184,2,0],[-18154,3,0],[-18125,4,0],[-18096,5,0],[-18066,6,0],[-18037,7,0],[-18008,8,0],[-17978,9,0],[-17948,10,0],[-17919,11,0],[-17889,12,0],[-17859,1,0],[-17829,2,0],[-17800,3,0],[-17770,4,0],[-17741,5,0],[-17712,6,0],[-17682,7,0],[-17653,8,0],[-17624,9,0],[-17594,10,0],[-17565,11,0],[-17535,12,0],[-17505,1,0],[-17475,2,0],[-17446,3,0],[-17416,4,0],[-17386,5,0],[-17357,5,1],[-17328,6,0],[-17298,7,0],[-17269,8,0],[-17240,9,0],[-17210,10,0],[-17181,11,0],[-17151,12,0],[-17121,1,0],[-17092,2,0],[-17062,3,0],[-17032,4,0],[-17003,5,0],[-16973,6,0],[-16944,7,0],[-16914,8,0],[-16885,9,0],[-16855,10,0],[-16826,11,0],[-16797,12,0],[-16767,1,0],[-16737,2,0],[-16708,3,0],[-16678,4,0],[-16649,5,0],[-16619,6,0],[-16589,7,0],[-16560,8,0],[-16530,9,0],[-16501,10,0],[-16471,11,0],[-16442,12,0],[-16413,1,0],[-16383,2,0],[-16354,3,0],[-16324,4,0],[-16294,4,1],[-16265,5,0],[-16235,6,0],[-16206,7,0],[-16176,8,0],[-16146,9,0],[-16117,10,0],[-16087,11,0],[-16058,12,0],[-16028,1,0],[-15999,2,0],[-15970,3,0],[-15940,4,0],[-15911,5,0],[-15881,6,0],[-15852,7,0],[-15822,8,0],[-15792,9,0],[-15763,10,0],[-15733,11,0],[-15703,12,0],[-15674,1,0],[-15644,2,0],[-15615,3,0],[-15586,4,0],[-15556,5,0],[-15527,6,0],[-15497,7,0],[-15468,8,0],[-15438,9,0],[-15408,10,0],[-15379,11,0],[-15349,12,0],[-15319,1,0],[-15290,2,0],[-15260,2,1],[-15231,3,0],[-15202,4,0],[-15172,5,0],[-15143,6,0],[-15114,7,0],[-15084,8,0],[-15054,9,0],[-15025,10,0],[-14995,11,0],[-14965,12,0],[-14935,1,0],[-14906,2,0],[-14876,3Line truncated
+30
View File
@@ -0,0 +1,30 @@
/* 종이 달력의 날짜 격자와 작은 표제를 중심으로 구성한다. 근무 색과 날짜 색은 서로 구분한다. */
:root{font-family:system-ui,-apple-system,'Segoe UI','Malgun Gothic',sans-serif;color:#26364d;background:#f4f1ea;font-synthesis:none;--ink:#26364d;--green:#26364d;--muted:#626976;--line:#dcdedc;--red:#b24d52;--blue:#365fad;--paper:#fffefa;--accent:#b65b3c}
*{box-sizing:border-box}body{margin:0}button,input,select,textarea{font:inherit}button,a,input,select,textarea{-webkit-tap-highlight-color:transparent}button{border:1px solid transparent;border-radius:5px;padding:11px 17px;background:var(--ink);color:#fff;font-weight:650;cursor:pointer;min-height:44px}button:hover{background:#3a4c65}button:disabled{opacity:.5;cursor:wait}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible{outline:3px solid #b65b3c;outline-offset:4px}a{color:var(--ink);text-underline-offset:4px}[hidden]{display:none!important}h1,h2,h3,p{margin:0}h1{font-size:32px;line-height:1.3;letter-spacing:-1.4px}h2{font-size:20px;letter-spacing:-.7px}h3{font-size:17px}.small{font-size:13px;line-height:1.75;color:var(--muted)}.eyebrow{font-size:12px;font-weight:650;letter-spacing:.04em;color:var(--muted);margin-bottom:10px}
.topbar{max-width:1320px;min-height:96px;margin:auto;padding:21px 40px;display:flex;align-items:center;justify-content:space-between;gap:28px;border-bottom:1px solid #cfd2d2}.brand{display:flex;align-items:center;gap:13px;text-decoration:none;font-size:21px;font-weight:750;letter-spacing:-.7px;white-space:nowrap}.brand-mark{display:block;width:36px;height:40px;flex-shrink:0}.brand small{display:block;font-size:11px;font-weight:450;letter-spacing:.04em;color:var(--muted);margin-top:4px}.top-actions{display:flex;align-items:center;justify-content:flex-end;gap:17px;flex-wrap:wrap}.top-actions button{font-size:12px;padding:9px 14px;min-height:40px}#public-auth{display:flex;align-items:center;gap:4px}#status{font-size:11px;color:var(--muted)}.download-small{font-size:12px;white-space:nowrap}.secondary{background:transparent;color:var(--ink);border-color:#c6cbd0}.secondary:hover{background:#e5e8ec}.text-button{background:transparent;color:var(--ink);padding:8px 4px;font-size:13px}.text-button:hover{background:#e7e8e6}.icon-button{background:transparent;color:var(--ink);padding:10px;width:42px;min-height:42px}.icon-button:hover{background:#eaedea}.icon-button svg{display:block;width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:1.7}
main{max-width:1320px;margin:auto;padding:40px}.welcome{padding:12px 0 0}.welcome-hero{display:grid;grid-template-columns:minmax(0,.82fr) minmax(0,1.18fr);gap:85px;align-items:center;padding:0 0 64px}.welcome-copy h1{font-size:clamp(38px,4vw,54px);font-weight:700;line-height:1.28;letter-spacing:-2.8px;margin:24px 0}.intro{font-size:16px;color:#5c626d;line-height:1.9;letter-spacing:-.3px}.welcome-actions{display:flex;align-items:center;gap:23px;margin:28px 0 12px}.download-button{display:inline-flex;align-items:center;justify-content:center;gap:12px;background:var(--ink);color:white;border:1px solid var(--ink);border-radius:5px;padding:15px 20px;min-height:54px;font-size:14px;font-weight:650;text-decoration:none;white-space:nowrap}.download-button:hover{background:#3a4c65}.download-button svg{width:19px;height:19px;fill:none;stroke:currentColor;stroke-width:1.7}.install-link{display:inline-flex;align-items:center;min-height:44px;font-size:13px;white-space:nowrap}.download-meta{font-size:11px;color:var(--muted)}.welcome-caption{margin-top:39px;border-left:2px solid var(--accent);padding-left:16px}.welcome-caption strong{font-size:14px;font-weight:650}.welcome-caption p{font-size:12px;line-height:1.8;color:var(--muted);margin-top:6px}
/* 예시 달력은 로그인 데이터와 분리한다. 고정 예시임을 표제에 밝히고 실제 사용 화면과 같은 색을 쓴다. */
.calendar-preview{margin:0;min-width:0;position:relative;padding:0 12px 0 0}.calendar-preview figcaption{display:flex;justify-content:space-between;margin:0 0 13px;font-size:11px;letter-spacing:.02em;color:var(--muted)}.calendar-preview figcaption span:last-child{color:#7c8188}.calendar-paper{position:relative;padding:24px 25px 16px;background:var(--paper);border:1px solid #dbd8ce;border-top:5px solid var(--ink);border-radius:3px;box-shadow:8px 8px 0 #e8e4da,0 15px 30px #29334509}.paper-heading{display:flex;align-items:center;justify-content:space-between;margin-bottom:19px}.paper-heading>div:first-child{display:flex;align-items:baseline;gap:15px}.paper-year{font-size:12px;font-weight:550;color:#5c6471;writing-mode:vertical-rl;transform:rotate(180deg)}.paper-heading strong{font-size:54px;line-height:1;letter-spacing:-2px;font-weight:600;font-variant-numeric:tabular-nums}.paper-heading strong span{font-size:15px;margin-left:5px;letter-spacing:0}.paper-note{text-align:right;display:flex;flex-direction:column;gap:7px;font-size:12px}.paper-note span{font-size:10px;color:var(--muted)}.sample-week,.sample-grid{display:grid;grid-template-columns:repeat(7,minmax(0,1fr))}.sample-week{text-align:center;border-top:1px solid var(--ink);border-bottom:1px solid var(--line);padding:10px 0;font-size:10px}.sample-week span:first-child{color:var(--red)}.sample-week span:last-child{color:var(--blue)}.sample-day{min-height:57px;padding:8px 2px 5px;border-bottom:1px solid #e8e7e1;display:flex;flex-direction:column;align-items:center;gap:5px}.sample-day>span{font-size:14px;font-variant-numeric:tabular-nums}.sample-day.sun>span{color:var(--red)}.sample-day.sat>span{color:var(--blue)}.sample-day em{font-size:9px;font-style:normal;padding:2px 5px;border-radius:2px}.sample-day.picked{background:#f9eee6;box-shadow:inset 0 0 0 1px #c27859}.paper-footer{display:flex;align-items:center;justify-content:space-between;gap:8px;padding-top:13px;font-size:10px;color:#686d75}.paper-footer i{display:inline-block;width:5px;height:5px;background:var(--accent);margin:0 6px 2px 0}.preview-detail{position:relative;display:flex;align-items:center;gap:16px;margin:18px 0 0 35px;padding:13px 18px;border-left:3px solid var(--accent);background:#e9e3d7}.detail-index{font-size:30px;font-weight:500;line-height:1}.preview-detail strong{font-size:12px}.preview-detail p{font-size:11px;color:var(--muted);margin-top:4px}.detail-tag{margin-left:auto;font-size:10px;color:#655e57}
.feature-ledger{display:grid;grid-template-columns:1fr 2fr;gap:55px;border-top:1px solid var(--ink);padding:31px 0 50px}.ledger-heading>span{font-size:18px;font-weight:700;letter-spacing:-.5px}.ledger-heading p{margin-top:11px;font-size:12px;line-height:1.8;color:var(--muted)}.feature-rows article{display:flex;align-items:flex-start;gap:23px;padding:23px 0;border-bottom:1px solid #d7d9d7}.feature-rows article:first-child{padding-top:0}.feature-number{font-size:12px;color:var(--accent);font-variant-numeric:tabular-nums;line-height:24px}.feature-rows h2{font-size:16px;margin-bottom:8px}.feature-rows p{font-size:13px;line-height:1.8;color:var(--muted)}.feature-label{margin-left:auto;flex-shrink:0;font-size:10px;padding-top:5px;color:var(--muted)}.install-guide{display:grid;grid-template-columns:1fr 2fr;gap:55px;border-top:1px solid var(--ink);padding:34px 0 12px;scroll-margin-top:25px}.install-guide h2{font-size:29px;line-height:1.4;letter-spacing:-1px;margin:15px 0}.install-guide>div>p:not(.eyebrow):not(.install-notice){font-size:13px;line-height:1.8;color:var(--muted)}.install-guide .install-link{margin-top:12px}.install-guide ol{list-style:none;margin:0;padding:0;counter-reset:steps}.install-guide li{position:relative;counter-increment:steps;padding:0 0 24px 38px}.install-guide li:before{content:counter(steps);position:absolute;left:0;top:1px;font-size:12px;border-bottom:1px solid var(--accent);padding:0 4px 4px;color:var(--accent)}.install-guide strong{display:block;font-size:14px;margin-bottom:8px}.install-guide li span{display:block;font-size:13px;line-height:1.8;color:var(--muted)}.install-notice{font-size:11px;line-height:1.9;color:var(--muted);padding:15px 0 0;border-top:1px solid var(--line)}
/* 회원 화면은 달력을 주 작업 영역으로 두고 당일 정보와 소속 안내를 얇은 띠로 배치한다. */
.page-heading{display:flex;align-items:center;justify-content:space-between;margin-bottom:25px}.summary-row{display:grid;grid-template-columns:1.3fr 1fr;border-top:2px solid var(--ink);border-bottom:1px solid #cbd0d2;margin-bottom:22px;background:var(--paper)}.today-card{padding:21px 25px;border-left:4px solid var(--accent)}.today-card h2{font-size:25px;margin:5px 0 7px}.today-card p{color:var(--muted);font-size:12px}.month-summary{padding:21px 25px;border-left:1px solid var(--line);display:grid;grid-template-columns:1fr auto;align-items:center;gap:3px}.month-summary strong{font-size:31px;font-weight:550;grid-row:span 2;font-variant-numeric:tabular-nums}.month-summary span:nth-child(3){font-size:12px;color:var(--muted)}.month-summary button{justify-self:start;padding:3px 0;min-height:32px}.company-start{display:flex;justify-content:space-between;align-items:center;gap:22px;padding:3px 0 21px;border-bottom:1px solid #d6dadb;margin-bottom:25px}.company-start h2{font-size:14px;margin-bottom:6px}.company-start p{font-size:12px;line-height:1.7;color:var(--muted)}.company-start button{font-size:12px;flex-shrink:0;background:transparent;color:var(--ink);border-color:#bfc6cd}.calendar-layout{display:grid;grid-template-columns:minmax(0,1fr) 270px;gap:30px;align-items:start}.calendar-card{background:var(--paper);border:1px solid #d6d7d4;border-top:4px solid var(--ink);border-radius:3px;padding:23px}.agenda-card{padding:5px 0;background:transparent}.month-heading{display:flex;justify-content:space-between;align-items:center;margin-bottom:19px}.month-heading h2{font-size:26px;letter-spacing:-1px}.month-controls{display:flex;gap:3px;align-items:center}.week,.grid{display:grid;grid-template-columns:repeat(7,minmax(0,1fr))}.week{font-size:11px;color:var(--muted);text-align:center;border-top:1px solid #818b95;padding:12px 0}.week span:first-child{color:var(--red)}.week span:last-child{color:var(--blue)}.day{background:transparent;border:0;border-top:1px solid #e5e5df;border-radius:0;min-height:98px;padding:9px 2px 6px;color:var(--ink);display:flex;align-items:center;flex-direction:column;gap:5px;overflow:hidden;min-width:0;font-weight:450}.day:hover{background:#efeee7}.day.selected{background:#f4efe5;box-shadow:inset 0 0 0 1px #c1a484}.day.outside{opacity:.35}.day-number{font-size:15px;min-width:25px;line-height:25px;border-radius:3px;text-align:center;font-variant-numeric:tabular-nums}.day.current .day-number{background:var(--ink);color:white!important}.day.sun .day-number,.day.holiday .day-number{color:var(--red)}.day.sat:not(.holiday) .day-number{color:var(--blue)}.five-day .week span:last-child,.five-day .day.sat:not(.holiday) .day-number{color:var(--red)}.shift{border-radius:2px;padding:2px 5px;font-size:10px;line-height:16px}.duty{color:#aa4c2e;background:#faeadd}.off{color:#666f7c;background:#edf0f2}.regular{color:#365fad;background:#eaf0fc}.shift.daytime{color:#9b561d;background:#fff1df}.shift.evening{color:#ad3d6e;background:#fbeaf0}.shift.night{color:#79459d;background:#f1eaf8}.shift.rest{color:#64748b;background:#f0f3f5}.holiday-name{font-size:9px;color:var(--red);white-space:nowrap;max-width:100%;overflow:hidden;text-overflow:ellipsis}.event-count{font-size:10px;font-weight:650;color:#885c2e;white-space:nowrap}.legend{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-top:17px;font-size:10px;color:var(--muted)}.legend span{padding:3px 5px;border-radius:2px}.legend span:last-child{padding:3px 0;width:100%}.agenda-heading{display:flex;align-items:center;justify-content:space-between;gap:8px}.agenda-heading h2{margin-top:7px;font-size:22px}.agenda-card>p{font-size:12px;line-height:1.8;color:var(--muted);margin:13px 0 20px}.event-item{width:100%;text-align:left;background:#fffefa;color:var(--ink);border:1px solid #d5d7d6;border-left:3px solid #7c899a;margin:0 0 10px;padding:13px;border-radius:2px;font-weight:500;overflow-wrap:anywhere}.event-item:hover{background:#eaeef2}.event-item.work{border-left-color:#365fad}.event-item.leave{border-left-color:var(--accent)}.event-item strong{display:block;font-size:14px;line-height:1.5}.event-item span{display:block;font-size:11px;color:var(--muted);margin-top:6px}.empty{padding:23px 0;color:var(--muted);font-size:12px;line-height:1.9;border-top:1px solid var(--line)}.source-note{font-size:10px;color:var(--muted);margin-top:18px;line-height:1.8}.source-note span{display:block}.people-panel{border-top:1px solid #bfc5ca;margin-top:22px;padding-top:20px}.people-panel h3{font-size:15px}.people-panel>p{margin:8px 0 15px}.person-row{display:block;text-align:left;width:100%;background:var(--paper);margin:8px 0;border:1px solid var(--line);border-left:3px solid currentColor;border-radius:2px;overflow-wrap:anywhere}.person-row:hover{background:#eaeef2}.person-row small{display:block;color:var(--muted);font-weight:400;font-size:11px;margin-top:5px}.person-badge{font-size:10px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:650}.person-blLine truncated
footer{max-width:1240px;margin:15px auto 0;padding:24px 0 34px;border-top:1px solid #bec4c7;display:flex;align-items:center;gap:20px;color:var(--muted);font-size:11px}footer span:first-child{font-weight:700;margin-right:auto;color:var(--ink)}
/* 입력 창은 제목과 입력칸의 경계를 분명히 둔다. 키보드와 화면 읽기 기능의 기본 동작을 유지한다. */
dialog{border:1px solid #c2c8cd;border-top:4px solid var(--ink);border-radius:5px;padding:27px;width:min(540px,calc(100% - 28px));max-height:90dvh;color:var(--ink);background:var(--paper);box-shadow:0 18px 60px #16203024}dialog::backdrop{background:#18243780}.dialog-heading{display:flex;align-items:center;justify-content:space-between;margin-bottom:20px}.dialog-heading .close{font-size:26px}.dialog-actions{display:flex;gap:9px;justify-content:flex-end;margin-top:23px}.dialog-actions .danger{margin-right:auto}.danger{background:#f8e9e6;color:#9e3934;border-color:#e4c3be}.danger:hover{background:#eed2cd}label{display:flex;flex-direction:column;gap:8px;font-size:13px;font-weight:650;margin-top:18px}input,select,textarea{width:100%;min-width:0;border:1px solid #b8c0c9;border-radius:4px;background:#fff;padding:11px 12px;color:var(--ink);font-size:15px;line-height:1.5}textarea{resize:vertical}.field-row{display:flex;gap:12px}.field-row>label{flex:1;min-width:0}.check-label{flex-direction:row;align-items:center}.check-label input{width:19px;height:19px;accent-color:var(--ink)}.form-error{color:#9e3934;font-size:13px;line-height:1.7;margin-top:12px}.rotation-days{display:grid;grid-template-columns:1fr 1fr;gap:0 14px}.rotation-days label{margin-top:12px}.pair-code{font-size:28px;letter-spacing:4px}.pair-code+p,dialog p{line-height:1.8}.toast{position:fixed;bottom:25px;left:50%;transform:translateX(-50%);z-index:10;max-width:calc(100% - 30px);padding:13px 22px;background:var(--ink);color:white;border-radius:4px;font-size:13px;box-shadow:0 5px 15px #0002}pre{white-space:pre-wrap;overflow-wrap:anywhere;font-family:inherit;font-size:13px;line-height:1.8;padding:15px;background:#f0efe9;border:1px solid var(--line)}#conflict-notice{padding:18px 0;margin-top:20px;border-top:2px solid var(--accent)}#conflict-notice p{margin:10px 0;font-size:12px}#conflict-dialog h3{margin-top:18px}.wide-dialog{width:min(850px,calc(100% - 28px))}.member-row{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:16px 0;border-bottom:1px solid var(--line)}.member-row strong{overflow-wrap:anywhere}.member-row>div{min-width:0}.member-row button{flex-shrink:0}#member-total{margin:16px 0 4px}#member-delete{margin-top:20px;width:100%}#confirm-message{margin-top:15px}#account-description{margin-bottom:14px}#member-reset-code,#company-invite-code{font-family:monospace}#account-notice:empty{display:none}.company-member{display:flex;justify-content:space-between;gap:14px;padding:15px 0;border-bottom:1px solid var(--line)}.company-member>div{min-width:0}.company-member p{overflow-wrap:anywhere}.company-actions{display:flex;gap:8px;align-items:flex-start;flex-wrap:wrap}.company-actions button{font-size:12px;padding:9px}#company-dialog h3{margin-top:24px}#company-dialog form>button,#company-invite,#company-delete,#company-leave{margin-top:14px}#company-dialog hr{margin:24px 0;border:0;border-top:1px solid var(--line)}#company-code-box{padding:10px 16px;background:#e9edf3;border-radius:4px;margin-top:16px}
@media(max-width:1100px){.welcome-hero{gap:42px;grid-template-columns:minmax(0,.85fr) minmax(0,1.15fr)}.welcome-copy h1{font-size:43px}.welcome-actions{gap:15px;flex-wrap:wrap}.calendar-paper{padding:20px 18px 15px}.calendar-layout{gap:22px;grid-template-columns:minmax(0,1fr) 245px}.top-actions{gap:10px}.topbar{padding-left:30px;padding-right:30px}main{padding:35px 30px}footer{margin-left:30px;margin-right:30px}.feature-ledger,.install-guide{gap:35px}}
@media(max-width:760px){.topbar{padding:18px 20px;gap:15px;min-height:86px;align-items:flex-start}.brand{font-size:19px;gap:10px}.brand-mark{width:30px;height:34px}.brand small{font-size:10px}.top-actions{gap:7px;max-width:240px}.top-actions button{font-size:11px;padding:7px 10px}.top-actions .download-small{display:none}#status{display:none}#public-auth{gap:1px}main{padding:30px 20px}.welcome{padding:5px 0 0}.welcome-hero{grid-template-columns:1fr;gap:38px;padding-bottom:38px}.welcome-copy h1{font-size:43px;letter-spacing:-2px;margin:17px 0}.intro{font-size:14px;line-height:1.8}.welcome-actions{gap:20px;margin:23px 0 10px}.download-button{font-size:13px;padding:14px 18px;min-height:50px}.welcome-caption{margin-top:24px}.welcome-caption p br{display:none}.calendar-preview{padding-right:8px;max-width:530px;width:100%;margin:0 auto}.calendar-paper{padding:19px 16px 14px}.paper-heading{margin-bottom:16px}.paper-heading strong{font-size:47px}.sample-day{min-height:55px}.preview-detail{margin-left:20px}.feature-ledger,.install-guide{grid-template-columns:1fr;gap:25px;padding-top:25px}.feature-ledger{padding-bottom:35px}.ledger-heading p{margin-top:7px}.feature-rows article{gap:17px;padding:21px 0}.feature-rows h2{font-size:15px}.feature-rows p{font-size:12px}.feature-label{display:none}.install-guide h2{font-size:27px}.install-guide h2 br,.install-guide>div>p br{display:none}.install-guide .install-link{margin-top:5px}.install-guide li{padding-bottom:23px}.page-heading{margin-bottom:20px}.page-heading h1{font-size:28px}.page-heading button{font-size:12px}.summary-row{grid-template-columns:1fr}.today-card{padding:18px 20px}.today-card h2{font-size:23px}.month-summary{border-left:0;border-top:1px solid var(--line);padding:12px 20px;grid-template-columns:1fr auto 1fr;gap:8px}.month-summary strong{font-size:24px;grid-row:auto}.month-summary span:nth-child(3){display:none}.month-summary button{justify-self:end;font-size:12px}.company-start{align-items:flex-start;gap:12px}.company-start h2{font-size:13px}.company-start p{font-size:11px}.company-start button{font-size:11px;padding:8px 10px;max-width:120px}.calendar-layout{grid-template-columns:1fr;gap:28px}.calendar-card{padding:18px 9px}.month-heading{padding:0 6px;margin-bottom:16px}.month-heading h2{font-size:23px}.month-controls .secondary{font-size:11px;padding:8px 10px;min-height:38px}.day{min-height:85px;padding:8px 1px 4px;gap:4px}.shift{font-size:9px;padding:1px 4px}.day-number{font-size:14px}.holiday-name{font-size:8px}.event-count{font-size:9px}.legend{gap:5px;padding:0 4px}.with-people .day{min-height:124px}.person-badge{font-size:9px}.agenda-card{padding:0}.agenda-heading h2{font-size:23px}.people-panel{margin-top:20px}.source-note{font-size:10px}footer{margin:15px 20px 0;padding:21px 0 25px;gap:8px;flex-wrap:wrap;font-size:10px}footer button{width:100%;text-align:right}dialog{padding:20px}.dialog-actions button{padding:10px 13px;font-size:13px}.member-row{align-items:flex-start}.member-row strong{font-size:14px}.company-member{flex-direction:column}.field-row{gap:9px}}
@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important}}
/* 당직일의 평일색 선택은 토요일과 공휴일 규칙보다 우선한다. 오늘 표식의 흰 글자는 유지한다. */
.day.duty-weekday:not(.current) .day-number{color:var(--ink)!important}
.lunar-date{display:block;font-size:10px;line-height:1.4;color:var(--muted)}.day.with-lunar{min-height:116px}.day.current .lunar-date{color:inherit;opacity:.85}
.day.off-red:not(.current) .day-number{color:var(--red)!important}.day.off-red .shift.off{color:var(--red);background:#fbeaec}
/* 계산 기준과 표시 선택의 입구를 나누고 좁은 화면에서도 버튼이 겹치지 않게 한다. */
.settings-actions{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-top:8px}.settings-section{border-top:1px solid var(--line);padding-top:20px;margin-top:24px}
.anniversary-panel{border-top:1px solid var(--line);padding-top:18px;margin-top:20px}.anniversary-row{display:block;width:100%;text-align:left;margin:8px 0}.anniversary-row small{display:block;font-weight:400;margin-top:4px}.anniversary-badge{display:block;color:#896238;font-size:11px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}
.parttime-add{width:100%;margin:0 0 14px}.event-item.parttime{border-left-color:#317469;background:#f0f6f3}
+55
View File
@@ -0,0 +1,55 @@
'use strict';
const WEB_BUILD = '2026-11-20.10';
let offeredRelease=null, versionChecking=false;
const versionDeferKey='duty-web-update-later';
const versionSeenKey='duty-web-update-seen';
let seenWebVersion='';try{seenWebVersion=localStorage.getItem(versionSeenKey)||'';}catch{}
function showWebUpdate(){
if(!offeredRelease||document.visibilityState!=='visible')return;
const alreadyLoaded=offeredRelease.webVersion===WEB_BUILD;
if(alreadyLoaded&&seenWebVersion===WEB_BUILD)return;
let later;try{later=JSON.parse(localStorage.getItem(versionDeferKey)||'null');}catch{}
if(later?.version===offeredRelease.webVersion&&Date.now()<later.until)return;
// 일정 편집 창과 저장 대기 내용이 있으면 완료할 때까지 기다린다. 작성 중인 값을 새로고침으로 잃지 않게 한다.
if(pending.length||saving||document.querySelector('dialog[open]'))return;
$('update-heading').textContent=alreadyLoaded?'당직근무 업데이트 안내':'새 버전이 준비됐습니다';
$('update-description').textContent=alreadyLoaded?'새 버전 '+offeredRelease.appVersion+'이 적용되었습니다. 변경된 내용을 확인해 주세요.':'새 버전이 준비됐습니다. 업데이트를 누르면 홈페이지를 새로 불러와 적용합니다.';
$('update-apply').textContent=alreadyLoaded?'확인':'업데이트 적용';
$('update-notes').textContent=(offeredRelease.notes||[]).join('\n');
$('update-dialog').showModal();
}
async function checkWebVersion(force=false){
if(versionChecking||document.visibilityState!=='visible')return;
versionChecking=true;
try{
// 개인 일정은 요청하지 않는다. 비로그인 방문자도 공개 버전 정보만 확인한다.
const response=await fetch('api/version',{cache:'no-store'});
if(!response.ok)return;
const release=await response.json();
if(typeof release.webVersion!=='string'||!Array.isArray(release.notes)||release.notes.some(note=>typeof note!=='string'))return;
offeredRelease=release;if(force){try{localStorage.removeItem(versionDeferKey);}catch{}if(release.webVersion===WEB_BUILD&&seenWebVersion===WEB_BUILD)notify('현재 최신 버전입니다.');}showWebUpdate();
if(connected&&release.holidayRevision&&localStorage.getItem('duty-holiday-revision')!==release.holidayRevision){
// 실제 공휴일 내용이 바뀔 때만 전체 자료를 다시 받는다. 개인 일정은 별도 갱신 규칙을 유지한다.
holidayData=await cachedAsset('holidays.json',true,false);if(connected)render();
}
}catch{}finally{versionChecking=false;}
}
function deferWebUpdate(){
if(offeredRelease)try{localStorage.setItem(versionDeferKey,JSON.stringify({version:offeredRelease.webVersion,until:Date.now()+4*60*60*1000}));}catch{}
$('update-dialog').close();
}
$('update-later').onclick=deferWebUpdate;
$('update-dialog').addEventListener('cancel',event=>{event.preventDefault();deferWebUpdate();});
$('update-apply').onclick=()=>{
if(pending.length||saving){notify('저장 중인 내용이 있습니다. 저장을 마친 뒤 다시 시도해 주세요.');return;}
seenWebVersion=offeredRelease.webVersion;
try{localStorage.removeItem(versionDeferKey);localStorage.setItem(versionSeenKey,seenWebVersion);}catch{}
if(offeredRelease.webVersion===WEB_BUILD){$('update-dialog').close();return;}
location.reload();
};
$('web-update-check').onclick=()=>checkWebVersion(true);
document.addEventListener('visibilitychange',()=>{if(document.visibilityState==='visible')checkWebVersion();});
setInterval(()=>checkWebVersion(),5*60*1000);
setInterval(showWebUpdate,15*1000);
checkWebVersion();
+206
View File
@@ -0,0 +1,206 @@
[
{
"id": "duty-rest",
"name": "당직·비번·휴무 (3일)",
"pattern": [
"DUTY",
"OFF",
"REST"
]
},
{
"id": "weekday",
"name": "주간 상근 (주5휴2 예시)",
"pattern": [
"REGULAR",
"REGULAR",
"REGULAR",
"REGULAR",
"REGULAR",
"REST",
"REST"
]
},
{
"id": "two-two",
"name": "2조 2교대 (14일 예시)",
"pattern": [
"DAY",
"DAY",
"DAY",
"DAY",
"DAY",
"REST",
"REST",
"NIGHT",
"NIGHT",
"NIGHT",
"NIGHT",
"NIGHT",
"OFF",
"REST"
]
},
{
"id": "three-two-six",
"name": "3조 2교대 (6일 예시)",
"pattern": [
"DAY",
"DAY",
"NIGHT",
"NIGHT",
"OFF",
"REST"
]
},
{
"id": "three-two-nine",
"name": "3조 2교대 (9일 예시)",
"pattern": [
"DAY",
"DAY",
"DAY",
"NIGHT",
"NIGHT",
"NIGHT",
"OFF",
"REST",
"REST"
]
},
{
"id": "four-two-four",
"name": "4조 2교대 (4일 예시)",
"pattern": [
"DAY",
"NIGHT",
"OFF",
"REST"
]
},
{
"id": "four-two-eight",
"name": "4조 2교대 (8일 예시)",
"pattern": [
"DAY",
"DAY",
"NIGHT",
"NIGHT",
"OFF",
"REST",
"REST",
"REST"
]
},
{
"id": "four-two-sixteen",
"name": "4조 2교대 (16일 예시)",
"pattern": [
"DAY",
"DAY",
"DAY",
"DAY",
"REST",
"REST",
"REST",
"REST",
"NIGHT",
"NIGHT",
"NIGHT",
"NIGHT",
"OFF",
"REST",
"REST",
"REST"
]
},
{
"id": "three-three",
"name": "3조 3교대 (21일 예시)",
"pattern": [
"DAY",
"DAY",
"DAY",
"DAY",
"DAY",
"REST",
"REST",
"EVENING",
"EVENING",
"EVENING",
"EVENING",
"EVENING",
"REST",
"REST",
"NIGHT",
"NIGHT",
"NIGHT",
"NIGHT",
"NIGHT",
"OFF",
"REST"
]
},
{
"id": "four-three-eight",
"name": "4조 3교대 (8일 예시)",
"pattern": [
"DAY",
"DAY",
"EVENING",
"EVENING",
"NIGHT",
"NIGHT",
"OFF",
"REST"
]
},
{
"id": "four-three-sixteen",
"name": "4조 3교대 (16일 예시)",
"pattern": [
"DAY",
"DAY",
"DAY",
"DAY",
"REST",
"EVENING",
"EVENING",
"EVENING",
"EVENING",
"REST",
"NIGHT",
"NIGHT",
"NIGHT",
"NIGHT",
"OFF",
"REST"
]
},
{
"id": "four-three-twenty",
"name": "4조 3교대 (20일 예시)",
"pattern": [
"DAY",
"DAY",
"DAY",
"DAY",
"DAY",
"REST",
"EVENING",
"EVENING",
"EVENING",
"EVENING",
"EVENING",
"REST",
"REST",
"NIGHT",
"NIGHT",
"NIGHT",
"NIGHT",
"NIGHT",
"OFF",
"REST"
]
}
]