Merge remote-tracking branch 'origin/main' into feat/source-state

This commit is contained in:
민헌 committed 2026-08-07 14:36:41 +09:00
commit 67612b477c
63 files changed
+2162 -491

No files matched your search

+22
View File
@@ -55,6 +55,10 @@ class IQuotationCRUD(ABC):
async def get_company_settings(self, cdb: AsyncSession, user_id) -> dict:
pass
@abstractmethod
async def get_company_brand(self, cdb: AsyncSession, user_id) -> Tuple[str, dict]:
pass
@abstractmethod
async def add_rows(self, cdb: AsyncSession, obj_list: list) -> ErrorType:
pass
@@ -408,6 +412,24 @@ class QuotationCRUD(IQuotationCRUD):
LOG.e_no_callstack(ex)
return {}
async def get_company_brand(self, cdb: AsyncSession, user_id):
# 이 유저가 속한 회사의 (이름, settings). 초청 메일 헤더 기본값이 회사명이라 이름까지 같이 읽는다.
try:
query = (
select(companies.name, companies.settings)
.select_from(users)
.join(companies, companies.company_id == users.company_id)
.where(users.user_id == user_id, companies.deleted == False) # noqa: E712
.limit(1)
)
err, rows = await DB_SESSION_MNG.execute(cdb, query)
if err != ErrorType.SUCCESS or not rows:
return "", {}
return rows[0][0] or "", rows[0][1] or {}
except Exception as ex:
LOG.e_no_callstack(ex)
return "", {}
async def get_item_companies(self, cdb: AsyncSession, item_ids) -> Tuple[ErrorType, dict]:
"""item_id -> company_id(소유 회사) 매핑. 앵커링 칸(회사×유형×가격구간) 해석 입력."""
try:
+1
View File
@@ -12,4 +12,5 @@ openpyxl
httpx
apscheduler>=3.10
azure-communication-email>=1.0 # 초청 메일 1순위 발송 채널(ACS Email)
aiohttp>=3.9 # azure aio 클라이언트(EmailClient.aio)의 HTTP 전송 계층
aiosmtplib>=3.0 # 초청 메일 폴백(SMTP)
@@ -70,3 +70,13 @@ class Req_UpdateCompanySettings(CompanySettingsProtocol):
class Res_CompanySettings(Res_WebPacketProtocol):
settings: Optional[dict] = None
class Req_PreviewInviteEmail(CompanySettingsProtocol):
# 저장 전 편집값으로 초청 메일을 렌더한다. settings.branding 서브키 중 email_* 만 쓴다.
branding: dict = {}
class Res_PreviewInviteEmail(Res_WebPacketProtocol):
subject: str = ""
html: str = ""
@@ -3,7 +3,7 @@ from fastapi import APIRouter, Depends
from common.models.gmodel import UserInfo
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse, RequireOwner
from services.company_settings_service import CompanySettingsService
from .protocol import Req_UpdateCompanySettings, Res_CompanySettings
from .protocol import Req_PreviewInviteEmail, Req_UpdateCompanySettings, Res_CompanySettings, Res_PreviewInviteEmail
# 회사별 커스터마이징 설정. 조회=로그인 유저 전원(앱 부팅 시 브랜딩/라벨 로드), 수정=최고관리자(OWNER) 전용.
router = APIRouter(prefix="/v1/company/settings", tags=["CompanySettings"], responses={404: {"description": "Not found"}})
@@ -19,3 +19,11 @@ async def update_settings(
req: Req_UpdateCompanySettings, service: CompanySettingsService = Depends(), owner: UserInfo = Depends(RequireOwner)
):
return RemoveNoneResponse(await service.update_settings(owner.company_id, req))
# 저장 전 편집값을 그대로 렌더한다(쓰기 없음) — 로그인만 요구. 회사명은 토큰의 회사로 채운다.
@router.post(path="/email-preview", response_model=Res_PreviewInviteEmail, summary="협상 초청 메일 미리보기")
async def preview_invite_email(
req: Req_PreviewInviteEmail, service: CompanySettingsService = Depends(), user: UserInfo = Depends(IsValidAccessToken)
):
return RemoveNoneResponse(await service.preview_invite_email(user.company_id, req))
@@ -3,6 +3,7 @@ from uuid import UUID
from fastapi import APIRouter, Depends, Query
from common.enums import UserRole
from common.models.gmodel import PageParams, UserInfo
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse
from services.quotation import QuotationService
@@ -42,7 +43,9 @@ async def list_quotations(
mine: bool = Query(False, description="내 견적만 보기(작성자=로그인 유저)"),
pg: PageParams = Depends(),
):
owner = user_info.user_id if mine else None
# 일반(USER)은 mine 파라미터와 무관하게 본인 견적만 — 타 담당자 견적 조회는 OWNER 이상만.
force_mine = (user_info.role or 0) < UserRole.OWNER.value
owner = user_info.user_id if (mine or force_mine) else None
return RemoveNoneResponse(await service.list_quotations(user_info.company_id, owner, search, status, type, start_from, start_to, pg))
@@ -84,12 +87,12 @@ async def regenerate_quotation(
# ----- 견적 상세 (FK로 연결된 하위 데이터 / 일부는 모델 미존재로 스텁) -----
@router.get(path="/{qt_id}/status", response_model=Res_QuotationStatus, summary="견적 상태 조회")
async def get_quotation_status(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.get_status(str(qt_id), user_info.company_id))
return RemoveNoneResponse(await service.get_status(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
@router.get(path="/{qt_id}/sessions", response_model=Res_QuotationSessions, summary="참여현황")
async def get_quotation_sessions(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.list_sessions(str(qt_id), user_info.company_id))
return RemoveNoneResponse(await service.list_sessions(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
@router.post(path="/{qt_id}/notify", response_model=Res_NotifySessions, summary="협상 초청 메일 발송")
@@ -99,12 +102,12 @@ async def notify_quotation(qt_id: UUID, service: QuotationService = Depends(), u
@router.get(path="/session/{session_id}/chat", response_model=Res_SessionChat, summary="채팅 상세")
async def get_session_chat(session_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.list_chats(str(session_id), user_info.company_id))
return RemoveNoneResponse(await service.list_chats(str(session_id), user_info.company_id, user_info.user_id, user_info.role))
@router.get(path="/session/{session_id}/target-breakdown", response_model=Res_TargetBreakdown, summary="세션 목표가 산정내역")
async def get_target_breakdown(session_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.get_target_breakdown(str(session_id), user_info.company_id))
return RemoveNoneResponse(await service.get_target_breakdown(str(session_id), user_info.company_id, user_info.user_id, user_info.role))
@router.post(path="/session/{session_id}/notify", response_model=Res_NotifySessions, summary="세션 초청 메일 재발송")
@@ -114,12 +117,12 @@ async def notify_session(session_id: UUID, service: QuotationService = Depends()
@router.get(path="/{qt_id}/result", response_model=Res_QuotationResult, summary="낙찰 결과")
async def get_quotation_result(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.get_result(str(qt_id), user_info.company_id))
return RemoveNoneResponse(await service.get_result(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
@router.get(path="/{qt_id}/cards", response_model=Res_QuotationCards, summary="견적 사용 카드")
async def get_quotation_cards(qt_id: UUID, service: QuotationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.list_cards(str(qt_id), user_info.company_id))
return RemoveNoneResponse(await service.list_cards(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
@router.delete(path="/delete/{qt_id}", response_model=Res_DeleteQuotation, summary="견적 삭제")
@@ -130,4 +133,4 @@ async def delete_quotation(qt_id: UUID, service: QuotationService = Depends(), u
# ----- 단건 조회 (정적/하위 경로 뒤에 선언) -----
@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)):
return RemoveNoneResponse(await service.get_quotation(str(qt_id), user_info.company_id))
return RemoveNoneResponse(await service.get_quotation(str(qt_id), user_info.company_id, user_info.user_id, user_info.role))
@@ -1,12 +1,21 @@
import uuid
from datetime import timedelta
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import companies
from common.enums import DBWRType, ErrorType
from common.utils.gtime import GTime
from config.server_configs import web_server_config
from crud.user_crud import IUserCRUD, UserCRUD
from router.v1.company.protocol import Req_UpdateCompanySettings, Res_CompanySettings
from router.v1.company.protocol import (
Req_PreviewInviteEmail,
Req_UpdateCompanySettings,
Res_CompanySettings,
Res_PreviewInviteEmail,
)
from services.email import build_invite_email
class CompanySettingsService:
@@ -43,3 +52,25 @@ class CompanySettingsService:
return res
res.settings = req.settings
return res
async def preview_invite_email(self, company_id: str, req: Req_PreviewInviteEmail) -> Res_PreviewInviteEmail:
"""저장 전 branding 편집값을 샘플 견적 데이터로 렌더한다(발송 없음).
실제 발송(services/quotation/invites.py)과 같은 build_invite_email 을 타므로 미리보기=실물.
회사명은 헤더 기본값이라 실발송과 동일하게 채워 보여준다."""
res = Res_PreviewInviteEmail()
_, company = await DB_SESSION_MNG.execute_lambda(
companies.DBType(),
DBWRType.DB_READ.value,
lambda s: self.user_crud.get_company(s, uuid.UUID(company_id)),
)
base = (web_server_config.nego_chat_url or "").rstrip("/")
res.subject, res.html, _ = build_invite_email(
supplier_name="샘플 협력사",
quotation_name="복사용지 A4 80g 외 2건",
qt_number="EST-2026-0801",
end_time=GTime.UTC() + timedelta(days=3),
chat_url=f"{base}/chat?session_id=00000000-0000-0000-0000-000000000000",
company_name=(company.name if company else "") or "",
branding=req.branding,
)
return res
+34 -4
View File
@@ -9,6 +9,7 @@ HTML 본문 템플릿: services/email_templates/*.html ($placeholder 치환).
"""
from __future__ import annotations
import re
from datetime import datetime
from email.message import EmailMessage
from html import escape
@@ -21,6 +22,12 @@ from config.server_configs import mail_config
_KST = ZoneInfo("Asia/Seoul")
# 회사 CI(settings.branding) 미설정 시 기본값 — 설정 화면 placeholder 와 같은 값이어야 한다.
# 색 기본값은 공급사 협상 포털(frontend --brand-600)과 동일 — 메일에서 포털로 이어지는 화면이 한 브랜드로 보이게.
_DEFAULT_EMAIL_COLOR = "#3182f6"
_DEFAULT_EMAIL_HEADER = "NEGODATA"
_DEFAULT_EMAIL_GREETING = "아래 견적 건의 협상에 참여해 주세요."
# HTML 본문은 코드에 박지 않고 파일에서 읽는다(모듈 로드 시 1회). $placeholder 는 string.Template 로 치환.
_TEMPLATE_DIR = Path(__file__).parent / "email_templates"
_INVITE_HTML = Template((_TEMPLATE_DIR / "invite_email.html").read_text(encoding="utf-8"))
@@ -96,17 +103,27 @@ def build_invite_email(
qt_number: str,
end_time: datetime | None,
chat_url: str,
email_header: str | None = None,
company_name: str = "",
branding: dict | None = None,
) -> tuple[str, str, str]:
"""협상 초청 메일 (제목/HTML/텍스트) 생성.
목표가·앵커링가는 협상 전략 값이라 메일에 담지 않는다(공급사에게 노출 금지).
공급사는 링크로 협상 화면에 진입해 입찰한다.
branding = companies.settings.branding — 헤더는 회사 CI(logo_url·service_name)를
그대로 쓴다(메일 전용 이중 설정 금지). 메일 전용 키는 인사 문구(email_greeting) 하나뿐.
헤더는 로고 있으면 로고, 없으면 service_name → 회사명(company_name) → NEGODATA 텍스트 —
공급사에겐 솔루션명보다 발주사가 보여야 한다. 색은 회사별 커스텀 없이 솔루션 기본색 고정.
레이아웃은 고정이고 값만 갈아끼우므로, 어떤 값을 넣어도 메일이 깨지지 않는다.
"""
b = branding or {}
sp = supplier_name or "협력사"
deadline = _fmt_deadline(end_time) or "미정"
subject = f"[협상 견적 {qt_number}] {quotation_name} — 협상 참여 요청"
header_name = (b.get("service_name") or "").strip() or (company_name or "").strip() or _DEFAULT_EMAIL_HEADER
greeting = (b.get("email_greeting") or "").strip() or _DEFAULT_EMAIL_GREETING
# HTML 본문은 invite_email.html 에서 읽어 치환. 값은 escape 해 HTML 인젝션 방지(견적명 등은 사용자 입력).
html = _INVITE_HTML.substitute(
supplier_name=escape(sp),
@@ -114,14 +131,27 @@ def build_invite_email(
qt_number=escape(qt_number),
deadline=escape(deadline),
chat_url=escape(chat_url),
email_header=escape(email_header or "NEGODATA"),
brand_color=_DEFAULT_EMAIL_COLOR,
header_content=_header_content(header_name, (b.get("logo_url") or "").strip()),
email_greeting=escape(greeting),
)
text = (
f"{sp} 담당자님, 아래 견적 건의 협상에 참여해 주세요.\n\n"
f"{sp} 담당자님, {greeting}\n\n"
f" - 견적명: {quotation_name}\n"
f" - 견적번호: {qt_number}\n"
f" - 협상 마감: {deadline}\n\n"
f"협상 참여 링크: {chat_url}\n"
f"협상 참여 링크: {chat_url}\n\n"
f"— negotium B2B 구매협상 솔루션\n"
)
return subject, html, text
def _header_content(name: str, logo_url: str) -> str:
"""헤더(흰 배경) 내용물 — 회사 CI 로고가 있으면 이미지(회사명은 alt 로), 없으면 회사명 텍스트. escape 는 여기서 끝낸다."""
if logo_url:
return (
f'<img src="{escape(logo_url)}" alt="{escape(name)}" height="32" '
f'style="display:block;height:32px;max-width:220px;border:0;margin:0 auto;" />'
)
return f'<span style="color:#191f28;font-size:18px;font-weight:800;letter-spacing:-0.4px;">{escape(name)}</span>'
@@ -1,37 +1,43 @@
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f4f5f7;margin:0;padding:24px 12px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f2f4f6;margin:0;padding:24px 12px;">
<tr>
<td align="center">
<table role="presentation" width="480" cellpadding="0" cellspacing="0" style="width:480px;max-width:480px;background-color:#ffffff;border-radius:12px;overflow:hidden;border:1px solid #e5e7eb;font-family:'Apple SD Gothic Neo',-apple-system,'Segoe UI',Roboto,'Malgun Gothic',sans-serif;">
<table role="presentation" width="480" cellpadding="0" cellspacing="0" style="width:480px;max-width:480px;background-color:#ffffff;border-radius:16px;overflow:hidden;border:1px solid #e5e8eb;font-family:Pretendard,'Apple SD Gothic Neo',-apple-system,'Segoe UI',Roboto,'Malgun Gothic',sans-serif;">
<!-- 헤더 바 -->
<!-- 브랜드 액센트 — 회사 CI 색(primary_color) -->
<tr>
<td style="background-color:#2563eb;padding:18px 28px;">
<span style="color:#ffffff;font-size:16px;font-weight:700;letter-spacing:1px;">$email_header</span>
<td height="4" bgcolor="$brand_color" style="height:4px;font-size:0;line-height:0;">&nbsp;</td>
</tr>
<!-- 헤더 — 회사 CI(로고 있으면 로고, 없으면 회사명) + 솔루션 태그라인. 챗 포털 로그인 락업과 같은 구성 -->
<tr>
<td align="center" style="padding:30px 28px 0 28px;">
$header_content
<p style="margin:10px 0 0 0;font-size:12px;color:#8b95a1;">negotium B2B 구매협상 솔루션</p>
</td>
</tr>
<!-- 본문 -->
<tr>
<td style="padding:32px 28px 4px 28px;">
<h1 style="margin:0 0 10px 0;font-size:20px;font-weight:700;color:#111827;">협상 참여 요청</h1>
<p style="margin:0 0 24px 0;font-size:14px;line-height:1.7;color:#4b5563;">
<strong style="color:#111827;">$supplier_name</strong> 담당자님,<br>
아래 견적 건의 협상에 참여해 주세요.
<h1 style="margin:0 0 10px 0;font-size:20px;font-weight:700;letter-spacing:-0.4px;color:#191f28;">협상 참여 요청</h1>
<p style="margin:0 0 24px 0;font-size:14px;line-height:1.7;color:#4e5968;">
<strong style="color:#191f28;">$supplier_name</strong> 담당자님,<br>
$email_greeting
</p>
<!-- 견적 정보 카드 -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f9fafb;border:1px solid #eef0f3;border-radius:10px;margin-bottom:28px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f9fafb;border:1px solid #e5e8eb;border-radius:12px;margin-bottom:28px;">
<tr>
<td style="padding:14px 16px;font-size:13px;color:#6b7280;width:88px;">견적명</td>
<td style="padding:14px 16px;font-size:13px;color:#111827;font-weight:600;text-align:right;">$quotation_name</td>
<td style="padding:14px 16px;font-size:13px;color:#8b95a1;width:88px;">견적명</td>
<td style="padding:14px 16px;font-size:13px;color:#191f28;font-weight:600;text-align:right;">$quotation_name</td>
</tr>
<tr>
<td style="padding:14px 16px;font-size:13px;color:#6b7280;border-top:1px solid #eef0f3;">견적번호</td>
<td style="padding:14px 16px;font-size:13px;color:#374151;text-align:right;border-top:1px solid #eef0f3;">$qt_number</td>
<td style="padding:14px 16px;font-size:13px;color:#8b95a1;border-top:1px solid #f2f4f6;">견적번호</td>
<td style="padding:14px 16px;font-size:13px;color:#333d4b;text-align:right;border-top:1px solid #f2f4f6;">$qt_number</td>
</tr>
<tr>
<td style="padding:14px 16px;font-size:13px;color:#6b7280;border-top:1px solid #eef0f3;">협상 마감</td>
<td style="padding:14px 16px;font-size:13px;color:#dc2626;font-weight:700;text-align:right;border-top:1px solid #eef0f3;">$deadline</td>
<td style="padding:14px 16px;font-size:13px;color:#8b95a1;border-top:1px solid #f2f4f6;">협상 마감</td>
<td style="padding:14px 16px;font-size:13px;color:#e71c3b;font-weight:700;text-align:right;border-top:1px solid #f2f4f6;">$deadline</td>
</tr>
</table>
@@ -41,9 +47,8 @@
<td align="center">
<table role="presentation" cellpadding="0" cellspacing="0">
<tr>
<td align="center" bgcolor="#2563eb" style="border-radius:8px;">
<!-- TODO: 세션별 협상링크 연결 시 href 를 $$chat_url 로 복원 -->
<a href="https://nego.o2o.kr" style="display:inline-block;padding:14px 34px;font-size:15px;font-weight:700;color:#ffffff;text-decoration:none;border-radius:8px;">협상 참여하기 →</a>
<td align="center" bgcolor="$brand_color" style="border-radius:12px;">
<a href="$chat_url" style="display:inline-block;padding:14px 34px;font-size:15px;font-weight:700;color:#ffffff;text-decoration:none;border-radius:12px;">협상 참여하기 →</a>
</td>
</tr>
</table>
@@ -56,15 +61,14 @@
<!-- 푸터 -->
<tr>
<td style="padding:18px 28px 26px 28px;">
<p style="margin:0;font-size:11px;line-height:1.7;color:#9ca3af;border-top:1px solid #f0f1f3;padding-top:16px;">
<p style="margin:0;font-size:11px;line-height:1.7;color:#8b95a1;border-top:1px solid #f2f4f6;padding-top:16px;">
버튼이 열리지 않으면 아래 링크를 복사해 접속하세요.<br>
<a href="https://nego.o2o.kr" style="color:#6b7280;word-break:break-all;">https://nego.o2o.kr</a>
<a href="$chat_url" style="color:#4e5968;word-break:break-all;">$chat_url</a>
</p>
</td>
</tr>
</table>
<p style="margin:16px 0 0 0;font-size:11px;color:#b0b4bb;font-family:sans-serif;">본 메일은 협상 견적 시스템에서 자동 발송되었습니다.</p>
</td>
</tr>
</table>
@@ -95,12 +95,12 @@ class InvitesMixin:
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)."""
# 회사 브랜딩(초청 메일 헤더) 한 번 조회 — 견적당 동일.
settings = await DB_SESSION_MNG.execute_lambda(
# 회사명·브랜딩(메일 헤더·색·로고·문구) 한 번 조회 — 견적당 동일. 회사명은 헤더 기본값.
company_name, settings = await DB_SESSION_MNG.execute_lambda(
quotations.DBType(), DBWRType.DB_READ.value,
lambda s: self.quotation_crud.get_company_settings(s, quotation.user_id),
lambda s: self.quotation_crud.get_company_brand(s, quotation.user_id),
)
email_header = (settings.get("branding") or {}).get("email_header")
branding = settings.get("branding") or {}
sent_ids = []
for sess, sp_name, email in targets:
subject, html, text = build_invite_email(
@@ -109,7 +109,8 @@ class InvitesMixin:
qt_number=quotation.number,
end_time=quotation.end_time,
chat_url=self._session_chat_url(sess.session_id),
email_header=email_header,
company_name=company_name,
branding=branding,
)
try:
await send_email(email, subject, html, text)
@@ -180,7 +180,7 @@ class PricingMixin:
anchors[(iid, sid)] = (value, ap)
return anchors
async def get_target_breakdown(self, session_id: str, company_id=None) -> Res_TargetBreakdown:
async def get_target_breakdown(self, session_id: str, company_id=None, user_id=None, role=None) -> Res_TargetBreakdown:
"""목표가 모달의 산정내역 응답.
저장된 목표가·앵커링가는 그대로 내려주고, 후보 목록은 _candidates 로 다시 계산한다.
@@ -195,7 +195,7 @@ class PricingMixin:
res.result.SetResult(err_type if err_type != ErrorType.SUCCESS else ErrorType.QUOTATION_NOT_FOUND)
return res
sess = got[0]
err_type, quotation = await self._fetch(sess.quotation_id, company_id)
err_type, quotation = await self._fetch(sess.quotation_id, company_id, user_id, role)
if err_type != ErrorType.SUCCESS or quotation is None:
res.result.SetResult(err_type if err_type != ErrorType.SUCCESS else ErrorType.QUOTATION_NOT_FOUND)
return res
+50 -14
View File
@@ -23,9 +23,11 @@ from router.v1.quotation.protocol import (
class QueriesMixin:
async def _fetch(self, qt_id: uuid.UUID, company_id=None):
async def _fetch(self, qt_id: uuid.UUID, company_id=None, user_id=None, role=None):
"""견적 단건 조회. (ErrorType, quotation|None) 반환.
company_id 가 주어지면 회사 스코프(작성자 회사) 가드 — 남의 회사 견적은 NOT_FOUND. 내부/스케줄러 호출은 None."""
company_id 가 주어지면 회사 스코프(작성자 회사) 가드 — 남의 회사 견적은 NOT_FOUND. 내부/스케줄러 호출은 None.
user_id 가 주어지면 조회 게이팅 — 일반(USER)은 본인 견적만, 남의 견적은 존재를 숨긴다(NOT_FOUND).
변경 액션(삭제·마감 등)은 안내 문구가 필요해 user_id 없이 부르고 각자 ACCOUNT_FORBIDDEN 게이트를 탄다."""
err_type, quotation = await DB_SESSION_MNG.execute_lambda(
quotations.DBType(),
DBWRType.DB_READ.value,
@@ -33,6 +35,8 @@ class QueriesMixin:
)
if err_type != ErrorType.SUCCESS or quotation is None:
return ErrorType.QUOTATION_NOT_FOUND, None
if user_id is not None and not is_owner_or_admin(quotation.user_id, user_id, role):
return ErrorType.QUOTATION_NOT_FOUND, None
return ErrorType.SUCCESS, quotation
async def list_quotations(self, company_id, owner, search, status, type_, start_from, start_to, pg: PageParams) -> Res_QuotationList:
@@ -90,9 +94,9 @@ class QueriesMixin:
res.total = total
return res
async def get_quotation(self, qt_id: str, company_id=None) -> Res_Quotation:
async def get_quotation(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_Quotation:
res = Res_Quotation()
err_type, quotation = await self._fetch(uuid.UUID(qt_id), company_id)
err_type, quotation = await self._fetch(uuid.UUID(qt_id), company_id, user_id, role)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
@@ -121,9 +125,9 @@ class QueriesMixin:
res.result.SetResult(err_type)
return res
async def get_status(self, qt_id: str, company_id=None) -> Res_QuotationStatus:
async def get_status(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_QuotationStatus:
res = Res_QuotationStatus()
err_type, quotation = await self._fetch(uuid.UUID(qt_id), company_id)
err_type, quotation = await self._fetch(uuid.UUID(qt_id), company_id, user_id, role)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
@@ -132,9 +136,9 @@ class QueriesMixin:
res.message = "ok"
return res
async def get_result(self, qt_id: str, company_id=None) -> Res_QuotationResult:
async def get_result(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_QuotationResult:
res = Res_QuotationResult()
err_type, quotation = await self._fetch(uuid.UUID(qt_id), company_id)
err_type, quotation = await self._fetch(uuid.UUID(qt_id), company_id, user_id, role)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
@@ -147,10 +151,10 @@ class QueriesMixin:
res.result_count = 0
return res
async def list_sessions(self, qt_id: str, company_id=None) -> Res_QuotationSessions:
async def list_sessions(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_QuotationSessions:
res = Res_QuotationSessions()
qt_uuid = uuid.UUID(qt_id)
err_type, quotation = await self._fetch(qt_uuid, company_id)
err_type, quotation = await self._fetch(qt_uuid, company_id, user_id, role)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
@@ -193,7 +197,7 @@ class QueriesMixin:
res.total = len(res.sessions)
return res
async def list_chats(self, session_id: str, company_id=None) -> Res_SessionChat:
async def list_chats(self, session_id: str, company_id=None, user_id=None, role=None) -> Res_SessionChat:
res = Res_SessionChat()
sess_uuid = uuid.UUID(session_id)
res.session_id = sess_uuid
@@ -208,7 +212,7 @@ class QueriesMixin:
if g_err != ErrorType.SUCCESS or got is None:
res.result.SetResult(g_err if g_err != ErrorType.SUCCESS else ErrorType.QUOTATION_NOT_FOUND)
return res
guard_err, _ = await self._fetch(got[0].quotation_id, company_id)
guard_err, _ = await self._fetch(got[0].quotation_id, company_id, user_id, role)
if guard_err != ErrorType.SUCCESS:
res.result.SetResult(guard_err)
return res
@@ -242,10 +246,10 @@ class QueriesMixin:
]
return res
async def list_cards(self, qt_id: str, company_id=None) -> Res_QuotationCards:
async def list_cards(self, qt_id: str, company_id=None, user_id=None, role=None) -> Res_QuotationCards:
res = Res_QuotationCards()
qt_uuid = uuid.UUID(qt_id)
err_type, quotation = await self._fetch(qt_uuid, company_id)
err_type, quotation = await self._fetch(qt_uuid, company_id, user_id, role)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
@@ -280,5 +284,37 @@ class QueriesMixin:
memo=memo,
)
)
# 봇은 버전 카드셋 밖에서도 카드를 고르므로(RL 런타임 미제한) 채팅의 사용 카드(chats.card_id)가
# 버전 목록에 없으면 화면·JSON 내보내기의 카드 매칭이 전부 null 이 된다 → 실사용 카드를 합쳐 내려준다.
# 부가 조회라 실패 시 버전 카드만으로 응답한다(목록의 참여수 집계와 같은 best-effort 패턴).
used_err, used_rows = await DB_SESSION_MNG.execute_lambda(
chats.DBType(),
DBWRType.DB_READ.value,
lambda s: self.quotation_crud.list_used_cards(s, qt_uuid),
)
if used_err == ErrorType.SUCCESS:
seen = {c.session_card_id for c in cards}
for chat, card_pk, number, name, script, edit, condition, memo in used_rows:
# card_pk 미해석(카드 삭제 등)이면 건너뛴다 — 매칭할 카탈로그 정보가 없다.
if card_pk is None or card_pk in seen:
continue
seen.add(card_pk)
is_wild = chat.card_type == 2
cards.append(
QuotationCardData(
session_card_id=card_pk,
qt_id=quotation.qt_id,
nego_card_id=None if is_wild else card_pk,
wild_card_id=card_pk if is_wild else None,
type=chat.card_type,
number=number,
name=name,
script=script,
edit_script=edit,
condition=condition,
memo=memo,
)
)
res.cards = cards
return res
@@ -0,0 +1,74 @@
"""협상 초청 메일 미리보기(/v1/company/settings/email-preview) 테스트 — 회사 CI 슬롯 렌더 확인.
- 실제 발송(services/quotation/invites.py)과 같은 build_invite_email 을 타므로 미리보기 검증 = 발송물 검증.
- 헤더는 회사 CI(logo_url·service_name)를 그대로 쓰고 색은 솔루션 고정 — 메일 전용 설정은 인사 문구뿐.
- 색은 hex 만 통과한다(이상값이 style 을 깨거나 CSS 주입되는 것 방지).
"""
PREVIEW_URL = "/v1/company/settings/email-preview"
async def test_preview_requires_login(client):
"""검증: 토큰 없이 미리보기 호출.
기대결과: HTTP 401/403 으로 거부(로그인 필수)."""
r = await client.post(PREVIEW_URL, json={"branding": {}})
assert r.status_code in (401, 403)
async def test_preview_default_branding(client, auth_headers):
"""검증: branding 비운 채 미리보기 호출.
기대결과: 헤더는 회사명 텍스트(테스트사, NEGODATA 아님)·기본색(#3182f6)·기본 인사 문구로 렌더되고 제목이 채워진다."""
h = await auth_headers("previewer1")
r = await client.post(PREVIEW_URL, json={"branding": {}}, headers=h)
assert r.status_code == 200
body = r.json()
assert "협상 참여 요청" in body["subject"]
html = body["html"]
assert "테스트사" in html # conftest company_id 픽스처의 회사명
assert "NEGODATA" not in html
assert "#3182f6" in html
assert "아래 견적 건의 협상에 참여해 주세요." in html
assert "negotium B2B 구매협상 솔루션" in html # 발주사 CI 아래 솔루션 태그라인(고정)
async def test_preview_ci_branding(client, auth_headers):
"""검증: 회사 CI(서비스명·로고)와 인사 문구를 채워 미리보기 호출(브랜드 색을 넣어도 무시).
기대결과: 헤더는 로고 이미지(서비스명은 alt), 색은 회사 값과 무관하게 솔루션 기본색으로 렌더."""
h = await auth_headers("previewer2")
branding = {
"service_name": "아이좋아네고",
"logo_url": "https://cdn.example.com/ci.png",
"primary_color": "#f551a0", # 제거된 기능 — 값을 보내도 반영되지 않아야 한다
"email_greeting": "협상에 초대합니다.",
}
r = await client.post(PREVIEW_URL, json={"branding": branding}, headers=h)
assert r.status_code == 200
html = r.json()["html"]
assert '<img src="https://cdn.example.com/ci.png"' in html
assert 'alt="아이좋아네고"' in html
assert "#f551a0" not in html
assert "#3182f6" in html
assert "협상에 초대합니다." in html
async def test_preview_service_name_without_logo(client, auth_headers):
"""검증: 로고 없이 서비스명만 채워 미리보기 호출.
기대결과: 헤더는 서비스명 텍스트로 렌더되고 img 태그는 없다."""
h = await auth_headers("previewer3")
r = await client.post(PREVIEW_URL, json={"branding": {"service_name": "IMK 구매협상"}}, headers=h)
assert r.status_code == 200
html = r.json()["html"]
assert "IMK 구매협상" in html
assert "<img" not in html
async def test_preview_bad_color_falls_back(client, auth_headers):
"""검증: hex 가 아닌 primary_color(CSS 주입 꼴)로 미리보기 호출.
기대결과: 입력값은 HTML 에 실리지 않고 기본색(#3182f6)으로 렌더된다."""
h = await auth_headers("previewer4")
bad = "red;background-image:url(https://evil)"
r = await client.post(PREVIEW_URL, json={"branding": {"primary_color": bad}}, headers=h)
assert r.status_code == 200
html = r.json()["html"]
assert bad not in html
assert "#3182f6" in html
@@ -0,0 +1,142 @@
"""견적 조회 게이팅 + 사용 카드 매칭 보강.
- 조회 게이팅: 일반(USER)은 본인 견적만 — 목록은 서버가 강제 필터, 상세는 남의 견적의 존재 자체를
숨긴다(QUOTATION_NOT_FOUND). OWNER 이상은 회사 전체 조회. 판정은 common.authz.is_owner_or_admin 공용.
- 사용 카드: 봇은 버전 카드셋 밖에서도 카드를 고르므로(RL 런타임 미제한) 버전 목록에 없는
실사용 카드(chats.card_id)도 /cards 응답에 합쳐 내려준다 — 협상로그 화면·JSON 내보내기의
카드 매칭 실패(card=null) 복구.
"""
import uuid
from datetime import datetime
from sqlalchemy import text
from common.enums import ChatSender, ErrorType, QuotationStatus, QuotationType, SessionStatus, UserRole
from crud.quotation_crud import QuotationCRUD
from services.quotation import QuotationService
PAST = datetime(2020, 1, 1)
# ===== 목록 — HTTP e2e: 같은 회사, 담당자 2명 =====
async def test_list_forced_to_own_for_user_role(client, auth_headers, db_engine):
"""검증: 같은 회사 담당자 A/B 가 견적을 하나씩 가진 상태에서 일반유저 B 가 목록 조회(mine 미지정).
기대결과: B 본인 견적만 내려온다 — 서버가 mine 을 강제해 A 견적은 목록에서 제외."""
ha = await auth_headers("read_user_a")
hb = await auth_headers("read_user_b")
qt_a = await _seed_quotation(db_engine, user_id=await _user_id(db_engine, "read_user_a"), number="READ-A")
await _seed_quotation(db_engine, user_id=await _user_id(db_engine, "read_user_b"), number="READ-B")
numbers = [q["number"] for q in (await client.get("/v1/quotation/list", headers=hb)).json()["quotations"]]
assert numbers == ["READ-B"]
# 소유자 A 본인은 당연히 자기 견적을 본다(대조군)
assert (await client.get(f"/v1/quotation/{qt_a}", headers=ha)).json()["result"]["success"] is True
async def test_list_full_company_for_owner_role(client, auth_headers, db_engine):
"""검증: 최고관리자(OWNER)가 목록 조회(mine 미지정).
기대결과: 회사 전체 — 다른 담당자들 견적까지 모두 내려온다."""
await auth_headers("read_user_c")
hadmin = await auth_headers("read_admin", role=UserRole.OWNER.value)
await _seed_quotation(db_engine, user_id=await _user_id(db_engine, "read_user_c"), number="READ-C")
await _seed_quotation(db_engine, user_id=await _user_id(db_engine, "read_admin"), number="READ-D")
numbers = {q["number"] for q in (await client.get("/v1/quotation/list", headers=hadmin)).json()["quotations"]}
assert numbers == {"READ-C", "READ-D"}
# ===== 상세 — HTTP e2e: 남의 견적 =====
async def test_detail_hidden_from_other_user(client, auth_headers, db_engine):
"""검증: A 의 견적 상세(/{qt_id}·/sessions·/cards)를 같은 회사 일반유저 B 가 조회.
기대결과: 모두 거부 — 존재를 숨기는 QUOTATION_NOT_FOUND(권한 코드가 아니라 미존재로 응답)."""
await auth_headers("read_owner")
hb = await auth_headers("read_other")
qt = await _seed_quotation(db_engine, user_id=await _user_id(db_engine, "read_owner"), number="READ-HIDE")
for path in (f"/v1/quotation/{qt}", f"/v1/quotation/{qt}/sessions", f"/v1/quotation/{qt}/cards"):
body = (await client.get(path, headers=hb)).json()
assert body["result"]["success"] is False
assert body["result"]["code"] == ErrorType.QUOTATION_NOT_FOUND.value
async def test_detail_visible_to_owner_role(client, auth_headers, db_engine):
"""검증: A 의 견적 상세를 같은 회사 최고관리자(OWNER)가 조회.
기대결과: 성공 — 소유자가 아니어도 OWNER 는 조회 가능."""
await auth_headers("read_owner2")
hadmin = await auth_headers("read_admin2", role=UserRole.OWNER.value)
qt = await _seed_quotation(db_engine, user_id=await _user_id(db_engine, "read_owner2"), number="READ-SHOW")
body = (await client.get(f"/v1/quotation/{qt}", headers=hadmin)).json()
assert body["result"]["success"] is True
assert body["quotation"]["number"] == "READ-SHOW"
# ===== 사용 카드 — 서비스 직접: 버전 밖 카드 매칭 =====
async def test_list_cards_includes_used_card_outside_version(db_engine):
"""검증: 버전 카드셋엔 없는 카드를 채팅에서 사용(chats.card_used_yn=true, card_id=카드 PK)한 견적의 카드 조회.
기대결과: 응답에 그 카드가 session_card_id=카드 PK 로 포함 — 화면·내보내기 매칭이 성립한다."""
user = uuid.uuid4()
qt = await _seed_quotation(db_engine, user_id=user, number="CARD-USED")
card = uuid.uuid4()
session = uuid.uuid4()
async with db_engine.begin() as conn:
await conn.execute(
text("INSERT INTO nego_cards (nego_card_id, user_id, name, number, script, usage_type) "
"VALUES (:c, :u, '실사용카드', 'NGC-X1', '멘트', 1)"),
{"c": card, "u": user},
)
await conn.execute(
text(
"INSERT INTO sessions "
"(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, "
" target_price, status, end_time) VALUES "
"(:sid, :qt, :item, :sup, 'CARD-USED', 1, :type, 0, :st, :t)"
),
{"sid": session, "qt": qt, "item": uuid.uuid4(), "sup": uuid.uuid4(),
"type": QuotationType.REQUOTE.value, "st": SessionStatus.DONE.value, "t": PAST},
)
await conn.execute(
text(
"INSERT INTO chats (chat_id, session_id, card_id, seq, sender, target_price, card_used_yn, card_type) "
"VALUES (:cid, :sid, :card, 1, :sender, 0, true, 1)"
),
{"cid": uuid.uuid4(), "sid": session, "card": card, "sender": ChatSender.BOT.value},
)
res = await QuotationService(QuotationCRUD()).list_cards(str(qt))
assert res.result.success is True
got = {str(c.session_card_id): c for c in res.cards}
assert str(card) in got
assert got[str(card)].number == "NGC-X1"
assert got[str(card)].nego_card_id == card # nego 카드로 분류(type=1)
# ===== 헬퍼 =====
async def _user_id(engine, login_id) -> uuid.UUID:
async with engine.begin() as conn:
return (await conn.execute(
text("SELECT user_id FROM users WHERE id = :i"), {"i": login_id}
)).scalar_one()
async def _seed_quotation(engine, *, user_id, number):
"""견적 1건 시드(조회 게이팅 확인용 — 상태는 무관하므로 CLOSED 고정)."""
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) VALUES "
"(:qt_id, :user_id, :qt_setting_id, :version_id, '견적', :number, :type, :status, "
" 1, 0, :t, :t, 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": QuotationStatus.CLOSED.value, "t": PAST,
},
)
return qt_id