[refactor] 공급유형 기준을 상품-협력사 매핑으로 전환
This commit is contained in:
1 parent
9ac8fe6363
commit
d21e7c10b0
35 files changed
+157
-333
No files matched your search
@@ -25,21 +25,23 @@ _current_values = table(
|
||||
)
|
||||
|
||||
|
||||
async def fetch_current_values(db: AsyncSession, company_ids: list, supplier_type: int) -> dict:
|
||||
"""칸별 현재 앵커링 값 일괄 조회. {(company_id, price_range_index): rate‰} 반환.
|
||||
async def fetch_current_values(db: AsyncSession, company_ids: list, supplier_types: list[int]) -> dict:
|
||||
"""칸별 현재 앵커링 값 일괄 조회. {(company_id, supplier_type, price_range_index): rate‰} 반환.
|
||||
|
||||
supplier_type 은 견적 단위로 하나뿐이라 키에 넣지 않는다.
|
||||
supplier_type 은 세션의 (item_id, supplier_id) 매핑에서 온 supply_type 이다.
|
||||
조정 이력이 없는 칸은 결과에 없다(호출측 정적 폴백). 조회 실패 시 빈 dict."""
|
||||
if not company_ids or supplier_type not in SAMPLEABLE_SUPPLIER_TYPES:
|
||||
valid_types = sorted({int(t) for t in supplier_types if t in SAMPLEABLE_SUPPLIER_TYPES})
|
||||
if not company_ids or not valid_types:
|
||||
return {}
|
||||
try:
|
||||
stmt = select(
|
||||
_current_values.c.company_id,
|
||||
_current_values.c.supplier_type,
|
||||
_current_values.c.price_range_index,
|
||||
_current_values.c.anchoring_value,
|
||||
).where(
|
||||
_current_values.c.company_id.in_(company_ids),
|
||||
_current_values.c.supplier_type == supplier_type,
|
||||
_current_values.c.supplier_type.in_(valid_types),
|
||||
)
|
||||
rows = (await db.execute(stmt)).all()
|
||||
except Exception as ex:
|
||||
@@ -47,9 +49,9 @@ async def fetch_current_values(db: AsyncSession, company_ids: list, supplier_typ
|
||||
return {}
|
||||
|
||||
out = {}
|
||||
for company_id, price_range_index, rate in rows:
|
||||
for company_id, supplier_type, price_range_index, rate in rows:
|
||||
if not ANCHORING_VALUE_MIN <= rate <= ANCHORING_VALUE_MAX: # 범위 밖 값은 오염 방어 — 버리고 정적 폴백
|
||||
LOG.w(f"[앵커링] rate 범위 밖 — 무시(정적 폴백): company={company_id} bracket={price_range_index} rate={rate}")
|
||||
LOG.w(f"[앵커링] rate 범위 밖 — 무시(정적 폴백): company={company_id} type={supplier_type} bracket={price_range_index} rate={rate}")
|
||||
continue
|
||||
out[(company_id, price_range_index)] = rate
|
||||
out[(company_id, supplier_type, price_range_index)] = rate
|
||||
return out
|
||||
@@ -135,7 +135,7 @@ class supplier_items(MainTableMixin, MAIN_BASE):
|
||||
supplier_item_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
supplier_id = Column(UUID(as_uuid=True), nullable=False, index=True) # suppliers.supplier_id
|
||||
item_id = Column(UUID(as_uuid=True), nullable=False, index=True) # items.item_id
|
||||
# SupplierType: 이 협력사가 이 상품을 공급하는 방식(0=없음/1=유통/2=제조/3=총판). quotations.supplier_type 와 값은 같으나 의미 단위가 (협력사,상품)이라 컬럼명은 supply_type.
|
||||
# SupplierType: 이 협력사가 이 상품을 공급하는 방식(0=없음/1=유통/2=제조/3=총판).
|
||||
supply_type = Column(SmallInteger, nullable=False, server_default=text("0"), default=0)
|
||||
|
||||
|
||||
@@ -229,8 +229,6 @@ class quotations(MainTableMixin, MAIN_BASE):
|
||||
manager_contact_number = Column(String(20), nullable=True)
|
||||
memo = Column(String(100), nullable=True)
|
||||
md_price = Column(BigInteger, nullable=True)
|
||||
supplier_type = Column(SmallInteger, nullable=True)
|
||||
|
||||
iteration = Column(Integer, nullable=False, default=0)
|
||||
preferred_sp_yn = Column(Boolean, nullable=True)
|
||||
preferred_sp_id = Column(UUID(as_uuid=True), nullable=True)
|
||||
|
||||
@@ -237,8 +237,8 @@ class CardType(CodeEnum):
|
||||
|
||||
|
||||
class SupplierType(CodeEnum):
|
||||
"""quotations.supplier_type 코드값. 없음(0,미지정)/유통(1)/제조(2)/총판(3).
|
||||
없음은 프론트 폼에 '없음'으로 노출. KTC 앵커링 코드(기타=0)와 매핑 시 0↔없음 대응."""
|
||||
"""partner.supplier_items.supply_type 코드값. 없음(0,미지정)/유통(1)/제조(2)/총판(3).
|
||||
없음은 상품-협력사 매핑에서 유형 미지정 상태를 뜻한다."""
|
||||
|
||||
NONE = 0 # 없음(미지정)
|
||||
DISTRIBUTION = 1 # 유통
|
||||
|
||||
@@ -8,7 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import (
|
||||
quotations, sessions, chats, nego_cards, wild_cards, items, suppliers, quotation_settings,
|
||||
version_nego_cards, version_wild_cards, users,
|
||||
version_nego_cards, version_wild_cards, users, supplier_items,
|
||||
)
|
||||
from common.enums import CloseReason, ErrorType, QuotationStatus, SessionStatus
|
||||
from common.logger import LOG
|
||||
@@ -44,7 +44,7 @@ class IQuotationCRUD(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_last_supplier_type(self, cdb: AsyncSession, supplier_id, company_id=None) -> Tuple[ErrorType, Optional[tuple]]:
|
||||
async def get_supply_types(self, cdb: AsyncSession, item_ids, supplier_ids) -> Tuple[ErrorType, dict]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -400,33 +400,30 @@ class QuotationCRUD(IQuotationCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, {}
|
||||
|
||||
async def get_last_supplier_type(self, cdb: AsyncSession, supplier_id, company_id=None) -> Tuple[ErrorType, Optional[tuple]]:
|
||||
"""협력사의 직전 견적 supplier_type. (supplier_type, qt_number) | None.
|
||||
sessions(supplier_id) ⨝ quotations 에서 supplier_type 가 있는 최신 견적 1건."""
|
||||
async def get_supply_types(self, cdb: AsyncSession, item_ids, supplier_ids) -> Tuple[ErrorType, dict]:
|
||||
"""(item_id, supplier_id) -> supplier_items.supply_type 매핑.
|
||||
|
||||
매핑이 없거나 supply_type 이 0/NULL 이면 호출측이 정적 앵커링 값으로 폴백한다.
|
||||
"""
|
||||
try:
|
||||
conds = [
|
||||
sessions.supplier_id == supplier_id,
|
||||
quotations.supplier_type.isnot(None),
|
||||
quotations.deleted == False, # noqa: E712
|
||||
]
|
||||
if company_id is not None:
|
||||
conds.append(quotations.user_id.in_(select(users.user_id).where(users.company_id == company_id)))
|
||||
query = (
|
||||
select(quotations.supplier_type, quotations.number)
|
||||
.join(sessions, sessions.quotation_id == quotations.qt_id)
|
||||
.where(*conds)
|
||||
.order_by(quotations.created_at.desc())
|
||||
.limit(1)
|
||||
if not item_ids or not supplier_ids:
|
||||
return ErrorType.SUCCESS, {}
|
||||
query = select(
|
||||
supplier_items.item_id,
|
||||
supplier_items.supplier_id,
|
||||
supplier_items.supply_type,
|
||||
).where(
|
||||
supplier_items.item_id.in_(item_ids),
|
||||
supplier_items.supplier_id.in_(supplier_ids),
|
||||
supplier_items.deleted == False, # noqa: E712
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, None
|
||||
if not rows:
|
||||
return ErrorType.SUCCESS, None
|
||||
return ErrorType.SUCCESS, (rows[0][0], rows[0][1])
|
||||
return err_type, {}
|
||||
return ErrorType.SUCCESS, {(r[0], r[1]): r[2] for r in rows}
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
return ErrorType.DB_RUN_FAILED, {}
|
||||
|
||||
async def get_setting_rates(self, cdb: AsyncSession, qt_setting_id) -> Tuple[ErrorType, dict]:
|
||||
"""견적 세팅의 목표 마진율: {margin}. 목표가 산정 입력(인터넷 수수료는 상수).
|
||||
|
||||
@@ -4,7 +4,7 @@ from typing import Any, Optional
|
||||
|
||||
from pydantic import ConfigDict
|
||||
|
||||
from common.enums import CardType, ChatSender, CloseReason, DeliveryType, PriceGateAction, QuotationStatus, QuotationType, SessionStatus, SupplierType
|
||||
from common.enums import CardType, ChatSender, CloseReason, DeliveryType, PriceGateAction, QuotationStatus, QuotationType, SessionStatus
|
||||
from common.models.gmodel import Res_PageProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
@@ -26,7 +26,6 @@ class Req_CreateQuotation(QuotationProtocol):
|
||||
manager_contact_number: Optional[str] = None
|
||||
memo: Optional[str] = None
|
||||
md_price: Optional[int] = None # MD 제시가(원). 세션 목표가 산정 최우선값
|
||||
supplier_type: Optional[int] = None # 협력사 유형(SupplierType). 재견적 1:1 → 견적에 기록
|
||||
item_ids: list[uuid.UUID] = [] # 협상 대상 상품. item×supplier 조합마다 세션 1개 생성
|
||||
supplier_ids: list[uuid.UUID] = [] # 협상 초청 공급사
|
||||
card_ids: list[uuid.UUID] = [] # 선택 협상카드. 버전을 만들어 묶고 quotation.version_id 로 연결
|
||||
@@ -63,7 +62,6 @@ class QuotationData(WebPacketProtocol):
|
||||
manager_contact_number: Optional[str] = None
|
||||
memo: Optional[str] = None
|
||||
md_price: Optional[int] = None
|
||||
supplier_type: Optional[SupplierType] = None
|
||||
iteration: int = 0
|
||||
preferred_sp_yn: Optional[bool] = None
|
||||
preferred_sp_id: Optional[uuid.UUID] = None
|
||||
@@ -189,11 +187,6 @@ class Res_QuotationCards(Res_WebPacketProtocol):
|
||||
cards: list[QuotationCardData] = []
|
||||
|
||||
|
||||
class Res_LastSupplierType(Res_WebPacketProtocol):
|
||||
supplier_type: Optional[SupplierType] = None # 협력사 직전 견적의 유형(없으면 None)
|
||||
qt_number: Optional[str] = None # 그 견적의 번호(이전 견적 값임을 표시용)
|
||||
|
||||
|
||||
class TargetCandidate(WebPacketProtocol):
|
||||
basis: str
|
||||
label: str
|
||||
|
||||
@@ -12,7 +12,6 @@ from .protocol import (
|
||||
Req_RegenerateQuotation,
|
||||
Res_CreateQuotation,
|
||||
Res_DeleteQuotation,
|
||||
Res_LastSupplierType,
|
||||
Res_NotifySessions,
|
||||
Res_Quotation,
|
||||
Res_QuotationCards,
|
||||
@@ -122,11 +121,6 @@ async def delete_quotation(qt_id: UUID, service: QuotationService = Depends(), u
|
||||
return RemoveNoneResponse(await service.delete_quotation(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
|
||||
|
||||
|
||||
@router.get(path="/supplier/{supplier_id}/last-type", response_model=Res_LastSupplierType, summary="협력사 직전 견적 유형")
|
||||
async def get_supplier_last_type(supplier_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||
return RemoveNoneResponse(await service.get_last_supplier_type(str(supplier_id), user_info.company_id))
|
||||
|
||||
|
||||
# ----- 단건 조회 (정적/하위 경로 뒤에 선언) -----
|
||||
@router.get(path="/{qt_id}", response_model=Res_Quotation, summary="견적 조회")
|
||||
async def get_quotation(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||
|
||||
@@ -34,7 +34,7 @@ INSERT INTO quotation.quotations
|
||||
(qt_id, user_id, qt_setting_id, version_id, name, number, type, round, status,
|
||||
start_time, end_time, manager_name, manager_email, manager_contact_number, memo,
|
||||
iteration, preferred_sp_yn, preferred_sp_id, preferred_sp_name, equal_bid_yn, equal_bid_data,
|
||||
close_reason, md_price, supplier_type, created_at, updated_at, deleted)
|
||||
close_reason, md_price, created_at, updated_at, deleted)
|
||||
VALUES
|
||||
-- ① 낙찰(절감): 목표 400,000 → 낙찰 372,000
|
||||
('aaaa0001-0000-0000-0000-000000000001','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||
@@ -42,14 +42,14 @@ VALUES
|
||||
'① 낙찰(절감) 데모','EST-DEMO-01',4,1,3,
|
||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','낙찰·목표대비 절감 케이스',
|
||||
1, true,'9795c2e5-3ac2-4e44-aeb5-c6c5e3053f09','(주)대한정밀', null, null,
|
||||
1, 400000, 1, now(), now(), false),
|
||||
1, 400000, now(), now(), false),
|
||||
-- ② 낙찰(목표초과): 목표 350,000 → 낙찰 368,000 (over_action=낙찰)
|
||||
('aaaa0002-0000-0000-0000-000000000002','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||
'② 낙찰(목표초과) 데모','EST-DEMO-02',4,1,3,
|
||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','낙찰이지만 목표가 초과 케이스',
|
||||
1, true,'69e7057a-5919-48cd-b329-13b833bff994','서울산업소재(주)', null, null,
|
||||
1, 350000, 1, now(), now(), false),
|
||||
1, 350000, now(), now(), false),
|
||||
-- ③ 동가 재입찰(REGEN_EQUAL): 두 곳 390,000 동률 → 재입찰 진행
|
||||
('aaaa0003-0000-0000-0000-000000000003','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||
@@ -57,42 +57,42 @@ VALUES
|
||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','동가 발생·다음 라운드 재입찰 케이스',
|
||||
1, false, null, null, true,
|
||||
'[{"supplier_id":"9795c2e5-3ac2-4e44-aeb5-c6c5e3053f09","supplier_name":"(주)대한정밀","bid_price":390000},{"supplier_id":"747897ec-adab-4f3e-9076-15803ddf821f","supplier_name":"글로벌테크놀로지","bid_price":390000}]'::jsonb,
|
||||
6, 400000, 1, now(), now(), false),
|
||||
6, 400000, now(), now(), false),
|
||||
-- ④ 거부 유찰(FAIL_REJECT): 협상거부로 마감
|
||||
('aaaa0004-0000-0000-0000-000000000004','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||
'④ 거부 개찰 데모','EST-DEMO-04',2,1,3,
|
||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','협상 거부로 유찰 케이스',
|
||||
1, null, null, null, null, null,
|
||||
8, 400000, 1, now(), now(), false),
|
||||
8, 400000, now(), now(), false),
|
||||
-- ⑤ 미참여 재소집(REGEN_NOSHOW): 전원 미참여 → 다음 라운드 재소집
|
||||
('aaaa0005-0000-0000-0000-000000000005','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||
'⑤ 미응찰 개찰 데모','EST-DEMO-05',1,1,3,
|
||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','전원 미참여·다음 라운드 재소집 케이스',
|
||||
1, false, null, null, false, null,
|
||||
7, 400000, 1, now(), now(), false),
|
||||
7, 400000, now(), now(), false),
|
||||
-- ⑥ 진행중: 일부 투찰 완료, 아직 안 닫힘 (close_reason NULL)
|
||||
('aaaa0006-0000-0000-0000-000000000006','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||
'⑥ 진행중 데모','EST-DEMO-06',4,1,2,
|
||||
now()-interval '1 day', now()+interval '1 day','김담당','mgr@imk.kr','010-1111-1111','협상 진행중·현재 최저 투찰 케이스',
|
||||
1, null, null, null, null, null,
|
||||
null, 400000, 1, now(), now(), false),
|
||||
null, 400000, now(), now(), false),
|
||||
-- ⑦ 가격 재협상(REGEN_PRICE): 단독 최저가 420,000 > 목표 350,000 → 재협상 진행
|
||||
('aaaa0007-0000-0000-0000-000000000007','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||
'⑦ 목표초과 개찰 데모','EST-DEMO-07',4,1,3,
|
||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','목표 초과 → 재협상(더 깎기) 진행 케이스',
|
||||
1, false, null, null, false, null,
|
||||
5, 350000, 1, now(), now(), false),
|
||||
5, 350000, now(), now(), false),
|
||||
-- ⑧ 가격 유찰(FAIL_PRICE): 단독 최저가 430,000 > 목표 350,000, over_action=유찰(또는 한도소진) → 유찰
|
||||
('aaaa0008-0000-0000-0000-000000000008','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||
'⑧ 목표초과 개찰 데모(2)','EST-DEMO-08',4,1,3,
|
||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','목표 초과 → 유찰 케이스',
|
||||
1, false, null, null, false, null,
|
||||
5, 350000, 1, now(), now(), false),
|
||||
5, 350000, now(), now(), false),
|
||||
-- ⑨ 동가 유찰(FAIL_EQUAL): 동가지만 재입찰 한도 소진/유찰 정책 → 유찰
|
||||
('aaaa0009-0000-0000-0000-000000000009','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||
@@ -100,14 +100,14 @@ VALUES
|
||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','동가지만 재입찰 한도 소진 → 유찰 케이스',
|
||||
1, false, null, null, true,
|
||||
'[{"supplier_id":"9795c2e5-3ac2-4e44-aeb5-c6c5e3053f09","supplier_name":"(주)대한정밀","bid_price":405000},{"supplier_id":"69e7057a-5919-48cd-b329-13b833bff994","supplier_name":"서울산업소재(주)","bid_price":405000}]'::jsonb,
|
||||
6, 400000, 1, now(), now(), false),
|
||||
6, 400000, now(), now(), false),
|
||||
-- ⑩ 미참여 유찰(FAIL_NOSHOW): 전원 미참여 + 재소집 한도 소진 → 유찰
|
||||
('aaaa0010-0000-0000-0000-000000000010','b874f33d-afc3-4498-a9c2-19bc5ae8faba',
|
||||
'40614764-43d5-4c45-a2f7-ccf659884c37','00000000-0000-0000-0000-000000000030',
|
||||
'⑩ 미응찰 개찰 데모(2)','EST-DEMO-10',1,2,3,
|
||||
now()-interval '2 days', now()-interval '1 hour','김담당','mgr@imk.kr','010-1111-1111','전원 미참여 + 재소집 한도 소진 → 유찰 케이스',
|
||||
1, false, null, null, false, null,
|
||||
7, 400000, 1, now(), now(), false);
|
||||
7, 400000, now(), now(), false);
|
||||
|
||||
-- ── 세션 ────────────────────────────────────────────────────────────────
|
||||
-- 공통: item=a3d1fff5, DeliveryType 협력사배송=1
|
||||
|
||||
@@ -29,7 +29,6 @@ from router.v1.quotation.protocol import (
|
||||
Req_CreateQuotation,
|
||||
Res_CreateQuotation,
|
||||
Res_DeleteQuotation,
|
||||
Res_LastSupplierType,
|
||||
Res_NotifySessions,
|
||||
Res_Quotation,
|
||||
Res_QuotationCards,
|
||||
@@ -255,22 +254,6 @@ class QuotationService:
|
||||
res.quotation = QuotationData.model_validate(quotation)
|
||||
return res
|
||||
|
||||
async def get_last_supplier_type(self, supplier_id: str, company_id=None) -> Res_LastSupplierType:
|
||||
"""협력사의 직전 견적 supplier_type(견적생성 모달 프리필용). 이력 없으면 비워서 반환."""
|
||||
res = Res_LastSupplierType()
|
||||
err_type, got = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.quotation_crud.get_last_supplier_type(s, uuid.UUID(supplier_id), company_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
if got:
|
||||
res.supplier_type = got[0]
|
||||
res.qt_number = got[1]
|
||||
return res
|
||||
|
||||
async def create_quotation(self, user_id: str, req: Req_CreateQuotation) -> Res_CreateQuotation:
|
||||
"""[프론트] 신규 견적 생성. 요청값을 보정한 뒤 공통 빌더(_build_quotation)에 위임한다.
|
||||
생성 성공 시 작성자에게 CREATED 알림(인박스)."""
|
||||
@@ -291,7 +274,6 @@ class QuotationService:
|
||||
manager_contact_number=req.manager_contact_number,
|
||||
memo=req.memo,
|
||||
md_price=req.md_price,
|
||||
supplier_type=req.supplier_type,
|
||||
item_ids=req.item_ids,
|
||||
supplier_ids=req.supplier_ids,
|
||||
card_ids=req.card_ids,
|
||||
@@ -370,7 +352,6 @@ class QuotationService:
|
||||
manager_contact_number=original.manager_contact_number,
|
||||
memo=original.memo,
|
||||
md_price=original.md_price,
|
||||
supplier_type=original.supplier_type,
|
||||
item_ids=item_ids,
|
||||
supplier_ids=list(supplier_ids),
|
||||
card_ids=[], # 새 버전 안 만듦(원본 version_id 재사용)
|
||||
@@ -383,7 +364,7 @@ class QuotationService:
|
||||
self, *,
|
||||
user_id: str, qt_setting_id, version_id, name: str, number: str,
|
||||
type_: int, status: int, round_: int, start_time, end_time,
|
||||
manager_name, manager_email, manager_contact_number, memo, md_price, supplier_type,
|
||||
manager_name, manager_email, manager_contact_number, memo, md_price,
|
||||
item_ids: list, supplier_ids: list, card_ids: list,
|
||||
mid_action: Optional[int] = None, # 낙찰 기준(견적 단위). 앵커링가<투찰가≤목표가 처리(AWARD/OPEN)
|
||||
over_action: Optional[int] = None, # 목표가<투찰가 처리(1:1 협상은 항상 OPEN)
|
||||
@@ -418,7 +399,7 @@ class QuotationService:
|
||||
fee = self.INTERNET_AVERAGE_FEE # 인터넷가 차감 수수료율(상수)
|
||||
margin = rates.get("margin") or 0.0 # 판매가 차감 목표마진율
|
||||
# 앵커링가는 quotation_settings.anchoring_value(구 float 비율)를 더 이상 쓰지 않는다(앵커링 v1.2) —
|
||||
# 칸(회사×협력사유형×가격구간)별 조정 anchoring_value(정수 ‰)로 계산한다. 아래 세션 생성부 ②.
|
||||
# 칸(회사×상품-협력사 공급유형×가격구간)별 조정 anchoring_value(정수 ‰)로 계산한다. 아래 세션 생성부 ②.
|
||||
|
||||
# 선택 협상카드가 있으면 새 버전을 만들어 카드들을 묶고, quotation.version_id 로 연결한다.
|
||||
# (quotation↔card 는 version → version_nego_cards/version_wild_cards 로 연결.)
|
||||
@@ -465,7 +446,6 @@ class QuotationService:
|
||||
manager_contact_number=manager_contact_number,
|
||||
memo=memo,
|
||||
md_price=md_price,
|
||||
supplier_type=supplier_type,
|
||||
mid_action=mid_action,
|
||||
over_action=over_action,
|
||||
)
|
||||
@@ -491,8 +471,8 @@ class QuotationService:
|
||||
res.result.SetResult(ErrorType.QUOTATION_TARGET_PRICE_UNAVAILABLE)
|
||||
return res
|
||||
|
||||
# ② 앵커가 산출 — 칸(items.company_id × quotations.supplier_type × 목표가 구간) anchoring_value 조회 후
|
||||
# 정수 연산으로 박제(앵커링 v1.2, 인수인계.md §1.3). 유형 미지정/조정 이력 없음/조회 실패는
|
||||
# ② 앵커가 산출 — 칸(items.company_id × supplier_items.supply_type × 목표가 구간) anchoring_value 조회 후
|
||||
# 정수 연산으로 박제(앵커링 v1.2, 인수인계.md §1.3). 매핑 미지정/조정 이력 없음/조회 실패는
|
||||
# 정적 테이블 시작값 폴백 — 값 조회 때문에 견적 생성이 실패하지 않는다(규칙 6).
|
||||
_err, item_companies = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
@@ -500,12 +480,19 @@ class QuotationService:
|
||||
lambda s: self.quotation_crud.get_item_companies(s, item_ids),
|
||||
)
|
||||
item_companies = item_companies if _err == ErrorType.SUCCESS else {}
|
||||
_err, supply_types = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.quotation_crud.get_supply_types(s, item_ids, supplier_ids),
|
||||
)
|
||||
supply_types = supply_types if _err == ErrorType.SUCCESS else {}
|
||||
value_map = {}
|
||||
if supplier_type in SAMPLEABLE_SUPPLIER_TYPES and item_companies:
|
||||
sampleable_supply_types = sorted({t for t in supply_types.values() if t in SAMPLEABLE_SUPPLIER_TYPES})
|
||||
if sampleable_supply_types and item_companies:
|
||||
value_map = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: fetch_current_values(s, list(set(item_companies.values())), supplier_type),
|
||||
lambda s: fetch_current_values(s, list(set(item_companies.values())), sampleable_supply_types),
|
||||
)
|
||||
|
||||
session_objs = []
|
||||
@@ -513,11 +500,12 @@ class QuotationService:
|
||||
tp = target_prices[iid]
|
||||
price_range = calc_price_range_index(tp)
|
||||
company = item_companies.get(iid)
|
||||
value = value_map.get((company, price_range)) if company is not None else None
|
||||
if value is None:
|
||||
value = get_base_anchoring_value(price_range)
|
||||
ap = calc_anchoring_price(tp, value) # 목표가×(1000−value)//1000 — float 곱셈 금지(1원 내림 정확성)
|
||||
for sid in supplier_ids:
|
||||
supply_type = supply_types.get((iid, sid))
|
||||
value = value_map.get((company, supply_type, price_range)) if company is not None else None
|
||||
if value is None:
|
||||
value = get_base_anchoring_value(price_range)
|
||||
ap = calc_anchoring_price(tp, value) # 목표가×(1000−value)//1000 — float 곱셈 금지(1원 내림 정확성)
|
||||
session_objs.append(
|
||||
sessions(
|
||||
session_id=uuid.uuid4(),
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""앵커링 v1.2 — 견적 생성 시 칸(회사×협력사유형×가격구간) anchoring_value 로 앵커가를 박제하는지 검증.
|
||||
"""앵커링 v1.2 — 견적 생성 시 칸(회사×상품-협력사 공급유형×가격구간) anchoring_value 로 앵커가를 박제하는지 검증.
|
||||
|
||||
이식 명세: schedules/anchoring/docs/인수인계.md §1.
|
||||
- 앵커가 = 목표가 × (1000 − anchoring_value) // 1000 (정수 연산), anchoring_value 동시 박제
|
||||
- 조정 이력 없음 / 유형 미지정 / anchoring 스키마 미적용 → 정적 테이블 시작값(10‰) 폴백,
|
||||
- 조정 이력 없음 / 매핑 유형 미지정 / anchoring 스키마 미적용 → 정적 테이블 시작값(10‰) 폴백,
|
||||
견적 생성은 실패하지 않는다(규칙 6)
|
||||
- 재생성 라운드는 목표가만 상속하고 앵커는 생성 시점 anchoring_value 로 재계산(규칙 1 — 상속 폐지)
|
||||
"""
|
||||
@@ -22,12 +22,12 @@ BASE_VALUE = 10 # 정적 테이블 시작값(‰) — anchoring_base.json 전
|
||||
|
||||
|
||||
async def test_create_without_anchoring_schema_falls_back_to_base_value(db_engine, company_id):
|
||||
"""검증: anchoring 스키마가 아예 없는 DB 에서 supplier_type=1(유통) 견적 생성.
|
||||
"""검증: anchoring 스키마가 아예 없는 DB 에서 supply_type=1(유통) 매핑으로 견적 생성.
|
||||
기대결과: 조회 실패에도 생성 성공 + 앵커가=목표가×990‰(시작값), anchoring_value=10 박제."""
|
||||
await _drop_anchoring(db_engine)
|
||||
item = await _seed_item(db_engine, company_id, internet_lowest=100_000)
|
||||
|
||||
res = await _create(item_ids=[item], supplier_type=1)
|
||||
res = await _create(db_engine, item_ids=[item], supply_type=1)
|
||||
|
||||
assert res.result.success is True
|
||||
tp = int(100_000 * (1 - QuotationService.INTERNET_AVERAGE_FEE)) # 92,200
|
||||
@@ -45,7 +45,7 @@ async def test_create_uses_latest_adjusted_value_per_cell(db_engine, company_id)
|
||||
tp_miss = int(5_000 * (1 - QuotationService.INTERNET_AVERAGE_FEE))
|
||||
await _seed_adjustment(db_engine, company_id, supplier_type=1, price_range=calc_price_range_index(tp_hit), value_after=50)
|
||||
|
||||
res = await _create(item_ids=[item_hit, item_miss], supplier_type=1)
|
||||
res = await _create(db_engine, item_ids=[item_hit, item_miss], supply_type=1)
|
||||
|
||||
assert res.result.success is True
|
||||
rows = await _session_anchor_rows(db_engine, res.qt_id)
|
||||
@@ -53,15 +53,15 @@ async def test_create_uses_latest_adjusted_value_per_cell(db_engine, company_id)
|
||||
assert rows[item_miss] == (tp_miss, tp_miss * 990 // 1000, BASE_VALUE)
|
||||
|
||||
|
||||
async def test_supplier_type_unset_uses_base_value(db_engine, company_id):
|
||||
"""검증: supplier_type 미지정(None) 견적 생성 — 칸(회사×유형×구간) 구성 불가.
|
||||
async def test_supply_type_unset_uses_base_value(db_engine, company_id):
|
||||
"""검증: supply_type 미지정(None) 매핑으로 견적 생성 — 칸(회사×유형×구간) 구성 불가.
|
||||
기대결과: 같은 회사·구간에 조정 이력이 있어도 쓰지 않고 시작값 10‰ 박제."""
|
||||
await _reset_anchoring(db_engine)
|
||||
item = await _seed_item(db_engine, company_id, internet_lowest=100_000)
|
||||
tp = int(100_000 * (1 - QuotationService.INTERNET_AVERAGE_FEE))
|
||||
await _seed_adjustment(db_engine, company_id, supplier_type=1, price_range=calc_price_range_index(tp), value_after=50)
|
||||
|
||||
res = await _create(item_ids=[item], supplier_type=None)
|
||||
res = await _create(db_engine, item_ids=[item], supply_type=None)
|
||||
|
||||
assert res.result.success is True
|
||||
rows = await _session_anchor_rows(db_engine, res.qt_id)
|
||||
@@ -75,7 +75,7 @@ async def test_regenerate_inherits_target_but_recomputes_anchor(db_engine, compa
|
||||
item = await _seed_item(db_engine, company_id, internet_lowest=100_000)
|
||||
supplier = uuid.uuid4()
|
||||
|
||||
res1 = await _create(item_ids=[item], supplier_type=1, supplier_ids=[supplier])
|
||||
res1 = await _create(db_engine, item_ids=[item], supply_type=1, supplier_ids=[supplier])
|
||||
assert res1.result.success is True
|
||||
tp = int(100_000 * (1 - QuotationService.INTERNET_AVERAGE_FEE))
|
||||
rows1 = await _session_anchor_rows(db_engine, res1.qt_id)
|
||||
@@ -108,20 +108,40 @@ def _service():
|
||||
return QuotationService(QuotationCRUD())
|
||||
|
||||
|
||||
async def _create(*, item_ids, supplier_type, supplier_ids=None):
|
||||
"""supplier_type 을 지정해 견적 1건 생성(공급사 기본 1곳)."""
|
||||
async def _create(engine, *, item_ids, supply_type, supplier_ids=None):
|
||||
"""supplier_items.supply_type 매핑을 시드한 뒤 견적 1건 생성(공급사 기본 1곳)."""
|
||||
supplier_ids = supplier_ids or [uuid.uuid4()]
|
||||
await _seed_supplier_items(engine, item_ids, supplier_ids, supply_type=supply_type)
|
||||
req = Req_CreateQuotation(
|
||||
qt_setting_id=uuid.uuid4(), # FK 미설정 — 세팅 없으면 율 0(앵커는 세팅과 무관해짐)
|
||||
name="앵커링검증",
|
||||
type=QuotationType.NEW_QUOTE.value,
|
||||
end_time=FUTURE,
|
||||
supplier_type=supplier_type,
|
||||
item_ids=list(item_ids),
|
||||
supplier_ids=supplier_ids or [uuid.uuid4()],
|
||||
supplier_ids=supplier_ids,
|
||||
)
|
||||
return await _service().create_quotation(str(uuid.uuid4()), req)
|
||||
|
||||
|
||||
async def _seed_supplier_items(engine, item_ids, supplier_ids, *, supply_type):
|
||||
async with engine.begin() as conn:
|
||||
for item_id in item_ids:
|
||||
for supplier_id in supplier_ids:
|
||||
await conn.execute(
|
||||
text(
|
||||
"INSERT INTO supplier_items "
|
||||
"(supplier_item_id, supplier_id, item_id, supply_type) "
|
||||
"VALUES (:id, :supplier_id, :item_id, :supply_type)"
|
||||
),
|
||||
{
|
||||
"id": uuid.uuid4(),
|
||||
"supplier_id": supplier_id,
|
||||
"item_id": item_id,
|
||||
"supply_type": supply_type if supply_type is not None else 0,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def _seed_item(engine, company_id, *, internet_lowest):
|
||||
"""상품 1건 시드(인터넷최저가만). NOT NULL 컬럼은 명시(ORM default 는 raw INSERT 에 안 먹음)."""
|
||||
item_id = uuid.uuid4()
|
||||
|
||||
Reference in new issue
Block a user