[feat] negodata: 견적 목표가 산정 개편 + 협상 초청메일 + 카드 사용구분

[견적·목표가]
- 목표가 산정 KTC 기준 정비(MD 우선, 없으면 인터넷최저가·매입가·판매가 중 최저 / 신규는 인터넷최저가만)
- 인터넷 평균 수수료 0.078 상수화(견적설정 컬럼 제거)
- 앵커링가 세션 저장 + 목표가 클릭 시 산정내역 모달
- 재생성 시 목표가·앵커링가 재계산 없이 직전 값 상속(KTC)
- MD 제시가·협력사 유형(유통·제조·총판·기타) 입력

[협상카드]
- 사용 구분(공통/신규견적전용/재견적전용)

[협상 진행]
- 협력사 초청 메일 발송(일괄/개별·재발송, 발송상태 표시)

[기타]
- 견적상세 창 닫기 버그 수정, 불필요한 컬럼 주석 정리
- DB: 기존 DB는 postgres-init/04-alter.sql 적용 필요(자동 마이그레이션 없음)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
minaChoiandClaude Opus 4.8 committed 2026-06-29 13:33:08 +09:00
1 parent b42d084063
commit 019f3dbeac
51 files changed
+1263 -163

No files matched your search

+120 -2
View File
@@ -22,6 +22,7 @@ from router.v1.quotation.protocol import (
Res_CreateQuotation,
Res_DeleteQuotation,
Res_LastSupplierType,
Res_NotifySessions,
Res_Quotation,
Res_QuotationCards,
Res_QuotationList,
@@ -30,6 +31,7 @@ from router.v1.quotation.protocol import (
Res_QuotationStatus,
Res_SessionChat,
)
from services.email import EmailUnavailable, build_invite_email, send_email
class QuotationService:
@@ -51,6 +53,9 @@ class QuotationService:
# TODO 하한값 변경 해야함 !!! feat. MarineYang
MIN_REGEN_DURATION = timedelta(hours=1)
# 인터넷 평균 수수료율(상수). 시장 평균값이라 견적/세팅별로 두지 않고 고정. 목표가=인터넷최저가×(1−값).
INTERNET_AVERAGE_FEE = 0.078
def __init__(self, quotation_crud: IQuotationCRUD = Depends(QuotationCRUD)):
self.quotation_crud = quotation_crud
@@ -73,6 +78,11 @@ class QuotationService:
③ 후보 0개 → 견적 생성 불가(ValueError)."""
if md_price:
return int(md_price)
# 율은 비율(0~1 미만)이어야 한다. 1 이상이면 (1−율)≤0 → 목표가가 0/음수가 되므로 설정 오류로 막는다.
if not 0.0 <= (fee or 0.0) < 1.0:
raise ValueError(f"인터넷 수수료율은 0 이상 1 미만이어야 합니다: fee={fee}")
if not is_new and not 0.0 <= (margin or 0.0) < 1.0:
raise ValueError(f"목표 마진율은 0 이상 1 미만이어야 합니다: margin={margin}")
candidates = []
if internet_lowest:
candidates.append(int(internet_lowest) * (1 - (fee or 0.0)))
@@ -289,7 +299,7 @@ class QuotationService:
lambda s: self.quotation_crud.get_setting_rates(s, qt_setting_id),
)
rates = rates if _err == ErrorType.SUCCESS else {}
fee = rates.get("fee") or 0.0 # 인터넷가 차감 수수료율
fee = self.INTERNET_AVERAGE_FEE # 인터넷가 차감 수수료율(상수)
margin = rates.get("margin") or 0.0 # 판매가 차감 목표마진율
anchoring = rates.get("anchoring") or 0.0 # 앵커링가 = 목표가×(1−값)
@@ -352,6 +362,8 @@ class QuotationService:
else:
internet, purchase, selling = prices.get(iid) or (None, None, None)
tp = self._calc_target_price(md_price, internet, purchase, selling, fee, margin, is_new=is_new)
if not 0.0 <= anchoring < 1.0: # 율 1 이상이면 앵커링가가 0/음수 → 설정 오류로 막는다.
raise ValueError(f"앵커링 값은 0 이상 1 미만이어야 합니다: anchoring={anchoring}")
ap = int(tp * (1 - anchoring)) # 앵커링가 = floor(목표가×(1−앵커링율)); 율 0이면 목표가와 동일
for sid in supplier_ids:
session_objs.append(
@@ -369,7 +381,11 @@ class QuotationService:
end_time=quotation.end_time,
)
)
except ValueError:
except ValueError as ex:
LOG.w(
f"[목표가 산정불가] qt_id={qt_id} item={iid} is_new={is_new} "
f"md={md_price} internet={internet} purchase={purchase} selling={selling} :: {ex}"
)
res.result.SetResult(ErrorType.QUOTATION_TARGET_PRICE_UNAVAILABLE)
return res
@@ -694,6 +710,7 @@ class QuotationService:
qt_round=r.qt_round,
qt_type=r.qt_type,
target_price=r.target_price,
target_anchoring_price=r.target_anchoring_price,
status=r.status,
bid_price=r.bid_price,
bid_at=r.bid_at,
@@ -701,6 +718,7 @@ class QuotationService:
reject_reason=r.reject_reason,
reject_price=r.reject_price,
reject_delivery_type=r.reject_delivery_type,
email_sent_at=r.email_sent_at,
url=self._session_chat_url(r.session_id),
)
for r in rows
@@ -708,6 +726,106 @@ class QuotationService:
res.total = len(res.sessions)
return res
# ----- 협상 초청 메일 (수동 발송)
async def notify_sessions(self, qt_id: str) -> Res_NotifySessions:
"""[수동 발송] 견적의 '미발송' 세션(공급사 담당자)에게 협상 초청 메일을 일괄 발송한다.
대상 = email_sent_at IS NULL + 담당자 이메일 보유."""
res = Res_NotifySessions()
qt_uuid = uuid.UUID(qt_id)
err_type, quotation = await self._fetch(qt_uuid)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
err_type, rows = await DB_SESSION_MNG.execute_lambda(
sessions.DBType(),
DBWRType.DB_READ.value,
lambda s: self.quotation_crud.list_sessions_with_supplier(s, qt_uuid),
)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
# 행 언팩: (session, supplier_name, manager_email).
targets = [] # [(session, name, email)]
for r in rows:
sess, sp_name, email = r[0], r[1], r[2]
res.total += 1
if sess.email_sent_at is not None:
continue # 이미 발송됨 — 재발송은 행 단위 endpoint 로
if not email:
res.skipped += 1
continue
targets.append((sess, sp_name, email))
sent_ids = await self._send_invites(quotation, targets, res)
if sent_ids:
await self._mark_emailed(sent_ids)
return res
async def notify_session(self, session_id: str) -> Res_NotifySessions:
"""[수동 재발송] 단일 세션(공급사)에 초청 메일 발송(이미 보냈어도 강제 재발송)."""
res = Res_NotifySessions()
sess_uuid = uuid.UUID(session_id)
err_type, got = await DB_SESSION_MNG.execute_lambda(
sessions.DBType(),
DBWRType.DB_READ.value,
lambda s: self.quotation_crud.get_session_with_supplier(s, sess_uuid),
)
if err_type != ErrorType.SUCCESS or got is None:
res.result.SetResult(err_type if err_type != ErrorType.SUCCESS else ErrorType.QUOTATION_NOT_FOUND)
return res
sess, sp_name, email = got[0], got[1], got[2]
res.total = 1
err_type, quotation = await self._fetch(sess.quotation_id)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
if not email:
res.skipped = 1
return res
sent_ids = await self._send_invites(quotation, [(sess, sp_name, email)], res)
if sent_ids:
await self._mark_emailed(sent_ids)
return res
async def _send_invites(self, quotation, targets: list, res: Res_NotifySessions) -> list:
"""targets [(session, supplier_name, email)] 에 초청 메일 발송. res.sent/failed 를 채우고
성공한 session_id 목록을 반환. ACS/SMTP 미설정이면 첫 발송에서 중단(EMAIL_NOT_CONFIGURED)."""
sent_ids = []
for sess, sp_name, email in targets:
subject, html, text = build_invite_email(
supplier_name=sp_name or "",
quotation_name=quotation.name,
qt_number=quotation.number,
end_time=quotation.end_time,
chat_url=self._session_chat_url(sess.session_id),
)
try:
await send_email(email, subject, html, text)
sent_ids.append(sess.session_id)
res.sent += 1
except EmailUnavailable as e:
res.result.SetResult(ErrorType.EMAIL_NOT_CONFIGURED) # 발송 채널 없음 — 더 시도해도 무의미
res.msg = str(e)
break
except Exception as ex:
LOG.e_no_callstack(ex)
res.failed += 1
# 보낼 대상이 있었는데 전부 실패면 명시적 실패 코드(설정은 됐으나 발송 실패).
if res.sent == 0 and res.failed > 0 and res.result.success:
res.result.SetResult(ErrorType.EMAIL_SEND_FAILED)
return sent_ids
async def _mark_emailed(self, session_ids: list) -> None:
"""발송 성공 세션들의 email_sent_at 갱신(write 트랜잭션)."""
now = GTime.UTC()
await DB_SESSION_MNG.execute_lambda_run(
[sessions.DBType()],
[lambda s: self.quotation_crud.mark_sessions_emailed(s, session_ids, now)],
)
async def list_chats(self, session_id: str) -> Res_SessionChat:
res = Res_SessionChat()
sess_uuid = uuid.UUID(session_id)