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
+132 -12
View File
@@ -1,4 +1,4 @@
"""매출 자동 업데이트 — 회차 시각 계산·건너뛰기."""
"""매출·광고비 자동 업데이트 — 일정(간격·요일·시작/끝)·회차 시각 계산·종류별 실행·건너뛰기."""
from __future__ import annotations
@@ -7,26 +7,122 @@ from datetime import date, datetime, timedelta, timezone
from app.modules.performance import auto_sync as au
KST = timezone(timedelta(hours=9))
H = (9, 19)
D = au.default_schedule() # 매일 09:00 ~ 19:00, 30분마다 (env 없을 때)
def _t(h, m, d=13):
def _t(h, m, d=13): # 2026-10-13 = 화요일
return datetime(2026, 10, d, h, m, tzinfo=KST)
def test_slots_every_half_hour_9_to_19():
slots = [t for t in (_t(0, 0) + timedelta(minutes=30 * i) for i in range(48)) if au.is_slot(t, H)]
def _s(**kw):
return {**D, **kw}
def test_default_schedule_every_half_hour_9_to_19(monkeypatch):
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_HOURS", raising=False)
assert au.default_schedule() == {"enabled": True, "interval": 30, "days": [0, 1, 2, 3, 4, 5, 6],
"start": "09:00", "end": "19:00"}
slots = [t for t in (_t(0, 0) + timedelta(minutes=5 * i) for i in range(288)) if au.is_slot(t, D)]
assert slots[0] == _t(9, 0) and slots[-1] == _t(19, 0) and len(slots) == 21
assert not au.is_slot(_t(19, 30), H) and not au.is_slot(_t(8, 30), H) and not au.is_slot(_t(10, 15), H)
assert not au.is_slot(_t(19, 30), D) and not au.is_slot(_t(8, 30), D) and not au.is_slot(_t(10, 15), D)
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_HOURS", "8-20") # 일정 저장 전 기본 시간대 = env
assert au.default_schedule()["start"] == "08:00" and au.default_schedule()["end"] == "20:00"
def test_next_slot():
assert au.next_slot(_t(8, 10), H) == _t(9, 0)
assert au.next_slot(_t(9, 0), H) == _t(9, 30) # 지금 회차는 이미 지남 → 다음
assert au.next_slot(datetime(2026, 10, 13, 9, 29, 59, tzinfo=KST), H) == _t(9, 30)
assert au.next_slot(_t(18, 45), H) == _t(19, 0)
assert au.next_slot(_t(19, 0), H) == _t(9, 0, d=14) # 저녁 이후 → 다음 날 9시
assert au.next_slot(_t(23, 59), H) == _t(9, 0, d=14)
assert au.next_slot(_t(8, 10), D) == _t(9, 0)
assert au.next_slot(_t(9, 0), D) == _t(9, 30) # 지금 회차는 이미 지남 → 다음
assert au.next_slot(datetime(2026, 10, 13, 9, 29, 59, tzinfo=KST), D) == _t(9, 30)
assert au.next_slot(_t(18, 45), D) == _t(19, 0)
assert au.next_slot(_t(19, 0), D) == _t(9, 0, d=14) # 저녁 이후 → 다음 날 9시
assert au.next_slot(_t(23, 59), D) == _t(9, 0, d=14)
def test_next_slot_custom_interval_window_weekdays():
s = _s(interval=25, start="08:35", end="10:00")
assert au.next_slot(_t(8, 0), s) == _t(8, 35)
assert au.next_slot(_t(8, 35), s) == _t(9, 0)
assert au.next_slot(_t(9, 40), s) == _t(9, 50) # 08:35 · 09:00 · 09:25 · 09:50 (10:15 는 끝 뒤)
assert au.next_slot(_t(9, 50), s) == _t(8, 35, d=14)
assert au.is_slot(_t(9, 25), s) and not au.is_slot(_t(10, 0), s)
assert au.is_slot(_t(10, 0), _s(interval=5, start="08:35", end="10:00")) # 끝 시각과 딱 맞으면 끝도 회차
weekdays = _s(days=[0, 1, 2, 3, 4])
assert au.next_slot(datetime(2026, 10, 16, 19, 0, tzinfo=KST), weekdays) == _t(9, 0, d=19) # 금 저녁 → 월 9시
assert not au.is_slot(datetime(2026, 10, 17, 10, 0, tzinfo=KST), weekdays) # 토요일
once = _s(start="07:05", end="07:05", days=[2]) # 수요일 07:05 한 번
assert au.next_slot(_t(7, 5), once) == datetime(2026, 10, 14, 7, 5, tzinfo=KST)
assert au.next_slot(datetime(2026, 10, 14, 7, 5, tzinfo=KST), once) == datetime(2026, 10, 21, 7, 5, tzinfo=KST)
assert au.next_slot(_t(9, 0), _s(enabled=False)) is None and au.next_slot(_t(9, 0), _s(days=[])) is None
assert au.next_slot(_t(9, 0), _s(interval=720, start="00:00", end="23:55")) == _t(12, 0)
def test_validate_schedule():
ok = au.validate_schedule({"enabled": True, "interval": "45", "days": [4, 0, 0], "start": "7:05", "end": "21:30"})
assert ok == {"enabled": True, "interval": 45, "days": [0, 4], "start": "07:05", "end": "21:30"}
assert au.validate_schedule({**D, "enabled": False, "days": []})["days"] == [] # 끈 일정은 요일 없어도 됨
import pytest
for bad, word in [({**D, "interval": 7}, "5분 단위"), ({**D, "interval": 0}, "간격"), ({**D, "interval": 725}, "간격"),
({**D, "interval": "x"}, "숫자"), ({**D, "days": []}, "요일을 하나"), ({**D, "days": [7]}, "요일"),
({**D, "days": [True]}, "요일"), ({**D, "start": "09:03"}, "5분 단위"), ({**D, "end": "24:00"}, "HH:MM"),
({**D, "start": "19:00", "end": "09:00"}, "끝 시각"), (None, "형식")]:
with pytest.raises(ValueError, match=word):
au.validate_schedule(bad)
def test_normalize_and_load_schedules():
from app.modules.performance.db import SettingsMigrationNeeded
saved = {"sales": _s(interval=10), "ads": {"interval": 3}} # 광고비 값이 깨짐 → 그 종류만 기본
n = au.normalize(saved)
assert n["sales"]["interval"] == 10 and n["ads"] == D
assert au.normalize(None) == {"sales": D, "ads": D}
class Store:
def __init__(self, value=None, missing=False):
self.value, self.missing = value, missing
def get_setting(self, key):
assert key == "auto_sync"
if self.missing:
raise SettingsMigrationNeeded()
return self.value
assert au.load_schedules(Store(saved)) == (n, True)
assert au.load_schedules(Store(missing=True)) == ({"sales": D, "ads": D}, False)
assert au.load_schedules(object()) == ({"sales": D, "ads": D}, True) # get_setting 없는 저장소
def test_describe():
assert au.describe(D) == "매일 09:00~19:00 · 30분마다"
assert au.describe(_s(days=[0, 1, 2, 3, 4], interval=90)) == "평일 09:00~19:00 · 1시간 30분마다"
assert au.describe(_s(days=[5, 6], interval=120)) == "주말 09:00~19:00 · 2시간마다"
assert au.describe(_s(days=[0, 2, 4], start="10:00", end="10:00")) == "월·수·금 10:00"
assert au.describe(_s(enabled=False)) == "꺼짐"
def test_scheduler_runs_each_kind_on_its_own_schedule():
fired = []
sch = au.Scheduler(lambda kind, due: fired.append((kind, due)))
schedules = {"sales": D, "ads": _s(interval=60, days=[0, 1, 2, 3, 4])}
sch.update(schedules, _t(9, 10)) # 시작 시각 회차는 안 돌림 — 다음부터
assert sch.due == {"sales": _t(9, 30), "ads": _t(10, 0)}
assert sch.wait_seconds(_t(9, 10)) == 60.0 and sch.wait_seconds(datetime(2026, 10, 13, 9, 29, 30, tzinfo=KST)) == 30.0
sch.tick(_t(9, 29))
assert fired == []
sch.tick(_t(9, 30))
assert fired == [("sales", _t(9, 30))] and sch.due["sales"] == _t(10, 0)
sch.tick(datetime(2026, 10, 13, 10, 0, 20, tzinfo=KST)) # 둘 다 10:00 → 둘 다(따로)
assert fired[1:] == [("sales", _t(10, 0)), ("ads", _t(10, 0))]
sch.tick(_t(11, 40)) # 밀린 회차(10:30·11:00·11:30)는 한 번만, 다음은 지금 뒤
assert fired[3:] == [("sales", _t(10, 30)), ("ads", _t(11, 0))]
assert sch.due == {"sales": _t(12, 0), "ads": _t(12, 0)}
sch.update(schedules, _t(11, 41)) # 일정 그대로 → due 그대로
assert sch.due["sales"] == _t(12, 0)
sch.update({**schedules, "sales": _s(interval=5)}, _t(11, 41)) # 매출 일정만 바뀜 → 매출만 지금부터 다시
assert sch.due == {"sales": _t(11, 45), "ads": _t(12, 0)}
sch.update({"sales": _s(interval=5), "ads": _s(enabled=False)}, _t(11, 41))
assert sch.due["ads"] is None and sch.due["sales"] == _t(11, 45)
def test_env_parsing(monkeypatch):
@@ -42,6 +138,30 @@ def test_env_parsing(monkeypatch):
assert au.hour_window() == (8, 20)
def test_run_once_only_given_kinds(monkeypatch):
"""종류마다 따로 회차(2026-10-26) — kinds=("ads",) 면 매출은 건드리지 않는다."""
from app.modules.performance import ad_sync, jobs
from app.modules.performance.sync import SyncService
sales = []
monkeypatch.setattr(SyncService, "sync_all", lambda self, **kw: sales.append(1) or [])
monkeypatch.setattr(ad_sync.AdSyncService, "sync_all", lambda self, start, end, *, user="", job=None: [])
monkeypatch.setattr(ad_sync, "ad_credentials", lambda store, ring: None)
monkeypatch.setattr(jobs, "running_job", lambda kind="sales": None)
class Store:
def last_update_at(self):
return None
def ad_source_statuses(self):
return {}
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=3, kinds=("ads",))
assert sales == [] and res["sales_skipped"] and not res["ads_skipped"] and res["from"] == "2026-10-11"
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=3, kinds=("sales",))
assert sales == [1] and res["ads_skipped"] and not res["sales_skipped"]
def test_run_once_uses_job_and_skips_when_busy(monkeypatch):
from app.modules.performance import jobs
from app.modules.performance.sync import SyncService
@@ -0,0 +1,108 @@
"""자동 업데이트 일정 설정(2026-10-26, 마이그레이션 011) — 저장 API(관리자·검증·011 미적용 503), 화면 카운트다운 값(종류별 일정)."""
from __future__ import annotations
import importlib
from datetime import datetime, timedelta, timezone
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import auto_sync, common
from app.modules.performance.db import SettingsMigrationNeeded
perf_router = importlib.import_module("app.modules.performance.router")
KST = timezone(timedelta(hours=9))
D = auto_sync.default_schedule()
class Store:
def __init__(self, value=None, missing=False):
self.value, self.missing, self.saved = value, missing, []
def get_setting(self, key):
if self.missing:
raise SettingsMigrationNeeded()
return self.value
def set_setting(self, key, value, *, user=""):
if self.missing:
raise SettingsMigrationNeeded()
self.saved.append((key, value, user))
self.value = value
@pytest.fixture
def client_store(monkeypatch):
st, calls = Store(), []
def fake_require(request, admin=False):
calls.append(admin)
return st, {"email": "admin@x"}
monkeypatch.setattr(common, "require_store", fake_require)
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False)
monkeypatch.setattr("app.timezone.now_kst", lambda: datetime(2026, 10, 16, 18, 50, tzinfo=KST)) # 금요일
app = FastAPI()
app.include_router(perf_router.router)
return TestClient(app), st, calls
def test_save_schedule(client_store):
c, st, calls = client_store
body = {"sales": {"enabled": True, "interval": 15, "days": [0, 1, 2, 3, 4], "start": "08:30", "end": "20:00"},
"ads": {"enabled": False, "interval": 60, "days": [], "start": "09:00", "end": "18:00"}}
r = c.put("/performance/api/auto-sync-schedule", json=body)
assert r.status_code == 200 and calls == [True] # 관리자만
j = r.json()
assert st.saved == [("auto_sync", body, "admin@x")]
assert j["sales"]["next_at"] == "2026-10-16T19:00:00+09:00" and j["sales"]["label"] == "평일 08:30~20:00 · 15분마다"
assert j["ads"]["next_at"] == "" and j["ads"]["label"] == "꺼짐" and j["env_on"]
def test_save_schedule_rejects_bad_values(client_store):
c, st, _ = client_store
bad = {"sales": {**D, "interval": 12}, "ads": D}
r = c.put("/performance/api/auto-sync-schedule", json=bad)
assert r.status_code == 400 and r.json()["detail"].startswith("매출 실적:") and "5분 단위" in r.json()["detail"]
r = c.put("/performance/api/auto-sync-schedule", json={"sales": D, "ads": {**D, "start": "20:00", "end": "08:00"}})
assert r.status_code == 400 and r.json()["detail"].startswith("광고비:")
assert c.put("/performance/api/auto-sync-schedule", json={"sales": D}).status_code == 400 # 광고비 일정 없음
assert st.saved == []
st.missing = True
r = c.put("/performance/api/auto-sync-schedule", json={"sales": D, "ads": D})
assert r.status_code == 503 and "011" in r.json()["detail"]
def test_countdown_ctx_per_kind(monkeypatch):
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False)
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_HOURS", raising=False)
monkeypatch.setattr("app.timezone.now_kst", lambda: datetime(2026, 10, 16, 18, 50, tzinfo=KST))
st = Store({"sales": {**D, "interval": 5}, "ads": {**D, "days": [0, 1, 2, 3, 4], "start": "10:00"}})
sales = perf_router._auto_sync_ctx(st, "sales")
assert sales["next_at"] == "2026-10-16T18:55:00+09:00" and sales["schedule"]["interval"] == 5
assert sales["label"] == "매일 09:00~19:00 · 5분마다" and sales["now"].startswith("2026-10-16T18:50:00")
assert perf_router._auto_sync_ctx(st, "ads")["next_at"] == "2026-10-16T19:00:00+09:00"
st.value = {"sales": D, "ads": {**D, "days": [0, 1, 2, 3, 4], "start": "10:00", "end": "10:00"}}
assert perf_router._auto_sync_ctx(st, "ads")["next_at"] == "2026-10-19T10:00:00+09:00" # 금 저녁 → 월 10시
st.value = {"sales": {**D, "enabled": False}, "ads": D}
assert perf_router._auto_sync_ctx(st, "sales") is None # 끈 종류는 카운트다운 숨김
st.missing = True
assert perf_router._auto_sync_ctx(st, "sales")["next_at"] == "2026-10-16T19:00:00+09:00" # 011 전 = 기본 일정
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC", "false")
assert perf_router._auto_sync_ctx(st, "sales") is None
def test_settings_card_ctx(monkeypatch):
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False)
ctx = perf_router._auto_sync_settings_ctx(Store(missing=True))
assert not ctx["ready"] and ctx["env_on"] and [k["kind"] for k in ctx["kinds"]] == ["sales", "ads"]
assert ctx["kinds"][0]["schedule"] == D and ctx["step"] == 5
class Broken:
def get_setting(self, key):
raise RuntimeError("db down")
ctx = perf_router._auto_sync_settings_ctx(Broken())
assert ctx["ready"] and "RuntimeError" in ctx["error"] and ctx["kinds"][1]["schedule"] == D