[feat] negodata: 재협상 소유권 게이팅·처리담당자·상세 링크·재생성 타이틀·알림 토스트(읽음API)·재협상요청 표기·커스텀필드 select
This commit is contained in:
1 parent
d7c4e86f30
commit
51d07bb779
54 files changed
+2002
-58
No files matched your search
@@ -311,7 +311,7 @@ class QuotationService:
|
||||
)
|
||||
return res
|
||||
|
||||
async def regenerate_next_round(self, original_qt_id: uuid.UUID, supplier_ids: list) -> Res_CreateQuotation:
|
||||
async def regenerate_next_round(self, original_qt_id: uuid.UUID, supplier_ids: list, regen_label: Optional[str] = None) -> Res_CreateQuotation:
|
||||
"""[마감 후속] 결판 안 난 견적의 '다음 라운드'를 새로 만든다.
|
||||
|
||||
플로우:
|
||||
@@ -356,9 +356,10 @@ class QuotationService:
|
||||
)
|
||||
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)]
|
||||
# 이름 접미사: 재협상 승인 재생성은 '(재협상 요청 재생성)', 그 외 재생성은 '(N차)'.
|
||||
# 원래 이름의 기존 접미사(차수/재협상)는 떼고 새로 붙인다 + name 컬럼 50자 제한 보호.
|
||||
suffix = f" ({regen_label})" if regen_label else f" ({next_round}차)"
|
||||
base_name = re.sub(r"\s*\((?:\d+차|재협상[^)]*)\)\s*$", "", original.name or "")[: 50 - len(suffix)]
|
||||
return await self._build_quotation(
|
||||
user_id=str(original.user_id),
|
||||
qt_setting_id=original.qt_setting_id,
|
||||
@@ -697,7 +698,7 @@ class QuotationService:
|
||||
# 4) 전원 미응찰 → 개찰(미응찰).
|
||||
return await self._open(qt_uuid, original, CloseReason.OPEN_NOSHOW.value, "no_show")
|
||||
|
||||
async def regenerate_quotation(self, qt_id: str, company_id, supplier_ids: list, user_id=None, role=None) -> Res_CreateQuotation:
|
||||
async def regenerate_quotation(self, qt_id: str, company_id, supplier_ids: list, user_id=None, role=None, regen_label: Optional[str] = None) -> Res_CreateQuotation:
|
||||
"""[프론트] 마감된 견적을 골라 수동으로 다음 라운드를 생성한다.
|
||||
크론/수동마감의 자동 재생성과 달리 사유·체인 한도 판정 없이, 프론트가 고른 공급사로 바로 만든다.
|
||||
상품·기간·견적번호·카드버전은 원 견적에서 이어받는다(regenerate_next_round)."""
|
||||
@@ -733,7 +734,7 @@ class QuotationService:
|
||||
res.msg = "마지막 차수의 견적에서만 다음 라운드를 생성할 수 있습니다."
|
||||
return res
|
||||
|
||||
return await self.regenerate_next_round(qt_uuid, supplier_ids)
|
||||
return await self.regenerate_next_round(qt_uuid, supplier_ids, regen_label=regen_label)
|
||||
|
||||
async def stop_quotation(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_Quotation:
|
||||
"""[프론트] 수동 견적마감. 크론과 똑같은 마감 판정(close_and_decide)을 탄다
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.authz import is_owner_or_admin
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import sessions
|
||||
from common.enums import DBWRType, ErrorType, RenegotiationStatus
|
||||
from common.logger import LOG
|
||||
from common.models.gmodel import PageParams
|
||||
from common.utils.gtime import GTime
|
||||
from crud.renegotiation_crud import IRenegotiationCRUD, RenegotiationCRUD
|
||||
from router.v1.renegotiation.protocol import (
|
||||
RenegotiationData,
|
||||
Req_ApproveRenegotiation,
|
||||
Req_RejectRenegotiation,
|
||||
Res_RenegotiationDecision,
|
||||
Res_RenegotiationList,
|
||||
)
|
||||
from services.quotation_service import QuotationService
|
||||
|
||||
|
||||
class RenegotiationService:
|
||||
"""공급사 재협상 요청 심사(IMK #15).
|
||||
|
||||
요청 자체는 공급사 포털이 sessions.custom.renegotiation 에 기록한다. 여기서는 조회와 승인/반려만 한다.
|
||||
승인은 새 로직이 아니라 기존 수동 재생성(regenerate_quotation)을 그대로 호출한다 — 라운드 생성 규칙을 한 곳에 둔다.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
crud: IRenegotiationCRUD = Depends(RenegotiationCRUD),
|
||||
quotation_service: QuotationService = Depends(),
|
||||
):
|
||||
self.crud = crud
|
||||
self.quotation_service = quotation_service
|
||||
|
||||
async def list_requests(self, company_id: str, user_id: str, role: int, status: Optional[int], pg: PageParams) -> Res_RenegotiationList:
|
||||
res = Res_RenegotiationList(page=pg.page, size=pg.size)
|
||||
# 리스트는 회사 전체가 보인다(현황 공유). 처리 권한은 항목별 can_act 로 내려준다.
|
||||
err, rows, total = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.crud.list_requests(s, uuid.UUID(company_id), status, pg.skip, pg.size),
|
||||
)
|
||||
if err != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err)
|
||||
return res
|
||||
res.requests = [self._to_data(r, user_id, role) for r in rows]
|
||||
res.total = total
|
||||
return res
|
||||
|
||||
async def approve(self, company_id: str, user_id: str, role: int, session_id: str, req: Req_ApproveRenegotiation) -> Res_RenegotiationDecision:
|
||||
"""승인 → 원 견적의 다음 라운드 생성. 요청 공급사는 항상 포함한다."""
|
||||
res = Res_RenegotiationDecision()
|
||||
err, row, current = await self._load_pending(company_id, session_id)
|
||||
if err != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err)
|
||||
return res
|
||||
# 승인은 견적 작성자 본인 또는 최고관리자만 — 일반관리자는 남의 견적 처리 불가.
|
||||
if not is_owner_or_admin(row[13], user_id, role):
|
||||
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||
return res
|
||||
|
||||
supplier_ids = list({str(row[2]), *(req.supplier_ids or [])})
|
||||
created = await self.quotation_service.regenerate_quotation(
|
||||
str(row[1]), company_id, supplier_ids, user_id=user_id, role=role, regen_label="재협상 요청 재생성"
|
||||
)
|
||||
if created.result.success is False:
|
||||
res.result.SetResult(ErrorType.FAIL)
|
||||
res.msg = created.msg or "다음 라운드 생성에 실패했습니다."
|
||||
return res
|
||||
|
||||
patch = {
|
||||
**current,
|
||||
"status": RenegotiationStatus.APPROVED.value,
|
||||
"decided_by": user_id,
|
||||
"decided_at": GTime.UTC().isoformat(),
|
||||
"memo": (req.memo or "").strip() or None,
|
||||
"next_quotation_id": str(created.qt_id) if created.qt_id else None,
|
||||
}
|
||||
err = await self._save(session_id, patch)
|
||||
if err != ErrorType.SUCCESS:
|
||||
# 라운드는 이미 생겼는데 상태만 못 남긴 경우 — 로그로 남기고 성공으로 반환한다(재승인은 막힌다).
|
||||
LOG.e_no_callstack(f"[renego] 승인 상태 기록 실패 session={session_id} next_qt={created.qt_id}")
|
||||
|
||||
res.session_id = session_id
|
||||
res.status = RenegotiationStatus.APPROVED.value
|
||||
res.next_quotation_id = str(created.qt_id) if created.qt_id else None
|
||||
return res
|
||||
|
||||
async def reject(self, company_id: str, user_id: str, role: int, session_id: str, req: Req_RejectRenegotiation) -> Res_RenegotiationDecision:
|
||||
res = Res_RenegotiationDecision()
|
||||
err, row, current = await self._load_pending(company_id, session_id)
|
||||
if err != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err)
|
||||
return res
|
||||
# 반려도 승인과 같은 소유권 규칙 — 견적 작성자 본인 또는 최고관리자만.
|
||||
if not is_owner_or_admin(row[13], user_id, role):
|
||||
res.result.SetResult(ErrorType.ACCOUNT_FORBIDDEN)
|
||||
return res
|
||||
|
||||
patch = {
|
||||
**current,
|
||||
"status": RenegotiationStatus.REJECTED.value,
|
||||
"decided_by": user_id,
|
||||
"decided_at": GTime.UTC().isoformat(),
|
||||
"memo": (req.memo or "").strip() or None,
|
||||
}
|
||||
err = await self._save(session_id, patch)
|
||||
if err != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err)
|
||||
return res
|
||||
|
||||
res.session_id = session_id
|
||||
res.status = RenegotiationStatus.REJECTED.value
|
||||
return res
|
||||
|
||||
async def _load_pending(self, company_id: str, session_id: str):
|
||||
"""심사 대상(대기 중) 요청 로드. (err, row, renegotiation dict)"""
|
||||
try:
|
||||
sid = uuid.UUID(session_id)
|
||||
except (ValueError, TypeError):
|
||||
return ErrorType.INVALID_REQUEST_DATA, None, {}
|
||||
err, row = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.crud.get_request(s, uuid.UUID(company_id), sid),
|
||||
)
|
||||
if err != ErrorType.SUCCESS or row is None:
|
||||
return ErrorType.QUOTATION_NOT_FOUND, None, {}
|
||||
current = (row[5] or {}).get("renegotiation") or {}
|
||||
if current.get("status") != RenegotiationStatus.PENDING.value:
|
||||
return ErrorType.INVALID_REQUEST_DATA, None, {}
|
||||
return ErrorType.SUCCESS, row, current
|
||||
|
||||
async def _save(self, session_id: str, patch: dict) -> ErrorType:
|
||||
return await DB_SESSION_MNG.execute_lambda_run(
|
||||
[sessions.DBType()],
|
||||
[lambda s: self.crud.merge_custom(s, uuid.UUID(session_id), {"renegotiation": patch})],
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _to_data(row, user_id=None, role=None) -> RenegotiationData:
|
||||
r = (row[5] or {}).get("renegotiation") or {}
|
||||
return RenegotiationData(
|
||||
can_act=is_owner_or_admin(row[13], user_id, role) if user_id is not None else True,
|
||||
session_id=str(row[0]),
|
||||
quotation_id=str(row[1]),
|
||||
supplier_id=str(row[2]),
|
||||
target_price=row[3],
|
||||
bid_price=row[4],
|
||||
qt_number=row[6] or "",
|
||||
qt_round=row[7] or 0,
|
||||
qt_name=row[8] or "",
|
||||
close_reason=row[9],
|
||||
item_id=str(row[15]) if row[15] else "",
|
||||
item_name=row[10] or "",
|
||||
supplier_name=row[11] or "",
|
||||
owner_name=row[14] or "",
|
||||
status=r.get("status") or 0,
|
||||
reason=r.get("reason") or "",
|
||||
desired_price=r.get("desired_price"),
|
||||
requested_at=r.get("requested_at") or "",
|
||||
decided_at=r.get("decided_at"),
|
||||
decided_by_name=row[12] or None,
|
||||
memo=r.get("memo"),
|
||||
next_quotation_id=r.get("next_quotation_id"),
|
||||
)
|
||||
Reference in new issue
Block a user