[feat] negodata/backend: 견적 자동마감 스케줄러 + 다음 라운드 재생성(자동/수동)
- APScheduler 크론(KST 5분): 마감일 지난 견적 / 모든 세션 종결 견적 → close_and_decide
- 마감 판정: 단독 최저가 낙찰 확정 / 동가·전원미참여 다음 라운드 재생성 / 거부·한도 마감
- 재생성: 같은 견적번호 체인(round+1, 이름 '(N차)'), 공급사 수로 재협상·재견적, 사유별 한도(미참여1+동가1)
- 수동 재생성 POST /regenerate/{qt_id} (마지막 차수만 허용)
- CloseOutcome enum + 잡 결과별 로그
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
d47476dc04
commit
7f948075e5
10 files changed
+641
-189
No files matched your search
@@ -1,17 +1,15 @@
|
||||
"""백그라운드 스케줄러(크론) 패키지 — '언제'(when) 담당.
|
||||
|
||||
router/(HTTP 진입점)와 동급의 '시간 진입점' 계층. APScheduler 수명주기와 잡 등록(타이밍)만 책임지고,
|
||||
실제로 하는 일(what)은 scheduler/jobs.py 에 있다.
|
||||
다중 워커(운영)에서 잡이 워커마다 중복 실행되면 안 되므로 SCHEDULER_ENABLED=1 인 프로세스에서만 등록한다.
|
||||
|
||||
- 다중 워커(운영)에서 잡이 워커마다 중복 실행되면 안 되므로 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 세션 있으면 즉시 마감
|
||||
잡 ① close_expired_quotations : 5분마다(KST) — 마감시각 지난 견적 마감
|
||||
잡 ② close_negotiated_quotations: 5분마다(KST) — 모든 세션 협상 끝난 견적 즉시 마감(타입 무관)
|
||||
"""
|
||||
import os
|
||||
|
||||
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
|
||||
from common.logger import LOG
|
||||
from scheduler import jobs
|
||||
|
||||
@@ -33,36 +31,28 @@ def start_scheduler():
|
||||
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
|
||||
# 한국시간 기준, 두 잡 모두 5분마다 실행.
|
||||
_scheduler = AsyncIOScheduler(timezone="Asia/Seoul")
|
||||
# 잡 ① 마감시각 지난 견적 처리
|
||||
_scheduler.add_job(
|
||||
jobs.close_expired_quotations,
|
||||
CronTrigger(hour=0, minute=10),
|
||||
CronTrigger(minute="*/5"),
|
||||
id="close_expired_quotations",
|
||||
coalesce=True, # 밀린 실행이 여러 번 쌓여도 1번만
|
||||
misfire_grace_time=3600, # 정시보다 늦게 깨어나도 1시간 내면 실행
|
||||
coalesce=True, # 밀린 실행이 쌓여도 1번만
|
||||
misfire_grace_time=600, # 정시보다 늦게 깨어나도 10분 내면 실행
|
||||
max_instances=1,
|
||||
)
|
||||
# 잡 ② 재견적 협상완료 처리: 1시간마다
|
||||
# 잡 ② 모든 세션 협상 끝난 견적 즉시 마감(타입 무관)
|
||||
_scheduler.add_job(
|
||||
jobs.complete_requote_quotations,
|
||||
IntervalTrigger(hours=1),
|
||||
id="complete_requote_quotations",
|
||||
jobs.close_negotiated_quotations,
|
||||
CronTrigger(minute="*/5"),
|
||||
id="close_negotiated_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)")
|
||||
LOG.i("[scheduler] started (KST, both every 5min)")
|
||||
|
||||
|
||||
def shutdown_scheduler():
|
||||
|
||||
@@ -1,17 +1,27 @@
|
||||
"""스케줄 잡 로직(what). '언제 도느냐'(scheduler/__init__.py)와 분리된, 잡이 실제로 하는 일.
|
||||
|
||||
두 잡 모두 '대상 견적을 골라' → 견적마다 QuotationService.close_and_decide 를 호출한다.
|
||||
마감 + 결과 판정(낙찰 확정 / 다음 라운드 재생성 / 그냥 마감)은 전부 도메인(close_and_decide)이 책임지고,
|
||||
여기 잡은 '어떤 견적을 고르냐(대상 선정)'와 '언제 도느냐'만 담당한다.
|
||||
"""
|
||||
from collections import Counter
|
||||
|
||||
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.database.model.models import quotations
|
||||
from common.enums import CloseOutcome, DBWRType, ErrorType
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
from crud.quotation_crud import QuotationCRUD
|
||||
from services.quotation_service import QuotationService
|
||||
|
||||
|
||||
async def close_expired_quotations() -> int:
|
||||
"""[잡①] 마감일이 지난 견적을 자동으로 견적마감 처리한다. 하루 한 번 실행.
|
||||
"""[잡①] 마감일이 지난 견적을 자동 마감 처리한다. 하루 한 번 실행.
|
||||
대상: 마감 시각이 이미 지났는데 아직 마감되지 않은(삭제되지도 않은) 견적.
|
||||
처리: 그 견적들을 견적마감 상태로 바꾸고, 아직 시작 전인 세션은 미참여로 정리한다.
|
||||
반환: 마감 처리한 견적 수."""
|
||||
처리: 견적마다 close_and_decide 로 결과 판정(낙찰 확정 / 다음 라운드 재생성 / 그냥 마감).
|
||||
반환: 처리한 견적 수."""
|
||||
crud = QuotationCRUD()
|
||||
service = QuotationService(crud)
|
||||
now = GTime.UTC()
|
||||
err_type, qt_ids = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
@@ -21,104 +31,34 @@ async def close_expired_quotations() -> int:
|
||||
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)
|
||||
results = Counter()
|
||||
for qt_id in qt_ids:
|
||||
results[await service.close_and_decide(qt_id)] += 1
|
||||
if results:
|
||||
LOG.i(f"[scheduler] close_expired: 낙찰 {results[CloseOutcome.AWARDED]} / 재생성 {results[CloseOutcome.REGENERATED]} / 마감 {results[CloseOutcome.CLOSED]}")
|
||||
return sum(results.values())
|
||||
|
||||
|
||||
async def complete_requote_quotations() -> int:
|
||||
"""[잡②] 재견적은 협상완료된 세션이 생기면 나머지를 기다리지 않고 바로 마감한다. 한 시간마다 실행.
|
||||
대상: 아직 마감되지 않은 재견적 견적 중, 협상완료된 세션이 있는 것.
|
||||
낙찰: 협상완료된 세션 중 입찰가가 가장 낮은 공급사를 낙찰자로 정한다. 같은 최저가가 둘 이상이면(동가) 낙찰자를 비우고 동가 정보만 남긴다.
|
||||
(현재 재견적은 견적당 세션이 하나라 실제로는 단독 낙찰만 일어나지만, 모델상 1:N이라 일반 규칙을 그대로 둔다.)
|
||||
처리: 낙찰 정보를 기록하고 견적을 견적마감 상태로 바꾸며, 아직 시작 전인 세션은 미참여로 정리한다.
|
||||
반환: 마감 처리한 견적 수."""
|
||||
async def close_negotiated_quotations() -> int:
|
||||
"""[잡②] 모든 세션의 협상이 끝난 견적은 마감일을 기다리지 않고 바로 마감한다(견적 타입 무관).
|
||||
대상: 아직 마감되지 않았고, 진행중·미시작 세션이 하나도 없는(= 모두 종결된) 견적. 한 시간마다 실행.
|
||||
처리: 견적마다 close_and_decide 로 결과 판정(낙찰 확정 / 다음 라운드 재생성 / 그냥 마감).
|
||||
반환: 처리한 견적 수."""
|
||||
crud = QuotationCRUD()
|
||||
service = QuotationService(crud)
|
||||
err_type, qt_ids = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: crud.list_requote_done(s),
|
||||
lambda s: crud.list_all_sessions_ended(s),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
LOG.e_no_callstack(f"[scheduler] complete_requote 대상 조회 실패: {err_type.name}")
|
||||
return 0
|
||||
if not qt_ids:
|
||||
LOG.e_no_callstack(f"[scheduler] close_negotiated 대상 조회 실패: {err_type.name}")
|
||||
return 0
|
||||
|
||||
closed = 0
|
||||
results = Counter()
|
||||
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
|
||||
results[await service.close_and_decide(qt_id)] += 1
|
||||
if results:
|
||||
LOG.i(f"[scheduler] close_negotiated: 낙찰 {results[CloseOutcome.AWARDED]} / 재생성 {results[CloseOutcome.REGENERATED]} / 마감 {results[CloseOutcome.CLOSED]}")
|
||||
return sum(results.values())
|
||||
Reference in new issue
Block a user