feat(performance): 자동 업데이트 일정 설정 — 매출·광고비 따로 간격·요일·시작/끝

- 실적 설정 "자동 업데이트" 카드(관리자): 매출 실적·광고비 각각 사용·요일([매일]·[평일])·
  시작/끝 시각(5분 단위)·간격(5~720분, 5분 단위, 기본 30분), PUT /api/auto-sync-schedule
- 마이그레이션 011 perf_settings(key auto_sync, JSONB). 미적용·값 없음 = 기본 일정(매일 9~19시 30분)
- auto_sync: 종류별 일정·Scheduler(1분마다 다시 읽어 바뀐 종류만 다시 계산, 종류마다 따로 스레드)
- 매출·광고비 탭 카운트다운이 각자 일정대로 다음 회차 계산(nextScheduleSlot)
- 테스트: 일정 계산·검증·Scheduler·저장 API·브라우저(설정 카드·카운트다운)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-26 18:01:00 +09:00
parent 5d30433019
commit 07861dfe8c
18 changed files with 936 additions and 96 deletions
+67 -8
View File
@@ -145,24 +145,32 @@ def dashboard_page(
holidays=_holidays(), configured=creds.configured_codes(list(all_adapters())),
)
ctx["metric"] = metric if metric in ("gross", "commission", "net") else "net"
ctx["auto_sync"] = _auto_sync_ctx()
ctx["auto_sync"] = _auto_sync_ctx(store, "sales")
_unit_ctx(request, ctx)
return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx})
def _auto_sync_ctx() -> dict[str, Any] | None:
"""다음 자동 업데이트까지 남은 시간(2026-10-19) — 화면이 초 단위로 센다. 회차가 지나면 화면이 같은 규칙
(hours·slot, KST)으로 다음 회차를 계산한다. 서버 시각(now)으로 PC 시계 차이를 보정. 자동 업데이트가 꺼져 있으면 None."""
def _auto_sync_ctx(store: Any, kind: str) -> dict[str, Any] | None:
"""다음 자동 업데이트까지 남은 시간(2026-10-19) — 화면이 초 단위로 센다. kind = sales(매출 실적) / ads(광고비),
일정은 실적 설정 "자동 업데이트"(2026-10-26, auto_sync.load_schedules). 회차가 지나면 화면이 같은 규칙
(schedule: 간격·요일·시작/끝, KST)으로 다음 회차를 계산한다. 서버 시각(now)으로 PC 시계 차이를 보정.
자동 업데이트가 꺼져 있거나(env·일정) 회차가 없으면 None."""
from app.timezone import now_kst # noqa: WPS433
from . import auto_sync # noqa: WPS433
if not auto_sync.enabled():
return None
hours = auto_sync.hour_window()
try:
sched = auto_sync.load_schedules(store)[0][kind]
except Exception: # noqa: BLE001 — DB 오류: 카운트다운만 숨김
return None
now = now_kst()
return {"next_at": auto_sync.next_slot(now, hours).isoformat(), "now": now.isoformat(timespec="milliseconds"),
"hours": list(hours), "slot": auto_sync.SLOT_MINUTES}
nxt = auto_sync.next_slot(now, sched)
if nxt is None:
return None
return {"next_at": nxt.isoformat(), "now": now.isoformat(timespec="milliseconds"), "schedule": sched,
"label": auto_sync.describe(sched)}
def _unit_ctx(request: Request, ctx: dict[str, Any]) -> None:
@@ -212,7 +220,7 @@ def ads_page(
ctx["ad_sync_sources"] = [{"code": c, "name": get_source(c).name} for c, ok in configured.items() if ok]
ctx["ad_last_update_at"] = last_ad_update_at(store)
ctx["ad_running"] = jobs.running_job("ads") is not None
ctx["auto_sync"] = _auto_sync_ctx()
ctx["auto_sync"] = _auto_sync_ctx(store, "ads")
return render_template(request, "performance/ads.html",
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
@@ -239,11 +247,62 @@ def settings_page(request: Request):
)
ctx["ad_sources"] = _ad_source_rows(store, ad_sync.configured())
ctx["ad_api_ready"] = store.ad_api_ready()
ctx["auto_sync_settings"] = _auto_sync_settings_ctx(store) # 카드는 관리자에게만(템플릿)
_unit_ctx(request, ctx)
return render_template(request, "performance/settings.html",
{**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx})
def _auto_sync_settings_ctx(store: Any) -> dict[str, Any]:
"""실적 설정 "자동 업데이트" 카드(2026-10-26) — 종류마다 일정·다음 회차, 011 적용 여부, env 로 꺼졌는지."""
from app.timezone import now_kst # noqa: WPS433
from . import auto_sync # noqa: WPS433
try:
schedules, ready = auto_sync.load_schedules(store)
error = ""
except Exception as exc: # noqa: BLE001 — DB 오류여도 설정 화면은 뜬다
schedules, ready, error = auto_sync.normalize(None), True, f"일정을 읽지 못했습니다({type(exc).__name__}) — 기본 일정을 보여 줍니다."
now = now_kst()
kinds = []
for k in auto_sync.KINDS:
nxt = auto_sync.next_slot(now, schedules[k])
kinds.append({"kind": k, "name": auto_sync.KIND_NAMES[k], "schedule": schedules[k],
"label": auto_sync.describe(schedules[k]), "next_at": nxt.isoformat() if nxt else ""})
return {"kinds": kinds, "ready": ready, "env_on": auto_sync.enabled(), "days": auto_sync.sync_days(),
"error": error, "weekdays": auto_sync.WEEKDAYS, "step": auto_sync.INTERVAL_STEP,
"max": auto_sync.INTERVAL_MAX}
@router.put("/api/auto-sync-schedule")
def api_auto_sync_schedule(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""자동 업데이트 일정 저장(2026-10-26, 관리자, 마이그레이션 011) — {sales: 일정, ads: 일정}. 스레드가 1분 안에 반영."""
from app.timezone import now_kst # noqa: WPS433
from . import auto_sync # noqa: WPS433
from .db import SettingsMigrationNeeded # noqa: WPS433
store, user = common.require_store(request, admin=True)
value = {}
for k in auto_sync.KINDS:
try:
value[k] = auto_sync.validate_schedule(payload.get(k))
except ValueError as exc:
raise HTTPException(status_code=400, detail=f"{auto_sync.KIND_NAMES[k]}: {exc}") from None
try:
store.set_setting(auto_sync.SETTING_KEY, value, user=user.get("email", ""))
except SettingsMigrationNeeded:
raise HTTPException(status_code=503, detail="일정을 저장하려면 performance_db 마이그레이션 011"
"(scripts/sql/performance_db_011_settings.sql)을 먼저 적용해야 합니다.") from None
now = now_kst()
out = {}
for k, sched in value.items():
nxt = auto_sync.next_slot(now, sched)
out[k] = {"schedule": sched, "label": auto_sync.describe(sched), "next_at": nxt.isoformat() if nxt else ""}
return JSONResponse({"ok": True, "env_on": auto_sync.enabled(), **out})
def _ad_source_rows(store: Any, configured: dict[str, bool]) -> list[dict[str, Any]]:
"""실적 설정 "광고 API 연동" 표 — 연동마다 설정 여부·연결 상태·마지막 가져오기."""
from .ad_sources.registry import all_sources # noqa: WPS433