[fix] 견적 자동마감 동시성·정합성 + 프론트 안정화 (코드리뷰 후속)
백엔드 close_and_decide 경로: - 동시 이중 마감 가드: 마감 판정 전 원자적 CLOSED 선점(claim)으로 두 크론 잡·수동마감 경합 직렬화 - 재생성 실패 표면화: regenerate_next_round 결과 검사 → 실패 시 REGEN_FAILED 반환(체인 끊김 은폐 방지) - 차수 충돌 방지: 다음 라운드 = 체인 최신 round+1(chain_max_round 기준) - 재생성 사유 집계 정밀화: 미참여/동가를 양성 표식으로 구분(단독낙찰·거부 오집계 제거) - 재생성 라운드 최소 협상기간 하한(즉시 재마감 캐스케이드 방지) - 잡 루프 per-item 예외 격리(한 건 실패가 배치 전체를 멈추지 않음) 프론트: - useChatController: 무권한 가드를 sessionId 별로 추적해 세션 변경 시 자연 해제 - useScrollLock: 마지막 해제를 rAF 로 지연해 재마운트 사이 일시적 잠금 해제 방지 - quotation 상세 쿼리 placeholderData 로 라운드 전환 중 시트 유지 테스트: - 신규 test_close_and_decide_fixes.py(동시성·차수·집계·기간 하한 검증) - conftest 결함 수정(존재하지 않는 tbl_account TRUNCATE 제거, companies.status 명시) - stale 테스트 갱신(test_quotation_create 를 타입드 Req/신규 응답 형식에 맞게 재작성) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
b4dc862912
commit
7e0f88ca03
12 files changed
+397
-44
No files matched your search
@@ -1,6 +1,6 @@
|
||||
import re
|
||||
import uuid
|
||||
from datetime import timezone
|
||||
from datetime import timezone, timedelta
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
@@ -8,6 +8,7 @@ from fastapi import Depends
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import quotations, sessions, chats, versions, version_nego_cards, version_wild_cards
|
||||
from common.enums import CloseOutcome, DBWRType, ErrorType, QuotationStatus, QuotationType, SessionStatus
|
||||
from common.logger import LOG
|
||||
from common.models.gmodel import PageParams
|
||||
from common.utils.gtime import GTime
|
||||
from config.server_configs import web_server_config
|
||||
@@ -43,6 +44,12 @@ class QuotationService:
|
||||
# 재생성 한도: 한 체인(같은 견적번호)에서 사유(미참여/동가)별 최대 1번까지 재생성(순서 무관, 같은 사유 2번 불가).
|
||||
MAX_REGEN_PER_CAUSE = 1
|
||||
|
||||
# 재생성 라운드의 최소 협상기간(방어적 하한). 원본 협상기간이 비정상적으로 짧으면(또는 0/음수면)
|
||||
# 새 라운드가 생성 즉시 만료돼 다음 크론 tick(*/5분)에 또 마감되는 연쇄를 막는다.
|
||||
# 정상 견적(수 시간~수일)은 원본 기간을 그대로 쓰며, 이 하한은 비정상적으로 짧은 경우에만 적용된다.
|
||||
# TODO 하한값 변경 해야함 !!! feat. MarineYang
|
||||
MIN_REGEN_DURATION = timedelta(hours=1)
|
||||
|
||||
def __init__(self, quotation_crud: IQuotationCRUD = Depends(QuotationCRUD)):
|
||||
self.quotation_crud = quotation_crud
|
||||
|
||||
@@ -190,9 +197,18 @@ class QuotationService:
|
||||
|
||||
# 3) 다음 라운드의 견적 생성
|
||||
now = GTime.UTC()
|
||||
duration = original.end_time - original.start_time
|
||||
# 진입 경로(크론 마감 / 수동 regenerate_quotation) 모두 '마지막 차수'만 넘기므로 +1 이 곧 체인 다음 차수.
|
||||
next_round = original.round + 1
|
||||
# 원본 협상기간을 이어쓰되, 비정상적으로 짧으면 최소 하한을 적용(즉시 만료→연쇄 재마감 방지).
|
||||
duration = max(original.end_time - original.start_time, self.MIN_REGEN_DURATION)
|
||||
# 다음 차수는 '원본 round+1' 이 아니라 '체인(같은 번호) 최신 round+1'.
|
||||
# 크론 마감과 수동 regenerate_quotation 이 같은 체인을 처리하는 타이밍이 엇갈려도
|
||||
# 항상 체인 끝에 이어붙어 uq_quotations_number(number, round) 충돌을 막는다.
|
||||
_e, chain_max = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.quotation_crud.chain_max_round(s, original.number),
|
||||
)
|
||||
base_round = chain_max if (_e == ErrorType.SUCCESS and chain_max) else original.round
|
||||
next_round = base_round + 1
|
||||
# 이름에 '(N차)' 표기. 원래 이름 기준(기존 '(M차)' 표기는 떼고 새로) + name 컬럼 50자 제한 보호.
|
||||
suffix = f" ({next_round}차)"
|
||||
base_name = re.sub(r"\s*\(\d+차\)\s*$", "", original.name or "")[: 50 - len(suffix)]
|
||||
@@ -372,6 +388,26 @@ class QuotationService:
|
||||
],
|
||||
)
|
||||
|
||||
async def _close_as_no_show(self, qt_uuid) -> None:
|
||||
"""전원 미참여로 '다음 라운드 재생성' 하며 마감 + 미완료 세션 미참여.
|
||||
재생성 사유(미참여)를 체인에 남기기 위해 preferred_sp_yn=False, equal_bid_yn=False 로 양성 표식한다
|
||||
(단독낙찰=preferred_sp_yn True / 동가=equal_bid_yn True / 거부·한도 등 그냥 마감=둘 다 NULL 과 구분).
|
||||
_chain_regen_counts 가 이 표식으로 '미참여 재생성 이력'만 정확히 센다."""
|
||||
data = {
|
||||
"status": QuotationStatus.CLOSED.value,
|
||||
"preferred_sp_yn": False,
|
||||
"equal_bid_yn": False,
|
||||
}
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[quotations.DBType()],
|
||||
[
|
||||
lambda s: self.quotation_crud.update_quotation(s, qt_uuid, data),
|
||||
lambda s: self.quotation_crud.update_sessions_status(
|
||||
s, qt_uuid, [SessionStatus.CREATED.value, SessionStatus.IN_PROGRESS.value], SessionStatus.NOT_PARTICIPATED.value
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
async def _close_as_equal(self, qt_uuid, equal) -> None:
|
||||
"""동가로 마감 + 미완료 세션 미참여. equal_bid_yn/data 를 기록해 둔다
|
||||
(재생성 한도 계산이 이 플래그로 동가 라운드를 식별하고, 프론트도 동가 정보를 그대로 쓴다)."""
|
||||
@@ -407,6 +443,17 @@ class QuotationService:
|
||||
if err_type != ErrorType.SUCCESS or original is None:
|
||||
return CloseOutcome.CLOSED
|
||||
|
||||
# [동시 마감 가드] 마감 판정 전에 원자적으로 status→CLOSED 를 선점한다.
|
||||
# 두 크론 잡(close_expired / close_negotiated)이나 수동 stop_quotation 이 같은 견적을
|
||||
# 동시에 닫으려 해도, 실제로 CLOSED 로 전이한 호출자만 통과하고 진 호출자는 여기서 끝난다
|
||||
# → 이중 재생성·uq(number,round) 충돌 방지. (이미 닫힌 견적의 재처리도 여기서 차단)
|
||||
claim_err, claimed = await DB_SESSION_MNG.execute_lambda_claim(
|
||||
quotations.DBType(),
|
||||
lambda s: self.quotation_crud.claim_for_close(s, qt_uuid),
|
||||
)
|
||||
if claim_err != ErrorType.SUCCESS or claimed == 0:
|
||||
return CloseOutcome.CLOSED
|
||||
|
||||
err_type, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
@@ -430,7 +477,14 @@ class QuotationService:
|
||||
if equal is not None and equal_used < self.MAX_REGEN_PER_CAUSE:
|
||||
tied_ids = [uuid.UUID(sp["supplier_id"]) for sp in equal["suppliers"]]
|
||||
await self._close_as_equal(qt_uuid, equal) # 동가 기록(equal_bid_yn) 후 마감
|
||||
await self.regenerate_next_round(qt_uuid, tied_ids)
|
||||
regen = await self.regenerate_next_round(qt_uuid, tied_ids)
|
||||
if not regen.result.success:
|
||||
# 원본은 이미 CLOSED 인데 다음 라운드 생성이 실패 → 체인이 끊긴 상태. 성공으로 위장하지 않고 드러낸다.
|
||||
LOG.e_no_callstack(
|
||||
f"[close] 동가 재생성 실패 qt={qt_uuid} number={original.number} round={original.round} "
|
||||
f"code={regen.result.code}({regen.result.desc})"
|
||||
)
|
||||
return CloseOutcome.REGEN_FAILED
|
||||
return CloseOutcome.REGENERATED
|
||||
# 3) 협상거부 있음 → 마감만 (재생성 안 함)
|
||||
if has_rejected:
|
||||
@@ -439,26 +493,36 @@ class QuotationService:
|
||||
# 4) 전원 미참여 → 공급사 전체로 다음 라운드 (체인에 미참여 재생성 이력 없을 때만)
|
||||
if not done and rows and no_part_used < self.MAX_REGEN_PER_CAUSE:
|
||||
supplier_ids = list({r.supplier_id for r in rows})
|
||||
await self._just_close(qt_uuid)
|
||||
await self.regenerate_next_round(qt_uuid, supplier_ids)
|
||||
await self._close_as_no_show(qt_uuid) # 미참여 재생성 표식(preferred_sp_yn=False, equal_bid_yn=False) 후 마감
|
||||
regen = await self.regenerate_next_round(qt_uuid, supplier_ids)
|
||||
if not regen.result.success:
|
||||
# 원본은 이미 CLOSED 인데 다음 라운드 생성이 실패 → 체인이 끊긴 상태. 성공으로 위장하지 않고 드러낸다.
|
||||
LOG.e_no_callstack(
|
||||
f"[close] 미참여 재생성 실패 qt={qt_uuid} number={original.number} round={original.round} "
|
||||
f"code={regen.result.code}({regen.result.desc})"
|
||||
)
|
||||
return CloseOutcome.REGEN_FAILED
|
||||
return CloseOutcome.REGENERATED
|
||||
# 5) 그 외 / 한도 도달 → 마감만
|
||||
await self._just_close(qt_uuid)
|
||||
return CloseOutcome.CLOSED
|
||||
|
||||
async def _chain_regen_counts(self, number: str, current_round: int) -> tuple[int, int]:
|
||||
"""체인(같은 견적번호) 이전 라운드들의 재생성 사유 횟수. 반환: (미참여 횟수, 동가 횟수).
|
||||
동가로 닫힌 라운드는 equal_bid_yn=True 로 기록되므로 그 플래그로 센다.
|
||||
(이전 라운드는 동가 아니면 미참여 둘뿐 — 단독낙찰·거부는 체인을 끝냄 → equal_bid_yn 이 True 아니면 미참여)."""
|
||||
"""체인(같은 견적번호) 이전 라운드들의 '재생성 사유' 횟수. 반환: (미참여 횟수, 동가 횟수).
|
||||
마감 시 남긴 양성 표식으로만 센다(오집계 방지):
|
||||
- 동가 재생성 → equal_bid_yn=True
|
||||
- 미참여 재생성 → preferred_sp_yn=False AND equal_bid_yn=False
|
||||
단독낙찰(preferred_sp_yn=True)·거부/한도 그냥 마감(둘 다 NULL)은 어느 쪽에도 세지 않는다.
|
||||
(수동 regenerate_quotation 으로 단독낙찰·거부 라운드를 이어붙여도 자동 재생성 한도에 영향 없음.)"""
|
||||
err_type, flags = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.quotation_crud.list_chain_equal_flags(s, number, current_round),
|
||||
lambda s: self.quotation_crud.list_chain_close_flags(s, number, current_round),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return 0, 0
|
||||
equal = sum(1 for f in flags if f is True)
|
||||
no_part = len(flags) - equal
|
||||
equal = sum(1 for _pref, eq in flags if eq is True)
|
||||
no_part = sum(1 for pref, eq in flags if pref is False and eq is False)
|
||||
return no_part, equal
|
||||
|
||||
async def regenerate_quotation(self, qt_id: str, supplier_ids: list) -> Res_CreateQuotation:
|
||||
|
||||
Reference in new issue
Block a user