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

@@ -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