Merge branch 'feat/perf-auto-sync'
This commit is contained in:
@@ -169,6 +169,10 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
||||
# APP_ENCRYPTION_KEY_V1=
|
||||
# [매출 업데이트] 가 가져오는 기간(오늘 포함 최근 N일, 기본 7, 최대 90)
|
||||
# PERFORMANCE_SYNC_DAYS=7
|
||||
# 매출 자동 업데이트(웹 프로세스 안 스레드) — 기본 켜짐, 매일 09:00~19:00 정각·30분마다 오늘 포함 최근 10일.
|
||||
# PERFORMANCE_AUTO_SYNC=false # 끄기
|
||||
# PERFORMANCE_AUTO_SYNC_DAYS=10 # 가져올 기간(1~90일)
|
||||
# PERFORMANCE_AUTO_SYNC_HOURS=9-19 # 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
|
||||
|
||||
# 자산관리 — 별도 asset_db. 사용자가 서버에서 asset_db_init.sql로 직접 초기화.
|
||||
# 미설정 시 등록/배정은 비활성, HWiNFO XML 분석 미리보기는 사용 가능.
|
||||
|
||||
+5
-1
@@ -117,10 +117,14 @@ def build_google_oauth() -> OAuth:
|
||||
async def _lifespan(app_: FastAPI): # noqa: ANN201
|
||||
"""앱 시작 시 백그라운드 작업 시작.
|
||||
- 프로젝트 업무 마감 알림(매일 1회, 기본 09시 KST) 스레드.
|
||||
PROJECT_REMINDERS=false 면 안 돈다. 상세는 app/modules/project/reminders.py."""
|
||||
PROJECT_REMINDERS=false 면 안 돈다. 상세는 app/modules/project/reminders.py.
|
||||
- 실적 매출 자동 업데이트(09~19시 정각·30분, 최근 10일) 스레드.
|
||||
PERFORMANCE_AUTO_SYNC=false 면 안 돈다. 상세는 app/modules/performance/auto_sync.py."""
|
||||
from .modules.performance.auto_sync import start_auto_sync_thread # noqa: WPS433
|
||||
from .modules.project.reminders import start_reminder_thread # noqa: WPS433
|
||||
|
||||
start_reminder_thread(getattr(app_.state, "project_store", None))
|
||||
start_auto_sync_thread(app_.state)
|
||||
yield
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"""매출 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식).
|
||||
|
||||
기본: 매일 09:00 ~ 19:00(KST) 정각·30분마다, 오늘 포함 최근 10일을 [매출 업데이트] 와 같은 방식으로 다시 가져온다.
|
||||
- 진행 창 작업(jobs)으로 돌린다 — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
|
||||
- 그 시각에 이미 다른 업데이트가 돌고 있으면 그 회차는 건너뛴다(같은 쇼핑몰 동시 실행은 어차피 막혀 있음).
|
||||
- 한 회차가 30분을 넘기면 지나간 회차는 건너뛰고 다음 정각/30분을 기다린다(밀린 회차를 몰아서 돌리지 않음).
|
||||
- 서버를 켠 시각의 회차는 돌리지 않고 다음 회차부터.
|
||||
|
||||
환경변수(.env)
|
||||
PERFORMANCE_AUTO_SYNC=false 끄기(기본 켜짐)
|
||||
PERFORMANCE_AUTO_SYNC_DAYS=10 가져올 기간(오늘 포함 최근 N일, 1~90)
|
||||
PERFORMANCE_AUTO_SYNC_HOURS=9-19 돌리는 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from app.timezone import now_kst
|
||||
|
||||
logger = logging.getLogger("performance.auto_sync")
|
||||
|
||||
AUTO_USER = "자동 업데이트"
|
||||
DEFAULT_DAYS = 10
|
||||
DEFAULT_HOURS = (9, 19)
|
||||
SLOT_MINUTES = 30
|
||||
|
||||
_started = False
|
||||
_start_lock = threading.Lock()
|
||||
|
||||
|
||||
def _env(name: str) -> str:
|
||||
return (os.getenv(name, "") or "").strip()
|
||||
|
||||
|
||||
def enabled() -> bool:
|
||||
return _env("PERFORMANCE_AUTO_SYNC").lower() not in ("0", "false", "no", "off")
|
||||
|
||||
|
||||
def sync_days() -> int:
|
||||
try:
|
||||
return max(1, min(90, int(_env("PERFORMANCE_AUTO_SYNC_DAYS") or DEFAULT_DAYS)))
|
||||
except ValueError:
|
||||
return DEFAULT_DAYS
|
||||
|
||||
|
||||
def hour_window() -> tuple[int, int]:
|
||||
m = re.fullmatch(r"(\d{1,2})\s*-\s*(\d{1,2})", _env("PERFORMANCE_AUTO_SYNC_HOURS"))
|
||||
if not m:
|
||||
return DEFAULT_HOURS
|
||||
first, last = int(m.group(1)), int(m.group(2))
|
||||
if not (0 <= first <= last <= 23):
|
||||
return DEFAULT_HOURS
|
||||
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:
|
||||
return False
|
||||
return first <= t.hour < last or (t.hour == last and t.minute == 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 run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str, Any]:
|
||||
"""한 회차 — 진행 창 작업으로 오늘 포함 최근 days 일 업데이트. 이미 돌고 있으면 건너뜀."""
|
||||
from . import common, jobs # noqa: WPS433
|
||||
from .credentials import CredentialService # noqa: WPS433
|
||||
from .sync import SyncService # noqa: WPS433
|
||||
|
||||
if jobs.running_job() is not None:
|
||||
return {"skipped": True, "reason": "다른 업데이트 진행 중"}
|
||||
start, end = today - timedelta(days=days - 1), today
|
||||
job = jobs.create_job(user=AUTO_USER, start=start, end=end)
|
||||
sync = SyncService(store, CredentialService(store, common.key_ring), app_state=app_state)
|
||||
error = ""
|
||||
results: list[dict[str, Any]] = []
|
||||
try:
|
||||
results = sync.sync_all(start=start, end=end, trigger="schedule", user=AUTO_USER, job=job)
|
||||
except Exception as exc: # noqa: BLE001 — 스레드가 죽지 않게
|
||||
logger.exception("auto sync failed")
|
||||
error = f"업데이트 중 오류: {type(exc).__name__}"
|
||||
last = None
|
||||
try:
|
||||
last = store.last_update_at()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
job.finish(error=error, last_update_at=last)
|
||||
ok = sum(1 for r in results if r.get("ok"))
|
||||
return {"skipped": False, "from": start.isoformat(), "to": end.isoformat(), "ok": ok,
|
||||
"failed": [r.get("code") for r in results if not r.get("ok") and not r.get("skipped")], "error": error}
|
||||
|
||||
|
||||
def start_auto_sync_thread(app_state: Any) -> bool:
|
||||
"""웹 프로세스 시작 시 1번. 저장소가 없거나 꺼져 있거나 이미 돌고 있으면 False."""
|
||||
global _started # noqa: PLW0603
|
||||
store = getattr(app_state, "performance_store", None)
|
||||
if store is None or not enabled():
|
||||
return False
|
||||
with _start_lock:
|
||||
if _started:
|
||||
return False
|
||||
_started = True
|
||||
hours, days = hour_window(), sync_days()
|
||||
|
||||
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"))
|
||||
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)
|
||||
|
||||
threading.Thread(target=_loop, name="performance-auto-sync", daemon=True).start()
|
||||
return True
|
||||
@@ -0,0 +1,67 @@
|
||||
"""매출 자동 업데이트 — 회차 시각 계산·건너뛰기."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from app.modules.performance import auto_sync as au
|
||||
|
||||
KST = timezone(timedelta(hours=9))
|
||||
H = (9, 19)
|
||||
|
||||
|
||||
def _t(h, m, d=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)]
|
||||
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)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def test_env_parsing(monkeypatch):
|
||||
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False)
|
||||
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_DAYS", raising=False)
|
||||
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_HOURS", raising=False)
|
||||
assert au.enabled() and au.sync_days() == 10 and au.hour_window() == (9, 19)
|
||||
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC", "false")
|
||||
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_DAYS", "200")
|
||||
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_HOURS", "20-8") # 잘못된 값 → 기본
|
||||
assert not au.enabled() and au.sync_days() == 90 and au.hour_window() == (9, 19)
|
||||
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_HOURS", "8-20")
|
||||
assert au.hour_window() == (8, 20)
|
||||
|
||||
|
||||
def test_run_once_uses_job_and_skips_when_busy(monkeypatch):
|
||||
from app.modules.performance import jobs
|
||||
from app.modules.performance.sync import SyncService
|
||||
|
||||
calls = []
|
||||
|
||||
def fake_sync_all(self, *, start, end, codes=None, trigger="manual", user="", job=None):
|
||||
calls.append((start, end, trigger, user, job is not None))
|
||||
return [{"code": "naver", "ok": True}, {"code": "toss", "ok": False, "skipped": False}]
|
||||
|
||||
class Store:
|
||||
def last_update_at(self):
|
||||
return "2026-10-13T09:00:05+09:00"
|
||||
|
||||
monkeypatch.setattr(SyncService, "sync_all", fake_sync_all)
|
||||
monkeypatch.setattr(jobs, "running_job", lambda: None)
|
||||
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=10)
|
||||
assert calls == [(date(2026, 10, 4), date(2026, 10, 13), "schedule", au.AUTO_USER, True)]
|
||||
assert res == {"skipped": False, "from": "2026-10-04", "to": "2026-10-13", "ok": 1, "failed": ["toss"], "error": ""}
|
||||
|
||||
monkeypatch.setattr(jobs, "running_job", lambda: object())
|
||||
assert au.run_once(Store(), None, today=date(2026, 10, 13), days=10)["skipped"]
|
||||
assert len(calls) == 1
|
||||
@@ -282,8 +282,15 @@
|
||||
|
||||
## 6. 동기화 (`sync.py`)
|
||||
|
||||
- `SyncService.sync_all()` / `sync_marketplace()` — 버튼·향후 cron/worker 공용. 기본 기간: 오늘 포함 최근
|
||||
- `SyncService.sync_all()` / `sync_marketplace()` — 버튼·자동 업데이트 공용. 기본 기간: 오늘 포함 최근
|
||||
`PERFORMANCE_SYNC_DAYS`(기본 7)일.
|
||||
- **자동 업데이트**(`auto_sync.py`, 2026-10-13): 웹 프로세스 시작 때 데몬 스레드(`main._lifespan`) — 매일 **09:00~19:00(KST)
|
||||
정각·30분마다**(하루 21회) **오늘 포함 최근 10일**을 [매출 업데이트]와 같은 방식(진행 창 작업 `jobs`, `trigger='schedule'`(DB CHECK 허용값),
|
||||
사용자 "자동 업데이트")으로 다시 가져온다. 그 시각에 다른 업데이트가 돌고 있으면 그 회차는 건너뜀, 30분을 넘긴 회차 뒤엔
|
||||
밀린 회차를 몰아서 돌리지 않고 다음 회차부터, 서버 시작 시각 회차는 돌리지 않음. 자동 업데이트 중 누가 버튼을 누르면 그 진행
|
||||
창을 같이 본다(취소는 관리자). 수동 입력 전용 쇼핑몰은 대상 아님. env `PERFORMANCE_AUTO_SYNC`(false=끄기)·
|
||||
`PERFORMANCE_AUTO_SYNC_DAYS`(10)·`PERFORMANCE_AUTO_SYNC_HOURS`(9-19). uvicorn 단일 워커 기준(여러 프로세스면 회차마다 겹쳐
|
||||
돌지만 같은 쇼핑몰 동시 실행은 DB 에서 막힘).
|
||||
- **대시보드 [매출 업데이트]** = 지금 보고 있는 기간(오늘까지)을 `POST /api/sync {from, to}` 로 다시 가져온다
|
||||
("이번달"이면 1일~오늘). 모듈 권한자는 92일까지, 더 긴 기간(올해 등, 최대 366일)은 관리자만.
|
||||
- **과거 매출 가져오기**(설정 화면, 관리자): 같은 API 로 임의 기간(최대 366일). 같은 사건은 덮어써서 여러 번 해도 중복 없음.
|
||||
|
||||
Reference in New Issue
Block a user