[wip] negodata/backend: 견적 마감 스케줄러
- scheduler/(__init__·jobs): 마감 처리·낙찰자 선정 잡 - quotation_crud·service: 스케줄러 연동 조회/마감 로직 - web_main·requirements·docker-compose·config: 스케줄러 기동 설정 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
ae103fd0f1
commit
5406094ea1
9 files changed
+383
-22
No files matched your search
@@ -0,0 +1,74 @@
|
||||
"""백그라운드 스케줄러(크론) 패키지 — '언제'(when) 담당.
|
||||
|
||||
router/(HTTP 진입점)와 동급의 '시간 진입점' 계층. APScheduler 수명주기와 잡 등록(타이밍)만 책임지고,
|
||||
실제로 하는 일(what)은 scheduler/jobs.py 에 있다.
|
||||
|
||||
- 다중 워커(운영)에서 잡이 워커마다 중복 실행되면 안 되므로 SCHEDULER_ENABLED=1 인 프로세스에서만 등록한다.
|
||||
(개발은 RELOAD=1 단일 워커라 docker-compose 에서 SCHEDULER_ENABLED=1 로 켠다.)
|
||||
- apscheduler import 는 start_scheduler() 안에서 한다 → 미설치(이미지 미재빌드) 상태라도 API 는 부팅된다.
|
||||
|
||||
잡 ① close_expired_quotations : 매일 UTC 00:10(KST 09:10) — 마감시각 지난 견적 마감
|
||||
잡 ② complete_requote_quotations: 1시간마다 — 재견적 중 DONE 세션 있으면 즉시 마감
|
||||
"""
|
||||
import os
|
||||
|
||||
from common.logger import LOG
|
||||
from scheduler import jobs
|
||||
|
||||
__all__ = ["start_scheduler", "shutdown_scheduler"]
|
||||
|
||||
_scheduler = None # AsyncIOScheduler | None
|
||||
|
||||
|
||||
def _is_enabled() -> bool:
|
||||
return os.environ.get("SCHEDULER_ENABLED", "0") == "1"
|
||||
|
||||
|
||||
def start_scheduler():
|
||||
"""lifespan startup 에서 호출. SCHEDULER_ENABLED=1 일 때만 스케줄러를 띄운다."""
|
||||
global _scheduler
|
||||
if not _is_enabled():
|
||||
LOG.i("[scheduler] disabled (SCHEDULER_ENABLED != 1)")
|
||||
return
|
||||
if _scheduler is not None:
|
||||
return
|
||||
|
||||
try:
|
||||
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
from apscheduler.triggers.interval import IntervalTrigger
|
||||
except ImportError:
|
||||
# 의존성 미설치(이미지 미재빌드) → API 는 살리고 스케줄러만 끈다.
|
||||
LOG.e_no_callstack("[scheduler] apscheduler 미설치 → 스케줄러 비활성. requirements 재설치(이미지 재빌드) 필요")
|
||||
return
|
||||
|
||||
_scheduler = AsyncIOScheduler(timezone="UTC")
|
||||
# 잡 ① 마감시간 처리: 매일 UTC 00:10
|
||||
_scheduler.add_job(
|
||||
jobs.close_expired_quotations,
|
||||
CronTrigger(hour=0, minute=10),
|
||||
id="close_expired_quotations",
|
||||
coalesce=True, # 밀린 실행이 여러 번 쌓여도 1번만
|
||||
misfire_grace_time=3600, # 정시보다 늦게 깨어나도 1시간 내면 실행
|
||||
max_instances=1,
|
||||
)
|
||||
# 잡 ② 재견적 협상완료 처리: 1시간마다
|
||||
_scheduler.add_job(
|
||||
jobs.complete_requote_quotations,
|
||||
IntervalTrigger(hours=1),
|
||||
id="complete_requote_quotations",
|
||||
coalesce=True,
|
||||
misfire_grace_time=600,
|
||||
max_instances=1,
|
||||
)
|
||||
_scheduler.start()
|
||||
LOG.i("[scheduler] started (close_expired=daily 00:10 UTC, complete_requote=hourly)")
|
||||
|
||||
|
||||
def shutdown_scheduler():
|
||||
"""lifespan shutdown 에서 호출."""
|
||||
global _scheduler
|
||||
if _scheduler is not None:
|
||||
_scheduler.shutdown(wait=False)
|
||||
_scheduler = None
|
||||
LOG.i("[scheduler] stopped")
|
||||
@@ -0,0 +1,124 @@
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import quotations, sessions
|
||||
from common.enums import DBWRType, ErrorType, QuotationStatus, SessionStatus
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
from crud.quotation_crud import QuotationCRUD
|
||||
|
||||
|
||||
async def close_expired_quotations() -> int:
|
||||
"""[잡①] 마감일이 지난 견적을 자동으로 견적마감 처리한다. 하루 한 번 실행.
|
||||
대상: 마감 시각이 이미 지났는데 아직 마감되지 않은(삭제되지도 않은) 견적.
|
||||
처리: 그 견적들을 견적마감 상태로 바꾸고, 아직 시작 전인 세션은 미참여로 정리한다.
|
||||
반환: 마감 처리한 견적 수."""
|
||||
crud = QuotationCRUD()
|
||||
now = GTime.UTC()
|
||||
err_type, qt_ids = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: crud.list_due_for_close(s, now),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
LOG.e_no_callstack(f"[scheduler] close_expired 대상 조회 실패: {err_type.name}")
|
||||
return 0
|
||||
if not qt_ids:
|
||||
return 0
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[quotations.DBType()],
|
||||
[
|
||||
lambda s: crud.bulk_update_quotation_status(s, qt_ids, QuotationStatus.CLOSED.value),
|
||||
lambda s: crud.bulk_update_sessions_status(
|
||||
s, qt_ids, [SessionStatus.CREATED.value, SessionStatus.IN_PROGRESS.value], SessionStatus.NOT_PARTICIPATED.value
|
||||
),
|
||||
],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
LOG.e_no_callstack(f"[scheduler] close_expired 마감 실패: {err_type.name}")
|
||||
return 0
|
||||
LOG.i(f"[scheduler] close_expired: {len(qt_ids)}건 견적마감")
|
||||
return len(qt_ids)
|
||||
|
||||
|
||||
async def complete_requote_quotations() -> int:
|
||||
"""[잡②] 재견적은 협상완료된 세션이 생기면 나머지를 기다리지 않고 바로 마감한다. 한 시간마다 실행.
|
||||
대상: 아직 마감되지 않은 재견적 견적 중, 협상완료된 세션이 있는 것.
|
||||
낙찰: 협상완료된 세션 중 입찰가가 가장 낮은 공급사를 낙찰자로 정한다. 같은 최저가가 둘 이상이면(동가) 낙찰자를 비우고 동가 정보만 남긴다.
|
||||
(현재 재견적은 견적당 세션이 하나라 실제로는 단독 낙찰만 일어나지만, 모델상 1:N이라 일반 규칙을 그대로 둔다.)
|
||||
처리: 낙찰 정보를 기록하고 견적을 견적마감 상태로 바꾸며, 아직 시작 전인 세션은 미참여로 정리한다.
|
||||
반환: 마감 처리한 견적 수."""
|
||||
crud = QuotationCRUD()
|
||||
err_type, qt_ids = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: crud.list_requote_done(s),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
LOG.e_no_callstack(f"[scheduler] complete_requote 대상 조회 실패: {err_type.name}")
|
||||
return 0
|
||||
if not qt_ids:
|
||||
return 0
|
||||
|
||||
closed = 0
|
||||
for qt_id in qt_ids:
|
||||
e2, done_rows = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s, q=qt_id: crud.list_done_sessions(s, q),
|
||||
)
|
||||
if e2 != ErrorType.SUCCESS:
|
||||
LOG.e_no_callstack(f"[scheduler] complete_requote DONE세션 조회 실패 qt_id={qt_id}: {e2.name}")
|
||||
continue
|
||||
|
||||
# 현재 재견적은 세션이 하나라 사실상 단독 낙찰만 타지만, 모델상 1:N이라 일반 규칙(_pick_winner)을 그대로 쓴다.
|
||||
winner, equal = _pick_winner(done_rows)
|
||||
# 단독 낙찰과 동가는 상호배타(KTC 정본). 플래그를 명시적으로 박는다.
|
||||
data = {
|
||||
"status": QuotationStatus.CLOSED.value,
|
||||
"preferred_sp_yn": winner is not None,
|
||||
"equal_bid_yn": equal is not None,
|
||||
}
|
||||
if winner is not None:
|
||||
data["preferred_sp_id"] = winner["supplier_id"]
|
||||
data["preferred_sp_name"] = (winner["name"] or "")[:20]
|
||||
if equal is not None:
|
||||
data["equal_bid_data"] = equal
|
||||
|
||||
e3 = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[quotations.DBType()],
|
||||
[
|
||||
lambda s, d=data, q=qt_id: crud.update_quotation(s, q, d),
|
||||
lambda s, q=qt_id: crud.update_sessions_status(
|
||||
s, q, [SessionStatus.CREATED.value, SessionStatus.IN_PROGRESS.value], SessionStatus.NOT_PARTICIPATED.value
|
||||
),
|
||||
],
|
||||
)
|
||||
if e3 == ErrorType.SUCCESS:
|
||||
closed += 1
|
||||
else:
|
||||
LOG.e_no_callstack(f"[scheduler] complete_requote 마감 실패 qt_id={qt_id}: {e3.name}")
|
||||
|
||||
if closed:
|
||||
LOG.i(f"[scheduler] complete_requote: {closed}건 견적마감")
|
||||
return closed
|
||||
|
||||
|
||||
def _pick_winner(done_rows):
|
||||
"""협상완료된 세션들 중에서 낙찰자를 정한다(KTC 정본 규칙). complete_requote_quotations 전용 헬퍼.
|
||||
입찰가가 매겨진 세션들 가운데 가장 낮은 가격을 부른 공급사를 낙찰자로 본다.
|
||||
- 최저가를 부른 곳이 한 곳뿐이면: 그 공급사를 낙찰자로 정하고, 동가는 없다.
|
||||
- 최저가가 둘 이상으로 같으면(동가): 낙찰자는 비우고 동가 정보(최저가와 그 공급사들)만 남긴다.
|
||||
- 입찰가가 매겨진 세션이 하나도 없으면: 낙찰자도 동가 정보도 없다.
|
||||
낙찰자와 동가 정보를 한 쌍으로 돌려주며, 둘은 동시에 채워지지 않는다(단독 낙찰 또는 동가, 둘 중 하나)."""
|
||||
cands = [(sid, int(bp), name) for sid, bp, name in done_rows if bp is not None]
|
||||
if not cands:
|
||||
return None, None
|
||||
min_price = min(c[1] for c in cands)
|
||||
tied = [c for c in cands if c[1] == min_price]
|
||||
if len(tied) > 1: # 동가입찰: 최저가가 여럿 → 낙찰 미지정, 동가만 기록
|
||||
equal = {
|
||||
"price": min_price,
|
||||
"suppliers": [{"supplier_id": str(sid), "name": name} for sid, _, name in tied],
|
||||
}
|
||||
return None, equal
|
||||
return {"supplier_id": tied[0][0], "name": tied[0][2]}, None
|
||||
Reference in new issue
Block a user