[feat] negodata: 결렬 폐지→개찰 마감 개편 + 낙찰기준 견적 단위 이관 + 세팅 컬럼 정리 (백엔드+DB)
Co-Authored-By: Claude Opus 4.8뀨 <noreply@anthropic.com>
This commit is contained in:
1 parent
1a7674b1e3
commit
38709b3098
14 files changed
+314
-415
No files matched your search
@@ -1,17 +1,15 @@
|
||||
"""close_and_decide 동시성·정합성 수정 검증 (코드리뷰 후속).
|
||||
"""close_and_decide 마감 판정 검증 — 낙찰(AWARDED) 또는 개찰(OPEN_*, 낙찰자 미정 마감).
|
||||
|
||||
검증 대상:
|
||||
- #2 동시 이중 마감 가드: 같은 견적을 동시에 close_and_decide 해도 다음 라운드는 1개만 생성
|
||||
- #3 차수 매김: 다음 라운드 round = 체인 최신 round + 1
|
||||
- #4 재생성 사유 집계: 단독낙찰(preferred_sp_yn=True) 이전 라운드를 '미참여'로 오집계하지 않음
|
||||
- #6 재생성 라운드 최소 협상기간 하한(즉시 재마감 캐스케이드 방지)
|
||||
- 동시 이중 마감 가드: 같은 견적을 동시에 close_and_decide 해도 실제 마감 전이는 1번만
|
||||
- 낙찰 기준 게이트: 단독 최저가가 기준 통과면 낙찰, 미달이면 개찰(가격)
|
||||
- 동가 / 협상거부 / 전원 미응찰 → 각각 개찰(OPEN_EQUAL / OPEN_REJECT / OPEN_NOSHOW)
|
||||
|
||||
용어: 체인 = 같은 견적번호(number)로 이어지는 라운드들 / 미참여 = 공급사가 협상에 안 들어온 채 마감됨 /
|
||||
재생성 = 결판 안 난 견적의 '다음 라운드'를 자동 생성 / 재생성 한도 = 사유(미참여·동가)별로 체인당 1번까지만.
|
||||
용어: 개찰 = 낙찰자 미정으로 마감(결렬 아님). 자동 재협상/재생성 없음 — 다음 라운드는 담당자가 수동 재생성.
|
||||
"""
|
||||
import asyncio
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime
|
||||
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import text
|
||||
@@ -30,149 +28,125 @@ async def clean(db_engine):
|
||||
return db_engine
|
||||
|
||||
|
||||
async def test_concurrent_close_creates_only_one_next_round(clean):
|
||||
"""검증: 같은 견적(전원 미참여)을 5번 동시에 close_and_decide.
|
||||
기대결과: 재생성은 1번만(REGENERATED=1), 체인은 [1,2] — 이중 재생성/충돌 없음."""
|
||||
async def test_concurrent_close_single_transition(clean):
|
||||
"""검증: 전원 미응찰 견적을 5번 동시에 close_and_decide.
|
||||
기대결과: 실제 마감 전이(OPENED)는 1번만·나머지는 no-op(CLOSED), 체인 [1](자동 재생성 없음), close_reason=OPEN_NOSHOW."""
|
||||
engine = clean
|
||||
number = "C-CONCURRENT"
|
||||
qt = await _seed_quotation(engine, number=number, round_=1, status=QuotationStatus.IN_PROGRESS.value)
|
||||
# 전원 미참여(미시작 세션만) → close_and_decide 가 '다음 라운드 재생성' 경로를 탄다
|
||||
# 전원 미응찰(미시작 세션만) → 개찰(미응찰) 경로
|
||||
await _add_session(engine, qt, status=SessionStatus.CREATED.value)
|
||||
await _add_session(engine, qt, status=SessionStatus.CREATED.value)
|
||||
|
||||
service = QuotationService(QuotationCRUD())
|
||||
outcomes = await asyncio.gather(*[service.close_and_decide(qt) for _ in range(5)])
|
||||
|
||||
regenerated = sum(1 for o in outcomes if o == CloseOutcome.REGENERATED)
|
||||
opened = sum(1 for o in outcomes if o == CloseOutcome.OPENED)
|
||||
rounds = await _rounds(engine, number)
|
||||
round_numbers = [r.round for r in rounds]
|
||||
|
||||
assert regenerated == 1, f"재생성은 1번만 일어나야 함, 실제 {regenerated} ({outcomes})"
|
||||
assert round_numbers == [1, 2], f"체인은 [1,2] 여야 함(중복/충돌 없음), 실제 {round_numbers}"
|
||||
assert opened == 1, f"실제 마감 전이는 1번만이어야 함, 실제 {opened} ({outcomes})"
|
||||
assert [r.round for r in rounds] == [1], "자동 재생성 없음 — round 2 가 생기면 안 됨"
|
||||
assert rounds[0].close_reason == CloseReason.OPEN_NOSHOW.value
|
||||
|
||||
|
||||
async def test_next_round_numbering_and_min_duration(clean):
|
||||
"""검증: 협상기간이 0인 견적을 미참여로 재생성.
|
||||
기대결과: 체인 [1,2](round=최신+1), 새 라운드 협상기간 ≥ MIN_REGEN_DURATION(즉시 재마감 방지)."""
|
||||
async def test_single_lowest_meets_target_awarded(clean):
|
||||
"""검증: 단독 최저가(bid=100)가 목표가(200) 이내 · 목표까지 낙찰(mid=AWARD).
|
||||
기대결과: AWARDED — 그 협력사로 낙찰(preferred_sp_yn=True), close_reason=AWARDED."""
|
||||
engine = clean
|
||||
number = "C-DURATION"
|
||||
# start==end (협상기간 0) → 하한이 적용되지 않으면 새 라운드도 0 길이가 된다
|
||||
qt = await _seed_quotation(
|
||||
engine, number=number, round_=1, status=QuotationStatus.IN_PROGRESS.value,
|
||||
start_time=PAST, end_time=PAST,
|
||||
)
|
||||
await _add_session(engine, qt, status=SessionStatus.CREATED.value)
|
||||
|
||||
service = QuotationService(QuotationCRUD())
|
||||
outcome = await service.close_and_decide(qt)
|
||||
|
||||
assert outcome == CloseOutcome.REGENERATED
|
||||
rounds = await _rounds(engine, number)
|
||||
assert [r.round for r in rounds] == [1, 2]
|
||||
nxt = rounds[1]
|
||||
duration = nxt.end_time - nxt.start_time
|
||||
assert duration >= QuotationService.MIN_REGEN_DURATION, (
|
||||
f"재생성 라운드 협상기간({duration})이 최소 하한({QuotationService.MIN_REGEN_DURATION}) 이상이어야 함"
|
||||
)
|
||||
|
||||
|
||||
async def test_awarded_prior_round_not_counted_as_no_show(clean):
|
||||
"""검증: round1=단독낙찰 + round2=전원 미참여 인 체인에서 round2 를 마감.
|
||||
기대결과: REGENERATED, 체인 [1,2,3] — 단독낙찰 라운드를 '미참여'로 오집계해 재생성을 막지 않는다."""
|
||||
engine = clean
|
||||
number = "C-AWARDED-PRIOR"
|
||||
# round 1: 단독낙찰로 마감(close_reason=AWARDED). 수동 재생성 등으로 체인이 이어진 상황을 가정.
|
||||
await _seed_quotation(
|
||||
engine, number=number, round_=1, status=QuotationStatus.CLOSED.value,
|
||||
preferred_sp_yn=True, equal_bid_yn=False, close_reason=CloseReason.AWARDED.value,
|
||||
)
|
||||
# round 2: 전원 미참여 → 미참여 재생성이 일어나야 한다(round 1 은 미참여로 세면 안 됨)
|
||||
qt2 = await _seed_quotation(engine, number=number, round_=2, status=QuotationStatus.IN_PROGRESS.value)
|
||||
await _add_session(engine, qt2, status=SessionStatus.CREATED.value)
|
||||
|
||||
service = QuotationService(QuotationCRUD())
|
||||
outcome = await service.close_and_decide(qt2)
|
||||
|
||||
rounds = await _rounds(engine, number)
|
||||
round_numbers = [r.round for r in rounds]
|
||||
assert outcome == CloseOutcome.REGENERATED, (
|
||||
f"단독낙찰 이전 라운드는 미참여 예산을 소진하지 않아 round2 가 재생성돼야 함, 실제 {outcome}"
|
||||
)
|
||||
assert round_numbers == [1, 2, 3], f"round 3 이 생성돼야 함, 실제 {round_numbers}"
|
||||
|
||||
|
||||
async def test_no_show_prior_round_consumes_budget(clean):
|
||||
"""검증: round1=미참여 재생성 + round2=전원 미참여 인 체인에서 round2 를 마감.
|
||||
기대결과: CLOSED, 체인 [1,2] — 미참여 재생성 한도(1) 소진돼 재생성 없이 그냥 마감(round3 없음)."""
|
||||
engine = clean
|
||||
number = "C-NOSHOW-PRIOR"
|
||||
# round 1: 미참여 재생성으로 마감(close_reason=REGEN_NOSHOW) → 미참여 예산 1 소진
|
||||
await _seed_quotation(
|
||||
engine, number=number, round_=1, status=QuotationStatus.CLOSED.value,
|
||||
preferred_sp_yn=False, equal_bid_yn=False, close_reason=CloseReason.REGEN_NOSHOW.value,
|
||||
)
|
||||
# round 2: 또 전원 미참여 → 한도 도달이라 재생성 없이 그냥 마감
|
||||
qt2 = await _seed_quotation(engine, number=number, round_=2, status=QuotationStatus.IN_PROGRESS.value)
|
||||
await _add_session(engine, qt2, status=SessionStatus.CREATED.value)
|
||||
|
||||
service = QuotationService(QuotationCRUD())
|
||||
outcome = await service.close_and_decide(qt2)
|
||||
|
||||
rounds = await _rounds(engine, number)
|
||||
assert outcome == CloseOutcome.CLOSED, f"미참여 예산 소진 → 그냥 마감이어야 함, 실제 {outcome}"
|
||||
assert [r.round for r in rounds] == [1, 2], "재생성되면 안 됨(round 3 없음)"
|
||||
|
||||
|
||||
async def test_over_target_fail_closes(clean):
|
||||
"""검증: over_action=유찰(FAIL) 회사에서 단독 최저가가 목표 초과(session target=0 < bid=100)인 견적을 마감.
|
||||
기대결과: CLOSED + close_reason=FAIL_PRICE — 그 가격에 낙찰 안 하고 유찰(재생성 없음)."""
|
||||
engine = clean
|
||||
setting = await _seed_settings(engine, over_action=PriceGateAction.FAIL.value)
|
||||
qt = await _seed_quotation(engine, number="C-OVER-FAIL", round_=1,
|
||||
status=QuotationStatus.IN_PROGRESS.value, qt_setting_id=setting)
|
||||
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100)
|
||||
qt = await _seed_quotation(engine, number="C-AWARD", round_=1,
|
||||
status=QuotationStatus.IN_PROGRESS.value,
|
||||
mid_action=PriceGateAction.AWARD.value, over_action=PriceGateAction.OPEN.value)
|
||||
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100, target_price=200)
|
||||
|
||||
outcome = await QuotationService(QuotationCRUD()).close_and_decide(qt)
|
||||
|
||||
rounds = await _rounds(engine, "C-OVER-FAIL")
|
||||
assert outcome == CloseOutcome.CLOSED, f"목표초과+유찰정책 → 유찰이어야 함, 실제 {outcome}"
|
||||
assert [r.round for r in rounds] == [1], "재생성되면 안 됨(round 2 없음)"
|
||||
assert rounds[0].close_reason == CloseReason.FAIL_PRICE.value, f"close_reason=FAIL_PRICE 여야 함, 실제 {rounds[0].close_reason}"
|
||||
rounds = await _rounds(engine, "C-AWARD")
|
||||
assert outcome == CloseOutcome.AWARDED, f"기준 통과 단독 최저가 → 낙찰이어야 함, 실제 {outcome}"
|
||||
assert rounds[0].close_reason == CloseReason.AWARDED.value
|
||||
|
||||
|
||||
async def test_over_target_renego_regenerates(clean):
|
||||
"""검증: over_action=재협상(RENEGO) 회사에서 단독 최저가가 목표 초과인 견적을 첫 라운드에 마감.
|
||||
기대결과: REGENERATED + 체인 [1,2] — 그 가격에 낙찰 안 하고 다음 라운드로 더 깎기(1차 close_reason=REGEN_PRICE)."""
|
||||
async def test_over_target_opens(clean):
|
||||
"""검증: 단독 최저가(bid=200)가 목표가(100) 초과 · 목표초과=개찰(over=OPEN).
|
||||
기대결과: OPENED + close_reason=OPEN_PRICE — 낙찰 안 하고 개찰(자동 재생성 없이 체인 [1])."""
|
||||
engine = clean
|
||||
setting = await _seed_settings(engine, over_action=PriceGateAction.RENEGO.value)
|
||||
qt = await _seed_quotation(engine, number="C-OVER-RENEGO", round_=1,
|
||||
status=QuotationStatus.IN_PROGRESS.value, qt_setting_id=setting)
|
||||
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100)
|
||||
qt = await _seed_quotation(engine, number="C-OVER", round_=1,
|
||||
status=QuotationStatus.IN_PROGRESS.value,
|
||||
mid_action=PriceGateAction.AWARD.value, over_action=PriceGateAction.OPEN.value)
|
||||
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=200, target_price=100)
|
||||
|
||||
outcome = await QuotationService(QuotationCRUD()).close_and_decide(qt)
|
||||
|
||||
rounds = await _rounds(engine, "C-OVER-RENEGO")
|
||||
assert outcome == CloseOutcome.REGENERATED, f"목표초과+재협상정책 0회차 → 재생성이어야 함, 실제 {outcome}"
|
||||
assert [r.round for r in rounds] == [1, 2], f"round 2 가 생성돼야 함, 실제 {[r.round for r in rounds]}"
|
||||
assert rounds[0].close_reason == CloseReason.REGEN_PRICE.value, f"1차 close_reason=REGEN_PRICE 여야 함, 실제 {rounds[0].close_reason}"
|
||||
rounds = await _rounds(engine, "C-OVER")
|
||||
assert outcome == CloseOutcome.OPENED, f"목표초과 → 개찰이어야 함, 실제 {outcome}"
|
||||
assert [r.round for r in rounds] == [1], "자동 재생성 없음(round 2 없음)"
|
||||
assert rounds[0].close_reason == CloseReason.OPEN_PRICE.value
|
||||
|
||||
|
||||
# ===== 헬퍼 (위 테스트들이 쓰는 도우미. 세션 상태·마감 표식을 SQL 로 직접 세팅) =====
|
||||
async def test_anchor_only_opens_within_target(clean):
|
||||
"""검증: '앵커링가까지만 낙찰'(mid=OPEN) 에서 앵커(80)<최저가(120)≤목표(200).
|
||||
기대결과: OPENED + OPEN_PRICE — 앵커 위 구간은 낙찰 안 하고 개찰."""
|
||||
engine = clean
|
||||
qt = await _seed_quotation(engine, number="C-ANCHOR", round_=1,
|
||||
status=QuotationStatus.IN_PROGRESS.value,
|
||||
mid_action=PriceGateAction.OPEN.value, over_action=PriceGateAction.OPEN.value)
|
||||
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=120,
|
||||
target_price=200, target_anchoring_price=80)
|
||||
|
||||
outcome = await QuotationService(QuotationCRUD()).close_and_decide(qt)
|
||||
|
||||
rounds = await _rounds(engine, "C-ANCHOR")
|
||||
assert outcome == CloseOutcome.OPENED
|
||||
assert rounds[0].close_reason == CloseReason.OPEN_PRICE.value
|
||||
|
||||
|
||||
async def test_equal_lowest_opens(clean):
|
||||
"""검증: 최저가 동점(둘 다 100, 목표 200 이내).
|
||||
기대결과: OPENED + close_reason=OPEN_EQUAL(낙찰자 미정) — 자동 재입찰 없음(체인 [1])."""
|
||||
engine = clean
|
||||
qt = await _seed_quotation(engine, number="C-EQUAL", round_=1, status=QuotationStatus.IN_PROGRESS.value)
|
||||
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100, target_price=200)
|
||||
await _add_session(engine, qt, status=SessionStatus.DONE.value, bid_price=100, target_price=200)
|
||||
|
||||
outcome = await QuotationService(QuotationCRUD()).close_and_decide(qt)
|
||||
|
||||
rounds = await _rounds(engine, "C-EQUAL")
|
||||
assert outcome == CloseOutcome.OPENED, f"동가 → 개찰이어야 함, 실제 {outcome}"
|
||||
assert [r.round for r in rounds] == [1]
|
||||
assert rounds[0].close_reason == CloseReason.OPEN_EQUAL.value
|
||||
|
||||
|
||||
async def test_rejected_opens(clean):
|
||||
"""검증: 완료 투찰 없이 협상거부 세션만 존재.
|
||||
기대결과: OPENED + close_reason=OPEN_REJECT."""
|
||||
engine = clean
|
||||
qt = await _seed_quotation(engine, number="C-REJECT", round_=1, status=QuotationStatus.IN_PROGRESS.value)
|
||||
await _add_session(engine, qt, status=SessionStatus.REJECTED.value)
|
||||
|
||||
outcome = await QuotationService(QuotationCRUD()).close_and_decide(qt)
|
||||
|
||||
rounds = await _rounds(engine, "C-REJECT")
|
||||
assert outcome == CloseOutcome.OPENED, f"협상거부 → 개찰이어야 함, 실제 {outcome}"
|
||||
assert rounds[0].close_reason == CloseReason.OPEN_REJECT.value
|
||||
|
||||
|
||||
# ===== 헬퍼 (세션 상태·마감 표식을 SQL 로 직접 세팅) =====
|
||||
async def _seed_quotation(
|
||||
engine, *, number, round_, status, start_time=PAST, end_time=PAST,
|
||||
preferred_sp_yn=None, equal_bid_yn=None, close_reason=None, qt_setting_id=None,
|
||||
mid_action=1, over_action=1,
|
||||
):
|
||||
"""견적 1건 시드. number/round_ 로 체인을, close_reason 으로 '이전 라운드가 어떤 사유로 마감/재생성됐는지'를 만든다
|
||||
(재생성 한도 카운팅은 close_reason 의 REGEN_* 만 센다). qt_setting_id 로 마감 가격정책(설정)을 연결. preferred_sp_yn/equal_bid_yn 은 프론트 표시용."""
|
||||
"""견적 1건 시드. number/round_ 로 체인을, close_reason 으로 이전 라운드 마감 사유를 만든다.
|
||||
낙찰 기준(mid/over)은 견적 행에 직접 박제 — close_and_decide 가 이 행에서 읽는다(세팅 아님)."""
|
||||
qt_id = uuid.uuid4()
|
||||
async with engine.begin() as conn:
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO quotations "
|
||||
"(qt_id, user_id, qt_setting_id, version_id, name, number, type, status, "
|
||||
" round, iteration, start_time, end_time, deleted, preferred_sp_yn, equal_bid_yn, close_reason) VALUES "
|
||||
" round, iteration, start_time, end_time, deleted, preferred_sp_yn, equal_bid_yn, close_reason, "
|
||||
" mid_action, over_action) VALUES "
|
||||
"(:qt_id, :user_id, :qt_setting_id, :version_id, :name, :number, :type, :status, "
|
||||
" :round, 0, :start_time, :end_time, false, :pref, :eq, :creason)"
|
||||
" :round, 0, :start_time, :end_time, false, :pref, :eq, :creason, "
|
||||
" :mid, :over)"
|
||||
),
|
||||
{
|
||||
"qt_id": qt_id, "user_id": uuid.uuid4(), "qt_setting_id": qt_setting_id or uuid.uuid4(),
|
||||
@@ -180,51 +154,38 @@ async def _seed_quotation(
|
||||
"type": QuotationType.REQUOTE.value, "status": status, "round": round_,
|
||||
"start_time": start_time, "end_time": end_time,
|
||||
"pref": preferred_sp_yn, "eq": equal_bid_yn, "creason": close_reason,
|
||||
"mid": mid_action, "over": over_action,
|
||||
},
|
||||
)
|
||||
return qt_id
|
||||
|
||||
|
||||
async def _add_session(engine, qt_id, *, status, bid_price=None, supplier_id=None):
|
||||
"""세션 1건 시드(공급사 협상 1건)."""
|
||||
async def _add_session(engine, qt_id, *, status, bid_price=None, supplier_id=None,
|
||||
target_price=0, target_anchoring_price=None):
|
||||
"""세션 1건 시드(공급사 협상 1건). target_price/앵커링가로 가격게이트 입력을 만든다."""
|
||||
async with engine.begin() as conn:
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO sessions "
|
||||
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
|
||||
" target_price, status, bid_price, end_time) VALUES "
|
||||
" target_price, target_anchoring_price, status, bid_price, end_time) VALUES "
|
||||
"(:session_id, :quotation_id, :item_id, :supplier_id, :qt_number, :qt_round, :qt_type, "
|
||||
" 0, :status, :bid_price, :end_time)"
|
||||
" :target_price, :anchor, :status, :bid_price, :end_time)"
|
||||
),
|
||||
{
|
||||
"session_id": uuid.uuid4(), "quotation_id": qt_id, "item_id": uuid.uuid4(),
|
||||
"supplier_id": supplier_id or uuid.uuid4(), "qt_number": "Q", "qt_round": 1,
|
||||
"qt_type": QuotationType.REQUOTE.value, "status": status,
|
||||
"target_price": target_price, "anchor": target_anchoring_price,
|
||||
"bid_price": bid_price, "end_time": PAST,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def _rounds(engine, number):
|
||||
"""체인(number)의 (round, status, start_time, end_time, close_reason) 목록 — round 오름차순."""
|
||||
"""체인(number)의 (round, status, close_reason) 목록 — round 오름차순."""
|
||||
async with engine.begin() as conn:
|
||||
return (await conn.execute(
|
||||
text("SELECT round, status, start_time, end_time, close_reason FROM quotations "
|
||||
"WHERE number = :n ORDER BY round"),
|
||||
text("SELECT round, status, close_reason FROM quotations WHERE number = :n ORDER BY round"),
|
||||
{"n": number},
|
||||
)).all()
|
||||
|
||||
|
||||
async def _seed_settings(engine, *, mid_action=1, over_action=1, regen_limit=1):
|
||||
"""quotation_settings 1건 시드(마감 가격정책 지정). 반환: qt_setting_id."""
|
||||
sid = uuid.uuid4()
|
||||
async with engine.begin() as conn:
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO quotation_settings "
|
||||
"(qt_setting_id, user_id, target_margin_rate, anchoring_value, card_count, mid_action, over_action, regen_limit) "
|
||||
"VALUES (:sid, :uid, 0.1, 0.01, 3, :mid, :over, :lim)"
|
||||
),
|
||||
{"sid": sid, "uid": uuid.uuid4(), "mid": mid_action, "over": over_action, "lim": regen_limit},
|
||||
)
|
||||
return sid
|
||||
@@ -1,15 +1,14 @@
|
||||
"""견적 마감(close_and_decide) 테스트 — 마감하면 상황별로 결과가 맞게 판정되고, 그 결과가 작성자에게 알림으로 남는지 확인.
|
||||
|
||||
핵심은 '재견적(다음 라운드 재생성)이 나오는 경우 vs 안 나오는 경우'의 구분이다.
|
||||
마감 결과는 낙찰(AWARDED) 또는 개찰(OPENED, 낙찰자 미정 마감). 개찰은 결렬(유찰)이 아니며 자동 재협상/재생성도 없다.
|
||||
각 경우에 (1) 판정이 맞고 (2) 작성자 알림함에 알맞은 알림 1건이 남는지 본다:
|
||||
· 단독 최저가 → 낙찰 (SUCCESS) [재견적 X]
|
||||
· 협상 거부 → 결렬 (FAILURE, reason=rejected) [재견적 X]
|
||||
· 동가/미참여 + 한도 남음 → 재생성 (REGENERATED) [재견적 O]
|
||||
· 동가/미참여 + 한도 소진 → 결렬 (FAILURE, reason=closed) [재견적 X]
|
||||
재생성 한도: 사유(동가·미참여)별로 한 체인(같은 견적번호)에서 각 1번까지만.
|
||||
· 단독 최저가(기준 통과) → 낙찰 (SUCCESS)
|
||||
· 협상 거부 → 개찰 (알림 FAILURE, reason=rejected — 프론트에서 '개찰'로 표기)
|
||||
· 동가 → 개찰 (알림 FAILURE, reason=equal)
|
||||
· 전원 미응찰 → 개찰 (알림 FAILURE, reason=no_show)
|
||||
|
||||
공급사의 협상 결과(협상완료/거부/입찰가)는 협상 화면에서만 생기는 값이라 API 로 못 만든다 → SQL 로 직접 넣는다.
|
||||
마감 판정 로직 자체를 더 깊게 파는 건 test_scheduler·test_close_and_decide_fixes.
|
||||
마감 판정 로직 자체를 더 깊게 파는 건 test_close_and_decide_fixes.
|
||||
"""
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
@@ -17,7 +16,7 @@ from datetime import datetime
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.enums import CloseOutcome, CloseReason, NotificationType, QuotationStatus, QuotationType, SessionStatus
|
||||
from common.enums import CloseOutcome, NotificationType, QuotationStatus, QuotationType, SessionStatus
|
||||
from crud.quotation_crud import QuotationCRUD
|
||||
from services.quotation_service import QuotationService
|
||||
|
||||
@@ -32,10 +31,9 @@ async def clean(db_engine):
|
||||
return db_engine
|
||||
|
||||
|
||||
# ----- 재견적 X (낙찰·거부) -----
|
||||
async def test_award_notifies_success(clean):
|
||||
"""검증: 협상완료 세션 2건(입찰 100·200) — 단독 최저가로 마감.
|
||||
기대결과: 재견적 X, 판정 = 낙찰(AWARDED) + 알림 SUCCESS(winner_price=100=최저가, ref_qt_id=그 견적)."""
|
||||
"""검증: 협상완료 세션 2건(입찰 100·200) — 단독 최저가로 마감(기본 낙찰 기준=최저가 낙찰).
|
||||
기대결과: 판정 = 낙찰(AWARDED) + 알림 SUCCESS(winner_price=100=최저가, ref_qt_id=그 견적)."""
|
||||
engine = clean
|
||||
user_id = uuid.uuid4()
|
||||
winner = uuid.uuid4()
|
||||
@@ -54,9 +52,9 @@ async def test_award_notifies_success(clean):
|
||||
assert str(ref) == str(qt)
|
||||
|
||||
|
||||
async def test_rejected_notifies_failure(clean):
|
||||
async def test_rejected_notifies_open(clean):
|
||||
"""검증: 협상거부 세션만 있는 상태로 마감.
|
||||
기대결과: 재견적 X, 판정 = 결렬(CLOSED) + 알림 FAILURE(reason=rejected)."""
|
||||
기대결과: 판정 = 개찰(OPENED) + 알림(reason=rejected). 결렬 아님·자동 재생성 없음."""
|
||||
engine = clean
|
||||
user_id = uuid.uuid4()
|
||||
qt = await _seed_quotation(engine, user_id=user_id, number="N-REJECT")
|
||||
@@ -64,7 +62,7 @@ async def test_rejected_notifies_failure(clean):
|
||||
|
||||
outcome = await _service().close_and_decide(qt)
|
||||
|
||||
assert outcome == CloseOutcome.CLOSED
|
||||
assert outcome == CloseOutcome.OPENED
|
||||
notis = await _notifications(engine, user_id)
|
||||
assert len(notis) == 1
|
||||
type_, data, ref = notis[0]
|
||||
@@ -73,10 +71,9 @@ async def test_rejected_notifies_failure(clean):
|
||||
assert str(ref) == str(qt)
|
||||
|
||||
|
||||
# ----- 재견적 O (동가·미참여, 한도 남음) -----
|
||||
async def test_equal_bid_regenerates(clean):
|
||||
"""검증: 협상완료 세션 2건이 '동가'(둘 다 100), 체인에 동가 재생성 이력 없음(한도 남음).
|
||||
기대결과: 재견적 O, 판정 = 재생성(REGENERATED) + 알림 REGENERATED(reason=equal, tied_price=100, next_round=2)."""
|
||||
async def test_equal_bid_opens(clean):
|
||||
"""검증: 협상완료 세션 2건이 '동가'(둘 다 100).
|
||||
기대결과: 판정 = 개찰(OPENED, 낙찰자 미정) + 알림(reason=equal). 자동 재입찰 없음."""
|
||||
engine = clean
|
||||
user_id = uuid.uuid4()
|
||||
qt = await _seed_quotation(engine, user_id=user_id, number="N-EQUAL")
|
||||
@@ -85,19 +82,17 @@ async def test_equal_bid_regenerates(clean):
|
||||
|
||||
outcome = await _service().close_and_decide(qt)
|
||||
|
||||
assert outcome == CloseOutcome.REGENERATED
|
||||
assert outcome == CloseOutcome.OPENED
|
||||
notis = await _notifications(engine, user_id)
|
||||
assert len(notis) == 1
|
||||
type_, data, _ = notis[0]
|
||||
assert type_ == NotificationType.REGENERATED.value
|
||||
assert type_ == NotificationType.FAILURE.value
|
||||
assert data["reason"] == "equal"
|
||||
assert data["tied_price"] == 100
|
||||
assert data["next_round"] == 2
|
||||
|
||||
|
||||
async def test_no_show_regenerates(clean):
|
||||
"""검증: 전원 미참여(미시작 세션만), 체인에 미참여 재생성 이력 없음(한도 남음).
|
||||
기대결과: 재견적 O, 판정 = 재생성(REGENERATED) + 알림 REGENERATED(reason=no_show, next_round=2)."""
|
||||
async def test_no_show_opens(clean):
|
||||
"""검증: 전원 미응찰(미시작 세션만).
|
||||
기대결과: 판정 = 개찰(OPENED) + 알림(reason=no_show). 자동 재소집 없음."""
|
||||
engine = clean
|
||||
user_id = uuid.uuid4()
|
||||
qt = await _seed_quotation(engine, user_id=user_id, number="N-NOSHOW")
|
||||
@@ -106,89 +101,32 @@ async def test_no_show_regenerates(clean):
|
||||
|
||||
outcome = await _service().close_and_decide(qt)
|
||||
|
||||
assert outcome == CloseOutcome.REGENERATED
|
||||
assert outcome == CloseOutcome.OPENED
|
||||
notis = await _notifications(engine, user_id)
|
||||
assert len(notis) == 1
|
||||
type_, data, _ = notis[0]
|
||||
assert type_ == NotificationType.REGENERATED.value
|
||||
assert type_ == NotificationType.FAILURE.value
|
||||
assert data["reason"] == "no_show"
|
||||
assert data["next_round"] == 2
|
||||
|
||||
|
||||
# ----- 재견적 X (동가·미참여지만 한도 소진 → 결렬) -----
|
||||
async def test_equal_bid_limit_exhausted_fails(clean):
|
||||
"""검증: 1차가 이미 '동가'로 재생성된 체인(동가 한도 1 소진)에서, 2차도 또 동가로 마감.
|
||||
기대결과: 재견적 X — 판정 = 결렬(CLOSED) + 알림 FAILURE(reason=closed)."""
|
||||
engine = clean
|
||||
user_id = uuid.uuid4()
|
||||
# 1차: 동가로 재생성 마감(close_reason=REGEN_EQUAL) → 동가 한도 소진
|
||||
await _seed_quotation(engine, user_id=user_id, number="N-EQUAL-LIMIT", round_=1,
|
||||
status=QuotationStatus.CLOSED.value, equal_bid_yn=True,
|
||||
close_reason=CloseReason.REGEN_EQUAL.value)
|
||||
# 2차: 또 동가
|
||||
qt2 = await _seed_quotation(engine, user_id=user_id, number="N-EQUAL-LIMIT", round_=2)
|
||||
await _add_session(engine, qt2, status=SessionStatus.DONE.value, bid_price=100)
|
||||
await _add_session(engine, qt2, status=SessionStatus.DONE.value, bid_price=100)
|
||||
|
||||
outcome = await _service().close_and_decide(qt2)
|
||||
|
||||
assert outcome == CloseOutcome.CLOSED # 동가 한도 소진 → 재생성 없이 결렬
|
||||
notis = await _notifications(engine, user_id)
|
||||
assert len(notis) == 1
|
||||
type_, data, ref = notis[0]
|
||||
assert type_ == NotificationType.FAILURE.value
|
||||
assert data["reason"] == "equal" # 동가 유찰(FAIL_EQUAL) 사유
|
||||
assert str(ref) == str(qt2)
|
||||
|
||||
|
||||
async def test_no_show_limit_exhausted_fails(clean):
|
||||
"""검증: 1차가 이미 '미참여'로 재생성된 체인(미참여 한도 1 소진)에서, 2차도 또 전원 미참여로 마감.
|
||||
기대결과: 재견적 X — 판정 = 결렬(CLOSED) + 알림 FAILURE(reason=closed)."""
|
||||
engine = clean
|
||||
user_id = uuid.uuid4()
|
||||
# 1차: 미참여로 재생성 마감(close_reason=REGEN_NOSHOW) → 미참여 한도 소진
|
||||
await _seed_quotation(engine, user_id=user_id, number="N-NOSHOW-LIMIT", round_=1,
|
||||
status=QuotationStatus.CLOSED.value, preferred_sp_yn=False, equal_bid_yn=False,
|
||||
close_reason=CloseReason.REGEN_NOSHOW.value)
|
||||
# 2차: 또 전원 미참여
|
||||
qt2 = await _seed_quotation(engine, user_id=user_id, number="N-NOSHOW-LIMIT", round_=2)
|
||||
await _add_session(engine, qt2, status=SessionStatus.CREATED.value)
|
||||
await _add_session(engine, qt2, status=SessionStatus.CREATED.value)
|
||||
|
||||
outcome = await _service().close_and_decide(qt2)
|
||||
|
||||
assert outcome == CloseOutcome.CLOSED # 미참여 한도 소진 → 재생성 없이 결렬
|
||||
notis = await _notifications(engine, user_id)
|
||||
assert len(notis) == 1
|
||||
type_, data, ref = notis[0]
|
||||
assert type_ == NotificationType.FAILURE.value
|
||||
assert data["reason"] == "closed"
|
||||
assert str(ref) == str(qt2)
|
||||
|
||||
|
||||
# ===== 헬퍼 (위 테스트들이 쓰는 도우미. 세션 입찰값·이전 라운드 표식을 SQL 로 직접 세팅) =====
|
||||
async def _seed_quotation(
|
||||
engine, *, user_id, number, round_=1, status=QuotationStatus.IN_PROGRESS.value,
|
||||
preferred_sp_yn=None, equal_bid_yn=None, close_reason=None,
|
||||
):
|
||||
"""견적 1건 시드(작성자=user_id). close_reason 으로 '이전 라운드가 어떤 사유로 재생성됐는지'를 표식한다
|
||||
(재생성 한도 카운팅은 close_reason 의 REGEN_* 만 센다). preferred_sp_yn/equal_bid_yn 은 프론트 표시용."""
|
||||
# ===== 헬퍼 (세션 입찰값을 SQL 로 직접 세팅) =====
|
||||
async def _seed_quotation(engine, *, user_id, number, round_=1, status=QuotationStatus.IN_PROGRESS.value):
|
||||
"""견적 1건 시드(작성자=user_id). 낙찰 기준 mid/over 는 서버 기본(AWARD)=최저가 낙찰."""
|
||||
qt_id = uuid.uuid4()
|
||||
async with engine.begin() as conn:
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO quotations "
|
||||
"(qt_id, user_id, qt_setting_id, version_id, name, number, type, status, "
|
||||
" round, iteration, start_time, end_time, deleted, preferred_sp_yn, equal_bid_yn, close_reason) VALUES "
|
||||
" round, iteration, start_time, end_time, deleted) VALUES "
|
||||
"(:qt_id, :user_id, :qt_setting_id, :version_id, '견적A', :number, :type, :status, "
|
||||
" :round, 0, :start_time, :end_time, false, :pref, :eq, :creason)"
|
||||
" :round, 0, :start_time, :end_time, false)"
|
||||
),
|
||||
{
|
||||
"qt_id": qt_id, "user_id": user_id, "qt_setting_id": uuid.uuid4(),
|
||||
"version_id": uuid.uuid4(), "number": number,
|
||||
"type": QuotationType.REQUOTE.value, "status": status, "round": round_,
|
||||
"start_time": PAST, "end_time": PAST,
|
||||
"pref": preferred_sp_yn, "eq": equal_bid_yn, "creason": close_reason,
|
||||
},
|
||||
)
|
||||
return qt_id
|
||||
|
||||
@@ -9,7 +9,7 @@ from datetime import datetime
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.enums import QuotationType
|
||||
from common.enums import PriceGateAction, QuotationType
|
||||
from crud.quotation_crud import QuotationCRUD
|
||||
from router.v1.quotation.protocol import Req_CreateQuotation
|
||||
from services.quotation_service import QuotationService
|
||||
@@ -65,11 +65,67 @@ async def test_create_without_price_fails(db_engine, company_id):
|
||||
assert rows == []
|
||||
|
||||
|
||||
async def test_auction_forces_lowest_price_award(db_engine, company_id):
|
||||
"""검증: 1:N 경매(NEW_QUOTE)에 낙찰 기준(OPEN/OPEN)을 실어 생성 요청.
|
||||
기대결과: 경매는 무조건 최저가 낙찰 — 견적 행에 mid=over=AWARD 로 강제 저장(요청값 무시)."""
|
||||
item = await _seed_item(db_engine, company_id, internet_lowest=100_000)
|
||||
|
||||
req = Req_CreateQuotation(
|
||||
qt_setting_id=uuid.uuid4(),
|
||||
name="경매정책강제",
|
||||
type=QuotationType.NEW_QUOTE.value,
|
||||
end_time=FUTURE,
|
||||
item_ids=[item],
|
||||
supplier_ids=[uuid.uuid4(), uuid.uuid4()],
|
||||
mid_action=PriceGateAction.OPEN.value, # 경매엔 의미 없음 — 서버가 덮어야 함
|
||||
over_action=PriceGateAction.OPEN.value,
|
||||
)
|
||||
res = await _service().create_quotation(str(uuid.uuid4()), req)
|
||||
|
||||
assert res.result.success is True
|
||||
mid, over = await _quotation_policy(db_engine, res.qt_id)
|
||||
assert mid == PriceGateAction.AWARD.value, f"경매 mid_action 은 AWARD 강제여야 함, 실제 {mid}"
|
||||
assert over == PriceGateAction.AWARD.value, f"경매 over_action 은 AWARD 강제여야 함, 실제 {over}"
|
||||
|
||||
|
||||
async def test_nego_persists_award_criterion(db_engine, company_id):
|
||||
"""검증: 1:1 협상(NEW_NEGO)에 낙찰 기준(mid=AWARD/over=OPEN=목표까지 낙찰)을 실어 생성.
|
||||
기대결과: 요청값이 견적 행에 그대로 박제(협상은 사용자가 낙찰 기준을 정한다. 목표초과=개찰)."""
|
||||
item = await _seed_item(db_engine, company_id, internet_lowest=100_000)
|
||||
|
||||
req = Req_CreateQuotation(
|
||||
qt_setting_id=uuid.uuid4(),
|
||||
name="협상정책박제",
|
||||
type=QuotationType.NEW_NEGO.value,
|
||||
end_time=FUTURE,
|
||||
item_ids=[item],
|
||||
supplier_ids=[uuid.uuid4()],
|
||||
mid_action=PriceGateAction.AWARD.value,
|
||||
over_action=PriceGateAction.OPEN.value,
|
||||
)
|
||||
res = await _service().create_quotation(str(uuid.uuid4()), req)
|
||||
|
||||
assert res.result.success is True
|
||||
mid, over = await _quotation_policy(db_engine, res.qt_id)
|
||||
assert (mid, over) == (
|
||||
PriceGateAction.AWARD.value, PriceGateAction.OPEN.value,
|
||||
), f"협상 낙찰 기준이 그대로 저장돼야 함, 실제 {(mid, over)}"
|
||||
|
||||
|
||||
# ===== 헬퍼 (위 테스트들이 쓰는 도우미) =====
|
||||
def _service():
|
||||
return QuotationService(QuotationCRUD())
|
||||
|
||||
|
||||
async def _quotation_policy(engine, qt_id):
|
||||
"""생성된 견적의 낙찰 기준 (mid_action, over_action)."""
|
||||
async with engine.begin() as conn:
|
||||
return (await conn.execute(
|
||||
text("SELECT mid_action, over_action FROM quotations WHERE qt_id = :qt"),
|
||||
{"qt": qt_id},
|
||||
)).one()
|
||||
|
||||
|
||||
async def _seed_item(engine, company_id, *, internet_lowest):
|
||||
"""상품 1건 시드(인터넷최저가만). category_type·internet_lowest_price_yn 은 NOT NULL —
|
||||
ORM default 는 raw INSERT 에 안 먹으므로 명시한다(conftest companies.status 와 같은 이유)."""
|
||||
|
||||
Reference in new issue
Block a user