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
+9 -5
View File
@@ -31,7 +31,11 @@
- 진행 창에서 쇼핑몰별 [중지](그 쇼핑몰만 멈추고 다음 쇼핑몰로).
- **업데이트 중에도 [매출 업데이트] 누르기 가능**(2026-10-19) — 버튼이 "업데이트 중 · 진행 보기"로 바뀌고, 누르면 `GET /api/sync/current` 의 진행 중 작업(수동·자동)을 새로 시작하지 않고 진행 창으로 다시 연다.
- 서버 시작 때 남은 `perf_sync_runs` running 행은 `abandon_running_runs` 로 "중단됨(서버 재시작)" 정리(앱은 프로세스 하나 — 진행 작업은 메모리에만). 예전엔 30분(`STALE_RUN_AFTER`) 동안 버튼이 '업데이트 중'으로 막히고 그 쇼핑몰이 '이미 진행 중'으로 건너뛰어졌다.
- **자동 업데이트**(`auto_sync.py`, 웹 프로세스 데몬 스레드) — 매일 09~19시 정각·30분마다 오늘 포함 최근 10일, 진행 창 작업으로 돌고 다른 업데이트 중이면 그 회차 건너뜀. env `PERFORMANCE_AUTO_SYNC`·`_DAYS`·`_HOURS`.
- **자동 업데이트**(`auto_sync.py`, 웹 프로세스 데몬 스레드) — 오늘 포함 최근 10일, 진행 창 작업으로 돌고 다른 업데이트 중이면 그 회차 건너뜀. env `PERFORMANCE_AUTO_SYNC`(끄기)·`_DAYS`·`_HOURS`(일정 저장 전 기본 시간대).
- **일정 = 실적 설정 "자동 업데이트" 카드**(2026-10-26, 관리자, 마이그레이션 011 `perf_settings` key `auto_sync`) — 매출 실적·광고비 **따로**:
사용·요일(0=월…6=일, [매일]·[평일])·시작/끝 시각(5분 단위)·간격(5~720분, 5분 단위, 기본 30). 회차 = 고른 요일의 시작, 시작+간격, … 끝까지(끝과 맞으면 끝도).
`PUT /api/auto-sync-schedule {sales, ads}`(`auto_sync.validate_schedule`, 011 미적용 503). 스레드(`auto_sync.Scheduler`)가 1분마다 일정을 다시 읽어
바뀐 종류만 지금부터 다시 계산, 종류마다 따로 스레드(`run_once(kinds=(kind,))`). 저장 값 없음·011 미적용 = 기본(매일 9~19시 30분마다).
- 쿠팡은 판매자배송 발주서 + 로켓그로스 주문을 결제일로 합산(WING 판매분석 대조는 원본 데이터 확인으로).
## 수동 입력
@@ -69,7 +73,7 @@
- KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 %, 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다.
- 일자별 표 기본 보기 = **수수료 차감 매출**(라우터 기본 `metric=net`, 예전에 고른 보기 localStorage 는 안 씀).
- 마지막 업데이트 옆 **다음 업데이트까지 남은 시간** 초 단위 실시간(`router._auto_sync_ctx` → `performance.js initNextUpdate`, 자동 업데이트 규칙 `auto_sync.next_slot` 과 같게 화면이 다음 회차 계산, 서버 시각으로 PC 시계 보정, 자동 업데이트 꺼지면 숨김).
- 마지막 업데이트 옆 **다음 업데이트까지 남은 시간** 초 단위 실시간(`router._auto_sync_ctx(store, kind)` — 매출 탭 = 매출 일정, 광고비 탭 = 광고비 일정 → `performance.js initNextUpdate`·`nextScheduleSlot`, `auto_sync.next_slot` 과 같은 규칙으로 화면이 다음 회차 계산, 서버 시각으로 PC 시계 보정, 자동 업데이트(env·그 종류 일정) 꺼지면 숨김).
- 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타 두 줄(이름 붙임), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = **일 합계 금액 ÷ 일 합계 광고비**(2026-10-19 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다; `roas` 총매출·`roas_net` 수수료 차감 매출 기준, 보기 기준에 따라 하나만). 광고비 표 없으면 줄 없음.
- **매출 단위** 원·천원·백만원 — 설정 "보기 설정"(누구나, 이 브라우저 쿠키 `perf_unit`), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로.
@@ -99,12 +103,12 @@
총비용·광고수익률은 **머리글 이름으로 찾음**(열 구성 바뀐 보고서 — 고정 12열이 비어 ROAS 누락됐던 문제, 2026-10-20). 광고수익률 칸이 없거나 비면 구매완료 전환매출액 ÷ 총비용. 저장된 `roas` 가 빈 예전 행은 `db.ad_roas` 가 metrics 에서 다시 구함(`ad_spend.roas_from_metrics`).
- 일자별 보고서 창: ROAS 열은 **광고비 열 바로 오른쪽**, 네이버 "구매완료 광고수익률(%)" 머리글은 "ROAS(%)"로 표기(`ad_spend._roas_next_to_spend` → `labels`, 저장 키는 파일 머리글 그대로 — 예전 업로드도 그대로 적용).
- 매출 대비 광고비 KPI.
- 광고 API 연동(마이그레이션 007 `perf_ad_credentials`·`perf_ad_source_status`) — 실적 설정 **광고 API 연동** 카드, 쇼핑몰과 같은 마스터 키로 암호화(AAD `perf:ad:…`), `ad_sources/`(채널 하나 = 파일 하나) + `ad_sync.py`, 매출 자동 업데이트 회차에 함께.
- 광고 API 연동(마이그레이션 007 `perf_ad_credentials`·`perf_ad_source_status`) — 실적 설정 **광고 API 연동** 카드, 쇼핑몰과 같은 마스터 키로 암호화(AAD `perf:ad:…`), `ad_sources/`(채널 하나 = 파일 하나) + `ad_sync.py`, 광고비 자동 업데이트 일정(실적 설정 "자동 업데이트")대로.
- **[광고비 업데이트]**(2026-10-20, 예전 채널별 [구글/메타 광고 불러오기] 버튼 삭제) — 광고비 탭 오른쪽 위, 매출 탭과 같은 모양:
마지막 업데이트(광고 API 마지막 성공 가져오기 `ad_sync.last_ad_update_at`) · 다음 업데이트까지(매출과 같은 회차 카운트다운) · 버튼.
마지막 업데이트(광고 API 마지막 성공 가져오기 `ad_sync.last_ad_update_at`) · 다음 업데이트까지(광고비 일정 카운트다운) · 버튼.
설정된 광고 API 전부를 진행 창 작업으로(`POST /api/ad-sync` → `jobs` kind="ads", 채널별 막대 수집 50% → 저장 → 완료, 채널별 [중지]·[업데이트 취소]는
저장 직전까지, 진행·취소·중지 API 는 매출과 같은 `/api/sync/jobs/…`). 진행 중이면 새로 시작 안 하고 합류(`GET /api/ad-sync/current`, 매출 업데이트와 별개).
자동 업데이트 회차(`auto_sync.run_once`)는 매출과 광고비를 **동시에** 각각 진행 창 작업으로, 이미 돌고 있는 종류만 그 회차 건너뜀. 결과는 `perf_ad_spend` `source='api'`(초록 숫자, API 가 안 준 날은 예전 API 값만 지움).
자동 업데이트(`auto_sync.run_once`)는 매출·광고비를 각자 일정대로 각각 진행 창 작업으로(같은 시각이면 동시에), 이미 돌고 있는 종류는 그 회차 건너뜀. 결과는 `perf_ad_spend` `source='api'`(초록 숫자, API 가 안 준 날은 예전 API 값만 지움).
- **구글 = Google Ads API**(2026-10-15) — 고객 ID·(MCC)·서비스 계정 JSON·API 버전(기본 v26). 개발자 토큰은 2026-09-09 구글 폐지 — 접근 등급은 서비스 계정의 Cloud 프로젝트, 머리글 안 보냄. [광고비 업데이트]·자동 업데이트. 광고비 = 비용 × 1.1(부가세 포함)·ROAS(전환 가치 ÷ 비용, 구글 값 그대로)·항목.
- **메타 = 메타 마케팅 API**(2026-10-16, `ad_sources/meta_ads.py`, 새 마이그레이션 없음) — 광고 계정 ID(여러 개, 날짜별 합산)·액세스 토큰(ads_read, 시스템 사용자 토큰 권장)·앱 시크릿(선택)·API 버전(기본 v26.0). 광고비 = 지출 금액 그대로(메타는 이미 부가세 포함 — × 1.1 은 구글만)·ROAS = 구매 전환값 ÷ 지출 금액(광고 관리자 구매 ROAS). USD 등 외화 계정은 그날 환율로 원화 환산(`fx.py`, Frankfurter 중앙은행 고시 환율 종합, 키 없음). 상세보기 [합계 | 계정별] 탭, [광고비 업데이트]·자동 업데이트 회차.
**기간으로 물으면 메타가 지출·노출·클릭을 0 으로 주는 문제**(2026-10-21 운영 확인, v26.0 — 링크 클릭·구매는 정상, 하루만 물으면 정상) →
+196 -42
View File
@@ -1,17 +1,20 @@
"""매출 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식).
"""매출·광고비 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식).
기본: 매일 09:00 ~ 19:00(KST) 정각·30분마다, 오늘 포함 최근 10일을 [매출 업데이트] 와 같은 방식으로 다시 가져온다.
- 같은 회차에 광고비(설정된 광고 API — 구글·메타)도 같은 기간으로 **동시에** 가져온다(2026-10-20, 광고비 진행 창 작업
jobs kind="ads", 실패해도 매출과 무관). 광고비 탭 [광고비 업데이트]를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
- 진행 창 작업(jobs)으로 돌린다 — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
- 그 시각에 이미 같은 종류 업데이트가 돌고 있으면 그 종류는 그 회차를 건너뛴다(같은 쇼핑몰 동시 실행은 어차피 막혀 있음).
- 한 회차가 30분을 넘기면 지나간 회차는 건너뛰고 다음 정각/30분을 기다린다(밀린 회차를 몰아서 돌리지 않음).
일정(2026-10-26) — 실적 설정 "자동 업데이트" 카드에서 매출 실적·광고비를 **따로** 정한다(마이그레이션 011 perf_settings,
key 'auto_sync'). 종류마다 {enabled, interval(분, 5분 단위, 기본 30), days(0=월 … 6=일), start "HH:MM", end "HH:MM"}.
- 회차 = 고른 요일의 start, start+interval, … end 까지(end 와 딱 맞으면 end 도). 시각은 5분 단위, KST.
- 저장한 일정은 1분 안에 반영(스레드가 1분마다 다시 읽는다). 저장 값이 없으면(011 미적용 포함) 기본 일정 =
매일 env PERFORMANCE_AUTO_SYNC_HOURS(기본 9-19)시 정각 ~ 마지막 시 정각, 30분마다.
- 매출 = 진행 창 작업(jobs kind="sales") — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
- 광고비 = 설정된 광고 API(구글·메타) — 광고비 진행 창 작업(jobs kind="ads"). 광고비 탭 [광고비 업데이트]도 같은 진행 상황.
- 두 종류의 회차가 같은 시각이면 동시에 돈다(따로 스레드). 그 시각에 이미 같은 종류 업데이트가 돌고 있으면 그 종류는 그 회차를
건너뛴다. 한 회차가 간격을 넘기면 지나간 회차는 건너뛰고 다음 회차를 기다린다(밀린 회차를 몰아서 돌리지 않음).
- 서버를 켠 시각의 회차는 돌리지 않고 다음 회차부터.
환경변수(.env)
PERFORMANCE_AUTO_SYNC=false 끄기(기본 켜짐)
PERFORMANCE_AUTO_SYNC=false 끄기(기본 켜짐) — 끄면 설정 화면 일정과 상관없이 안 돈다
PERFORMANCE_AUTO_SYNC_DAYS=10 가져올 기간(오늘 포함 최근 N일, 1~90)
PERFORMANCE_AUTO_SYNC_HOURS=9-19 돌리는 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
PERFORMANCE_AUTO_SYNC_HOURS=9-19 설정 화면에서 일정을 저장하기 전 기본 시간대(시작시-마지막시)
"""
from __future__ import annotations
@@ -31,7 +34,13 @@ logger = logging.getLogger("performance.auto_sync")
AUTO_USER = "자동 업데이트"
DEFAULT_DAYS = 10
DEFAULT_HOURS = (9, 19)
SLOT_MINUTES = 30
DEFAULT_INTERVAL = 30
INTERVAL_STEP = 5
INTERVAL_MAX = 720
SETTING_KEY = "auto_sync"
KINDS = ("sales", "ads")
KIND_NAMES = {"sales": "매출 실적", "ads": "광고비"}
WEEKDAYS = ("월", "화", "수", "목", "금", "토", "일")
_started = False
_start_lock = threading.Lock()
@@ -62,27 +71,127 @@ def hour_window() -> tuple[int, int]:
return first, last
def is_slot(t: datetime, hours: tuple[int, int]) -> bool:
"""t(분 단위로 자른 시각)가 회차인가 — 정각·30분, first시 정각 ~ last시 정각."""
first, last = hours
if t.minute % SLOT_MINUTES:
# ════════════════════════════════════════════════════════════
# 일정
# ════════════════════════════════════════════════════════════
def default_schedule() -> dict[str, Any]:
first, last = hour_window()
return {"enabled": True, "interval": DEFAULT_INTERVAL, "days": list(range(7)),
"start": f"{first:02d}:00", "end": f"{last:02d}:00"}
def _minutes(hhmm: str) -> int:
h, m = hhmm.split(":")
return int(h) * 60 + int(m)
def _time(raw: Any, label: str) -> str:
m = re.fullmatch(r"(\d{1,2}):(\d{2})", str(raw or "").strip())
if not m or not (0 <= int(m.group(1)) <= 23 and 0 <= int(m.group(2)) <= 59):
raise ValueError(f"{label}을 HH:MM 으로 넣어 주세요.")
if int(m.group(2)) % INTERVAL_STEP:
raise ValueError(f"{label}은 {INTERVAL_STEP}분 단위로 정할 수 있습니다.")
return f"{int(m.group(1)):02d}:{m.group(2)}"
def validate_schedule(raw: Any) -> dict[str, Any]:
"""설정 화면에서 받은 일정 하나 → 정리한 값. 잘못되면 ValueError(화면에 그대로 보여 줄 문구)."""
if not isinstance(raw, dict):
raise ValueError("일정 형식이 잘못되었습니다.")
on = bool(raw.get("enabled"))
try:
interval = int(raw.get("interval"))
except (TypeError, ValueError):
raise ValueError("간격(분)을 숫자로 넣어 주세요.") from None
if not (INTERVAL_STEP <= interval <= INTERVAL_MAX) or interval % INTERVAL_STEP:
raise ValueError(f"간격은 {INTERVAL_STEP}분 ~ {INTERVAL_MAX}분, {INTERVAL_STEP}분 단위로 정할 수 있습니다.")
days = raw.get("days")
if not isinstance(days, list) or any(not isinstance(d, int) or isinstance(d, bool) or not 0 <= d <= 6 for d in days):
raise ValueError("요일이 잘못되었습니다.")
days = sorted(set(days))
if on and not days:
raise ValueError("요일을 하나 이상 고르세요(자동 업데이트를 쓰지 않으려면 [사용]을 끄세요).")
start, end = _time(raw.get("start"), "시작 시각"), _time(raw.get("end"), "끝 시각")
if _minutes(end) < _minutes(start):
raise ValueError("끝 시각은 시작 시각과 같거나 뒤여야 합니다(밤을 넘기는 시간대는 안 됩니다).")
return {"enabled": on, "interval": interval, "days": days, "start": start, "end": end}
def normalize(raw: Any) -> dict[str, dict[str, Any]]:
"""DB 에 저장된 값 → 종류마다 일정. 없거나 잘못된 종류는 기본 일정."""
out = {}
for k in KINDS:
try:
out[k] = validate_schedule((raw or {}).get(k)) if isinstance(raw, dict) else default_schedule()
except ValueError:
out[k] = default_schedule()
return out
def load_schedules(store: Any) -> tuple[dict[str, dict[str, Any]], bool]:
"""(종류 → 일정, 011 적용 여부). DB 오류는 그대로 올린다(스레드는 직전 일정을 계속 쓴다)."""
from .db import SettingsMigrationNeeded # noqa: WPS433
getter = getattr(store, "get_setting", None)
if getter is None: # 테스트용 가짜 저장소 등
return normalize(None), True
try:
return normalize(getter(SETTING_KEY)), True
except SettingsMigrationNeeded:
return normalize(None), False
def describe(sched: dict[str, Any]) -> str:
"""'매일 09:00~19:00 · 30분마다' / '평일 …' / '월·수·금 …' / '꺼짐'."""
if not sched.get("enabled") or not sched.get("days"):
return "꺼짐"
days = sched["days"]
if days == list(range(7)):
when = "매일"
elif days == list(range(5)):
when = "평일"
elif days == [5, 6]:
when = "주말"
else:
when = "·".join(WEEKDAYS[d] for d in days)
span = sched["start"] if sched["start"] == sched["end"] else f"{sched['start']}~{sched['end']}"
every = sched["interval"]
every_txt = f"{every // 60}시간" + (f" {every % 60}분" if every % 60 else "") if every >= 60 else f"{every}분"
return f"{when} {span}" + ("" if sched["start"] == sched["end"] else f" · {every_txt}마다")
def is_slot(t: datetime, sched: dict[str, Any]) -> bool:
"""t(분 단위로 자른 KST 시각)가 회차인가."""
if not sched.get("enabled") or t.weekday() not in sched["days"]:
return False
return first <= t.hour < last or (t.hour == last and t.minute == 0)
m, start, end = t.hour * 60 + t.minute, _minutes(sched["start"]), _minutes(sched["end"])
return start <= m <= end and (m - start) % sched["interval"] == 0
def next_slot(after: datetime, hours: tuple[int, int]) -> datetime:
"""after 보다 뒤의 첫 회차 시각."""
t = after.replace(second=0, microsecond=0)
t += timedelta(minutes=SLOT_MINUTES - t.minute % SLOT_MINUTES)
for _ in range(48 * 2 + 2): # 하루치 회차를 넘기기 전에 반드시 찾는다
if is_slot(t, hours):
return t
t += timedelta(minutes=SLOT_MINUTES)
raise ValueError("회차를 찾을 수 없습니다")
def next_slot(after: datetime, sched: dict[str, Any]) -> datetime | None:
"""after 보다 뒤의 첫 회차 시각(KST). 꺼져 있거나 요일이 없으면 None."""
if not sched.get("enabled") or not sched.get("days"):
return None
start, end, step = _minutes(sched["start"]), _minutes(sched["end"]), sched["interval"]
day0 = after.replace(hour=0, minute=0, second=0, microsecond=0)
for d in range(8):
base = day0 + timedelta(days=d)
if base.weekday() not in sched["days"]:
continue
first = base + timedelta(minutes=start)
k = 0 if first > after else int((after - first).total_seconds() // (step * 60)) + 1
m = start + k * step
if m <= end:
return base + timedelta(minutes=m)
return None
def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str, Any]:
"""한 회차 — 오늘 포함 최근 days 일. 매출(진행 창 작업)과 광고비(광고 진행 창 작업)를 동시에.
# ════════════════════════════════════════════════════════════
# 회차 실행
# ════════════════════════════════════════════════════════════
def run_once(store: Any, app_state: Any, *, today: Any, days: int,
kinds: tuple[str, ...] = KINDS) -> dict[str, Any]:
"""한 회차 — 오늘 포함 최근 days 일. kinds 의 매출(진행 창 작업)·광고비(광고 진행 창 작업)를 동시에.
각각 이미 돌고 있으면 그 종류만 건너뜀."""
from . import common, jobs # noqa: WPS433
from .ad_sync import run_ad_job # noqa: WPS433
@@ -92,7 +201,7 @@ def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str,
start, end = today - timedelta(days=days - 1), today
ads: list[dict[str, Any]] = []
ad_thread = None
ads_skipped = jobs.running_job("ads") is not None
ads_skipped = "ads" not in kinds or jobs.running_job("ads") is not None
if not ads_skipped:
ad_job = jobs.create_job(user=AUTO_USER, start=start, end=end, kind="ads")
@@ -102,7 +211,7 @@ def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str,
ad_thread = threading.Thread(target=_ads, name=f"perf-auto-ads-{ad_job.id}", daemon=True)
ad_thread.start()
sales_skipped = jobs.running_job("sales") is not None
sales_skipped = "sales" not in kinds or jobs.running_job("sales") is not None
error = ""
results: list[dict[str, Any]] = []
if not sales_skipped:
@@ -130,6 +239,36 @@ def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str,
"ads": [{"code": a.get("code"), "ok": bool(a.get("ok"))} for a in ads]}
class Scheduler:
"""종류마다 다음 회차(due)를 들고 있다가 시각이 되면 그 종류만 따로 스레드로 돌린다.
tick(now) 이 1분마다 불리며 일정이 바뀐 종류는 지금부터 다시 계산(서버 시작·저장 직후 회차는 안 돌림)."""
def __init__(self, fire: Any):
self.fire = fire # fire(kind, due)
self.schedules: dict[str, dict[str, Any]] = {}
self.due: dict[str, datetime | None] = {}
def update(self, schedules: dict[str, dict[str, Any]], now: datetime) -> None:
for k in KINDS:
s = schedules.get(k) or default_schedule()
if self.schedules.get(k) != s:
self.schedules[k] = s
self.due[k] = next_slot(now, s)
def tick(self, now: datetime) -> None:
for k in KINDS:
due = self.due.get(k)
if due is not None and due <= now:
self.fire(k, due)
self.due[k] = next_slot(max(now, due), self.schedules[k])
def wait_seconds(self, now: datetime) -> float:
dues = [d for d in self.due.values() if d is not None]
if not dues:
return 60.0
return max(0.0, min(60.0, min((d - now).total_seconds() for d in dues)))
def start_auto_sync_thread(app_state: Any) -> bool:
"""웹 프로세스 시작 시 1번. 저장소가 없거나 꺼져 있거나 이미 돌고 있으면 False."""
global _started # noqa: PLW0603
@@ -147,23 +286,38 @@ def start_auto_sync_thread(app_state: Any) -> bool:
if _started:
return False
_started = True
hours, days = hour_window(), sync_days()
days = sync_days()
def _fire(kind: str, due: datetime) -> None:
def _run() -> None:
try:
res = run_once(store, app_state, today=due.date(), days=days, kinds=(kind,))
logger.info("%s 자동 업데이트 %s: %s", KIND_NAMES[kind], due.strftime("%H:%M"), res)
except Exception: # noqa: BLE001
logger.exception("%s 자동 업데이트 실패 — 다음 회차에 다시", KIND_NAMES[kind])
threading.Thread(target=_run, name=f"performance-auto-{kind}", daemon=True).start()
sched = Scheduler(_fire)
def _reload(now: datetime) -> None:
try:
schedules, _ = load_schedules(store)
except Exception: # noqa: BLE001 — DB 가 잠시 끊기면 직전 일정 그대로(처음이면 기본 일정)
logger.warning("자동 업데이트 일정 읽기 실패 — 직전 일정 사용", exc_info=True)
schedules = sched.schedules or normalize(None)
sched.update(schedules, now)
def _loop() -> None:
due = next_slot(now_kst(), hours)
logger.info("매출 자동 업데이트 시작 — %02d~%02d시 30분마다, 최근 %d일, 다음 %s", hours[0], hours[1], days,
due.strftime("%m-%d %H:%M"))
_reload(now_kst())
logger.info("실적 자동 업데이트 시작 — 최근 %d일, %s", days, ", ".join(
f"{KIND_NAMES[k]} {describe(sched.schedules[k])} 다음 "
f"{sched.due[k].strftime('%m-%d %H:%M') if sched.due[k] else '없음'}" for k in KINDS))
while True:
wait = (due - now_kst()).total_seconds()
if wait > 0:
time.sleep(min(wait, 60)) # 시계 변경·절전에도 1분 안에 다시 확인
continue
try:
res = run_once(store, app_state, today=due.date(), days=days)
logger.info("매출 자동 업데이트 %s: %s", due.strftime("%H:%M"), res)
except Exception: # noqa: BLE001
logger.exception("매출 자동 업데이트 실패 — 다음 회차에 다시")
due = next_slot(max(now_kst(), due), hours)
time.sleep(max(1.0, sched.wait_seconds(now_kst()))) # 시계 변경·절전·일정 저장에도 1분 안에 다시 확인
now = now_kst()
_reload(now)
sched.tick(now)
threading.Thread(target=_loop, name="performance-auto-sync", daemon=True).start()
return True
+26
View File
@@ -30,6 +30,10 @@ class MemoMigrationNeeded(Exception):
"""날짜 칸 메모(마이그레이션 010: perf_cell_memos)가 아직 적용되지 않음."""
class SettingsMigrationNeeded(Exception):
"""설정 값 저장(마이그레이션 011: perf_settings — 자동 업데이트 일정)이 아직 적용되지 않음."""
class ManualMigrationNeeded(Exception):
"""수동 입력(마이그레이션 002: perf_marketplaces.manual_input · perf_manual_sales)이 아직 적용되지 않음."""
@@ -513,6 +517,28 @@ class PerformanceDBStore:
except pg_errors.UndefinedTable:
raise MemoMigrationNeeded() from None
# ════════════════════════════════════════════════════════════
# 설정 값(마이그레이션 011) — 키 하나 = JSONB. 'auto_sync' = 자동 업데이트 일정(auto_sync.py)
# ════════════════════════════════════════════════════════════
def get_setting(self, key: str) -> Any:
"""값(없으면 None). 011 미적용이면 SettingsMigrationNeeded."""
try:
with self._pool.connection() as conn:
row = conn.execute("SELECT value FROM perf_settings WHERE key = %s", (key,)).fetchone()
except pg_errors.UndefinedTable:
raise SettingsMigrationNeeded() from None
return row["value"] if row else None
def set_setting(self, key: str, value: Any, *, user: str = "") -> None:
try:
with self._pool.connection() as conn:
conn.execute(
"INSERT INTO perf_settings (key, value, updated_by) VALUES (%s, %s, %s) "
"ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_by = EXCLUDED.updated_by, "
"updated_at = now()", (key, Jsonb(value), user))
except pg_errors.UndefinedTable:
raise SettingsMigrationNeeded() from None
# ════════════════════════════════════════════════════════════
# 광고비(마이그레이션 005)
# ════════════════════════════════════════════════════════════
+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
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261027a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261027b" />{% endblock %}
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
@@ -38,14 +38,14 @@
<button class="erp-btn erp-btn-outline" type="submit">조회</button>
</form>
{# 광고비 업데이트(2026-10-20) — 매출 탭과 같은 모양: 마지막 업데이트(광고 API 마지막 성공) · 다음 자동 업데이트(매출과 같은 회차)
{# 광고비 업데이트(2026-10-20) — 매출 탭과 같은 모양: 마지막 업데이트(광고 API 마지막 성공) · 다음 자동 업데이트(실적 설정의 광고비 일정)
· [광고비 업데이트](설정된 광고 API 전부, 진행 창). 업데이트 중에도 누르면 진행 창을 다시 연다. #}
{% if ad_sync_sources %}
<div class="perf-update">
<span class="perf-muted" id="perf-last-update" title="광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }}) 마지막 업데이트">마지막 업데이트
<b>{{ (ad_last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
{% if auto_sync %}
<span class="perf-muted perf-next-update" id="perf-next-update" title="자동 업데이트: 매일 {{ auto_sync.hours[0] }}~{{ auto_sync.hours[1] }}시 {{ auto_sync.slot }}분마다(매출과 같은 시각)">다음 업데이트까지 <b>—</b></span>
<span class="perf-muted perf-next-update" id="perf-next-update" title="광고비 자동 업데이트: {{ auto_sync.label }} (실적 설정에서 바꿈)">다음 업데이트까지 <b>—</b></span>
{% endif %}
<button type="button" class="erp-btn erp-btn-primary{% if ad_running %} is-running{% endif %}" id="perf-ad-sync-btn"
title="{% if ad_running %}업데이트 진행 상황 보기{% else %}지금 보고 있는 기간({{ period.label }}, 오늘까지)의 광고비·ROAS 를 광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }})에서 다시 가져옵니다{% endif %}">
@@ -241,4 +241,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261027a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261027b" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261027a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261027b" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
@@ -82,7 +82,7 @@
<b>{{ (last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
{% if auto_sync %}
{# 다음 자동 업데이트까지 남은 시간 — 초 단위로 실시간(performance.js initNextUpdate, 2026-10-19) #}
<span class="perf-muted perf-next-update" id="perf-next-update" title="자동 업데이트: 매일 {{ auto_sync.hours[0] }}~{{ auto_sync.hours[1] }}시 {{ auto_sync.slot }}분마다">다음 업데이트까지 <b>—</b></span>
<span class="perf-muted perf-next-update" id="perf-next-update" title="매출 자동 업데이트: {{ auto_sync.label }} (실적 설정에서 바꿈)">다음 업데이트까지 <b>—</b></span>
{% endif %}
{# 업데이트 중에도 누를 수 있다 — 진행 중인 업데이트(수동·자동)의 진행 창을 다시 연다(2026-10-19) #}
<button type="button" class="erp-btn erp-btn-primary{% if running %} is-running{% endif %}" id="perf-sync-btn"
@@ -292,4 +292,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261027a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261027b" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261027a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261027b" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -161,6 +161,63 @@
</div>
</div>
{% if is_admin and auto_sync_settings %}
{# 자동 업데이트 일정(2026-10-26, 마이그레이션 011 perf_settings) — 매출 실적·광고비 따로: 사용·요일·시작/끝 시각(5분 단위)·간격(5분 단위,
기본 30분). [저장] = PUT /api/auto-sync-schedule, 스레드(auto_sync.py)가 1분 안에 반영. #}
{% set au = auto_sync_settings %}
{% macro time_select(part, value, label) -%}
{%- set hh, mm = value.split(':') -%}
<select class="erp-input perf-auto-time" data-t="{{ part }}-h" aria-label="{{ label }} 시">
{%- for h in range(24) %}<option value="{{ '%02d' % h }}"{% if '%02d' % h == hh %} selected{% endif %}>{{ '%02d' % h }}시</option>{% endfor -%}
</select><select class="erp-input perf-auto-time" data-t="{{ part }}-m" aria-label="{{ label }} 분">
{%- for m in range(0, 60, au.step) %}<option value="{{ '%02d' % m }}"{% if '%02d' % m == mm %} selected{% endif %}>{{ '%02d' % m }}분</option>{% endfor -%}
</select>
{%- endmacro %}
<div class="erp-card perf-card" id="perf-auto-sync">
<div class="perf-card-head">
<h2 class="perf-h">자동 업데이트</h2>
<span class="perf-muted">매출 실적·광고비를 고른 요일의 시작 ~ 끝 시각 사이에 정한 간격으로 자동으로 가져옵니다(오늘 포함 최근 {{ au.days }}일).
시각·간격은 {{ au.step }}분 단위이며, 저장하면 1분 안에 적용됩니다.</span>
</div>
{% if not au.env_on %}<div class="perf-notice is-warn">서버 환경변수 PERFORMANCE_AUTO_SYNC=false 로 자동 업데이트가 꺼져 있습니다 — 일정은 저장되지만 돌지 않습니다.</div>{% endif %}
{% if not au.ready %}<div class="perf-notice is-warn">일정 저장 표가 아직 없습니다. performance_db 마이그레이션 011
(scripts/sql/performance_db_011_settings.sql)을 적용해야 저장할 수 있습니다. 지금은 기본 일정(아래)으로 돕니다.</div>{% endif %}
{% if au.error %}<div class="perf-notice is-warn">{{ au.error }}</div>{% endif %}
<div class="perf-auto-rows">
{% for k in au.kinds %}{% set sc = k.schedule %}
<div class="perf-auto-row{% if not sc.enabled %} is-off{% endif %}" data-kind="{{ k.kind }}">
<div class="perf-auto-name">
<b>{{ k.name }}</b>
<label class="perf-auto-on"><input type="checkbox" data-f="enabled"{% if sc.enabled %} checked{% endif %} /> 사용</label>
</div>
<div class="perf-auto-fields">
<div class="perf-auto-field"><span class="perf-opt-label">요일</span>
<span class="perf-auto-days">
{%- for w in au.weekdays %}<label class="perf-day{% if loop.index0 == 5 %} is-sat{% elif loop.index0 == 6 %} is-sun{% endif %}"><input type="checkbox" data-day="{{ loop.index0 }}"{% if loop.index0 in sc.days %} checked{% endif %} /><span>{{ w }}</span></label>{% endfor -%}
</span>
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-days="all">매일</button>
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-days="weekday">평일</button>
</div>
<div class="perf-auto-field"><span class="perf-opt-label">시간</span>
{{ time_select('start', sc.start, k.name ~ ' 시작') }}<span class="perf-muted">부터</span>
{{ time_select('end', sc.end, k.name ~ ' 끝') }}<span class="perf-muted">까지</span>
</div>
<div class="perf-auto-field"><span class="perf-opt-label">간격</span>
<input class="erp-input perf-auto-interval" type="number" min="{{ au.step }}" max="{{ au.max }}" step="{{ au.step }}"
data-f="interval" value="{{ sc.interval }}" aria-label="{{ k.name }} 간격(분)" /><span class="perf-muted">분마다</span>
</div>
</div>
<div class="perf-muted perf-auto-next" data-next>{{ k.label }}{% if k.next_at %} · 다음 {{ k.next_at[5:16] | replace('T', ' ') }}{% endif %}</div>
</div>
{% endfor %}
</div>
<div class="perf-auto-actions">
<button type="button" class="erp-btn erp-btn-primary" id="perf-auto-save">저장</button>
<span class="perf-muted" id="perf-auto-msg" role="status"></span>
</div>
</div>
{% endif %}
{% if is_admin %}
{# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고·메타 광고(2026-10-16). 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장.
가져온 광고비·ROAS 는 광고비 탭(초록 숫자). [설정]·[연결 테스트]는 쇼핑몰 표와 같은 창(/api/ad-sources/…). #}
@@ -168,7 +225,7 @@
<div class="perf-card-head">
<h2 class="perf-h">광고 API 연동</h2>
<span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
설정이 끝나면 광고비 탭 [구글 광고 불러오기]·[메타 광고 불러오기]와 매출 자동 업데이트(30분마다 최근 며칠) 때 함께 가져옵니다.</span>
설정이 끝나면 광고비 탭 [광고비 업데이트]와 광고비 자동 업데이트(위 "자동 업데이트" 일정) 때 가져옵니다.</span>
</div>
{% if not ad_api_ready %}
<div class="perf-notice is-warn">광고 API 인증정보 저장 표가 아직 없습니다. performance_db 마이그레이션 007
@@ -259,4 +316,4 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261027a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261027b" defer></script>{% endblock %}
+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