Merge remote-tracking branch 'origin/main' into feat/source-state
This commit is contained in:
commit
67612b477c
63 files changed
+2162
-491
No files matched your search
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -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;"> </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
|
||||
|
||||
@@ -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
|
||||
Binary file not shown.
@@ -25,8 +25,10 @@ import type {
|
||||
|
||||
import type {
|
||||
HTTPValidationError,
|
||||
ReqPreviewInviteEmail,
|
||||
ReqUpdateCompanySettings,
|
||||
ResCompanySettings
|
||||
ResCompanySettings,
|
||||
ResPreviewInviteEmail
|
||||
} from '.././model';
|
||||
|
||||
import { customFetch } from '../../mutator/custom-fetch';
|
||||
@@ -191,4 +193,68 @@ export const useUpdateSettings = <TError = void | HTTPValidationError,
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
}
|
||||
/**
|
||||
* @summary 협상 초청 메일 미리보기
|
||||
*/
|
||||
export const previewInviteEmail = (
|
||||
reqPreviewInviteEmail: ReqPreviewInviteEmail,
|
||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
||||
) => {
|
||||
|
||||
|
||||
return customFetch<ResPreviewInviteEmail>(
|
||||
{url: `/v1/company/settings/email-preview`, method: 'POST',
|
||||
headers: {'Content-Type': 'application/json', },
|
||||
data: reqPreviewInviteEmail, signal
|
||||
},
|
||||
options);
|
||||
}
|
||||
|
||||
|
||||
|
||||
export const getPreviewInviteEmailMutationOptions = <TError = void | HTTPValidationError,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof previewInviteEmail>>, TError,{data: ReqPreviewInviteEmail}, TContext>, request?: SecondParameter<typeof customFetch>}
|
||||
): UseMutationOptions<Awaited<ReturnType<typeof previewInviteEmail>>, TError,{data: ReqPreviewInviteEmail}, TContext> => {
|
||||
|
||||
const mutationKey = ['previewInviteEmail'];
|
||||
const {mutation: mutationOptions, request: requestOptions} = options ?
|
||||
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
|
||||
options
|
||||
: {...options, mutation: {...options.mutation, mutationKey}}
|
||||
: {mutation: { mutationKey, }, request: undefined};
|
||||
|
||||
|
||||
|
||||
|
||||
const mutationFn: MutationFunction<Awaited<ReturnType<typeof previewInviteEmail>>, {data: ReqPreviewInviteEmail}> = (props) => {
|
||||
const {data} = props ?? {};
|
||||
|
||||
return previewInviteEmail(data,requestOptions)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
return { mutationFn, ...mutationOptions }}
|
||||
|
||||
export type PreviewInviteEmailMutationResult = NonNullable<Awaited<ReturnType<typeof previewInviteEmail>>>
|
||||
export type PreviewInviteEmailMutationBody = ReqPreviewInviteEmail
|
||||
export type PreviewInviteEmailMutationError = void | HTTPValidationError
|
||||
|
||||
/**
|
||||
* @summary 협상 초청 메일 미리보기
|
||||
*/
|
||||
export const usePreviewInviteEmail = <TError = void | HTTPValidationError,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof previewInviteEmail>>, TError,{data: ReqPreviewInviteEmail}, TContext>, request?: SecondParameter<typeof customFetch>}
|
||||
, queryClient?: QueryClient): UseMutationResult<
|
||||
Awaited<ReturnType<typeof previewInviteEmail>>,
|
||||
TError,
|
||||
{data: ReqPreviewInviteEmail},
|
||||
TContext
|
||||
> => {
|
||||
|
||||
const mutationOptions = getPreviewInviteEmailMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
}
|
||||
|
||||
@@ -203,6 +203,8 @@ export * from './reqCreateSupplierManagerEmail';
|
||||
export * from './reqCreateSupplierManagerName';
|
||||
export * from './reqCreateSupplierTotalRevenue';
|
||||
export * from './reqLogin';
|
||||
export * from './reqPreviewInviteEmail';
|
||||
export * from './reqPreviewInviteEmailBranding';
|
||||
export * from './reqRegenerateQuotation';
|
||||
export * from './reqRegenerateQuotationCardIds';
|
||||
export * from './reqRegenerateQuotationDoneCeilingRate';
|
||||
@@ -344,6 +346,8 @@ export * from './resNotificationRead';
|
||||
export * from './resNotificationReadMsg';
|
||||
export * from './resNotifySessions';
|
||||
export * from './resNotifySessionsMsg';
|
||||
export * from './resPreviewInviteEmail';
|
||||
export * from './resPreviewInviteEmailMsg';
|
||||
export * from './resQuotation';
|
||||
export * from './resQuotationCards';
|
||||
export * from './resQuotationCardsMsg';
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Negodata Api Server
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import type { ReqPreviewInviteEmailBranding } from './reqPreviewInviteEmailBranding';
|
||||
|
||||
export interface ReqPreviewInviteEmail {
|
||||
branding?: ReqPreviewInviteEmailBranding;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Negodata Api Server
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type ReqPreviewInviteEmailBranding = { [key: string]: unknown };
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Negodata Api Server
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import type { ErrorInfo } from './errorInfo';
|
||||
import type { ResPreviewInviteEmailMsg } from './resPreviewInviteEmailMsg';
|
||||
|
||||
export interface ResPreviewInviteEmail {
|
||||
result?: ErrorInfo;
|
||||
msg?: ResPreviewInviteEmailMsg;
|
||||
subject?: string;
|
||||
html?: string;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Negodata Api Server
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type ResPreviewInviteEmailMsg = string | null;
|
||||
@@ -21,18 +21,6 @@ import NotificationsPage from '../pages/notifications';
|
||||
import OnboardingPage from '../pages/onboarding';
|
||||
|
||||
export const router = createBrowserRouter([
|
||||
// dev 전용: import.meta.env.DEV가 false인 프로덕션 빌드에선 이 배열 항목과
|
||||
// 내부 import()가 통째로 트리셰이킹되어 번들/라우트에 포함되지 않는다.
|
||||
...(import.meta.env.DEV
|
||||
? [
|
||||
{
|
||||
path: 'dev/design',
|
||||
lazy: async () => ({
|
||||
Component: (await import('../pages/dev/dev-design')).default,
|
||||
}),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
index: true,
|
||||
loader: () => redirect('/dashboard'),
|
||||
|
||||
@@ -180,11 +180,7 @@ export default function Layout({ children, currentPage, setPage, onLogout }: Lay
|
||||
{branding.logoUrl ? (
|
||||
<img src={branding.logoUrl} alt={branding.serviceName} className="h-4 max-w-24 object-contain" />
|
||||
) : (
|
||||
<span
|
||||
aria-hidden
|
||||
className="size-4 rounded-[5px] bg-primary"
|
||||
style={branding.primaryColor ? { backgroundColor: branding.primaryColor } : undefined}
|
||||
/>
|
||||
<span aria-hidden className="size-4 rounded-[5px] bg-primary" />
|
||||
)}
|
||||
{branding.serviceName}
|
||||
</Typography>
|
||||
@@ -291,7 +287,9 @@ export default function Layout({ children, currentPage, setPage, onLogout }: Lay
|
||||
{/* Main Container Wrapper */}
|
||||
<div
|
||||
className={cn(
|
||||
'flex-1 flex flex-col transition-all duration-300',
|
||||
// min-w-0: flex 아이템은 기본 min-width:auto 라 넓은 콘텐츠(다컬럼 표·차트)가
|
||||
// 래퍼를 뷰포트 밖으로 밀어낸다 — 이걸 끊어야 표 내부 overflow-x-auto 가 스크롤로 받는다.
|
||||
'flex-1 min-w-0 flex flex-col transition-all duration-300',
|
||||
// 모바일: 사이드바가 오버레이라 패딩 없음 / 데스크톱: 사이드바 폭만큼 확보
|
||||
isSidebarOpen ? 'md:pl-60' : 'md:pl-16'
|
||||
)}
|
||||
@@ -585,7 +583,8 @@ function NavItem({
|
||||
function HeaderMeta({ user, today }: { user: SidebarUser; today: string }) {
|
||||
return (
|
||||
<div className="flex items-center gap-3 md:gap-4">
|
||||
<Typography as="div" variant="caption" className="hidden lg:block">
|
||||
{/* 기준일시·관리자는 xl 부터 — lg 구간(1024~1280)은 우측 1fr 이 ~240px 라 글자가 세로로 깨진다. */}
|
||||
<Typography as="div" variant="caption" className="hidden xl:block whitespace-nowrap">
|
||||
기준일시: <span className="font-semibold text-foreground">{today}</span>
|
||||
</Typography>
|
||||
|
||||
@@ -603,8 +602,8 @@ function HeaderMeta({ user, today }: { user: SidebarUser; today: string }) {
|
||||
</Typography>
|
||||
</div>
|
||||
|
||||
<div className="h-4 w-px bg-border hidden lg:block" />
|
||||
<div className="hidden lg:flex items-center gap-2">
|
||||
<div className="h-4 w-px bg-border hidden xl:block" />
|
||||
<div className="hidden xl:flex items-center gap-2 whitespace-nowrap">
|
||||
<Typography as="span" variant="caption">관리자:</Typography>
|
||||
<Typography as="span" variant="caption" className="font-semibold text-foreground">
|
||||
{user?.name} ({user?.loginId})
|
||||
|
||||
@@ -236,7 +236,7 @@ const ZONE_STYLE: Record<NegotiationZoneTone, { marker: string; active: string;
|
||||
marker: 'bg-primary',
|
||||
active: 'bg-primary/10',
|
||||
text: 'text-primary',
|
||||
track: '#2563eb',
|
||||
track: '#5E6AD2',
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { ImagePlus, X, Loader2 } from 'lucide-react';
|
||||
import { showToast } from '@/lib/notify';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { useScrollLock } from '@/lib/useScrollLock';
|
||||
import { uploadItemImage, updateItem } from '@/api/generated/item/item';
|
||||
import { useAuthStore, canManage } from '@/stores/auth';
|
||||
import type { Product } from '../types';
|
||||
|
||||
// 로컬 이미지 일괄 업로드 — 파일명(확장자 제외)을 상품코드로 매칭해 업로드하고 상품에 연결한다.
|
||||
// 엑셀 양식과 무관한 독립 흐름: 기존 단건 업로드(/v1/item/image)와 상품 수정(image_url)을 파일별로 반복한다.
|
||||
// (협력사·카드 엑셀과 같은 프론트 루프 패턴 — 신규 API 없음)
|
||||
|
||||
// 상품 등록 폼이 이미지 미입력 시 넣는 기본(placeholder) 이미지 — 실제 이미지로 치지 않는다.
|
||||
const PLACEHOLDER_IMAGE_MARK = 'images.unsplash.com/photo-1593941707882';
|
||||
|
||||
type RowIssue =
|
||||
| 'unmatched' // 파일명과 일치하는 상품코드 없음
|
||||
| 'dup_code' // 같은 코드의 상품이 여러 건 — 어느 상품인지 특정 불가
|
||||
| 'dup_file' // 같은 코드의 파일이 여러 개 — 앞 파일만 유효
|
||||
| 'forbidden'; // 남의 상품(수정권한 없음 — 본인∪최고관리자만)
|
||||
|
||||
type RowState = 'ready' | 'skip' | 'uploading' | 'done' | 'failed';
|
||||
|
||||
type MatchRow = {
|
||||
file: File;
|
||||
base: string; // 파일명에서 확장자를 뗀 값 = 상품코드 후보
|
||||
product?: Product;
|
||||
issue?: RowIssue;
|
||||
hasImage: boolean; // 기존 이미지 보유(placeholder 제외) — 덮어쓰기 옵션 판정용
|
||||
state: RowState;
|
||||
reason?: string; // failed 사유
|
||||
};
|
||||
|
||||
type Phase = 'select' | 'running' | 'done';
|
||||
|
||||
export function ImageBulkUploadModal({
|
||||
open,
|
||||
loadProducts,
|
||||
onClose,
|
||||
}: {
|
||||
open: boolean;
|
||||
loadProducts: () => Promise<Product[]>; // 전체 상품(페이지 밖 포함) — 매칭·권한 판정용
|
||||
onClose: () => void;
|
||||
}) {
|
||||
useScrollLock(open);
|
||||
const queryClient = useQueryClient();
|
||||
const myUserId = useAuthStore((s) => s.user?.userId);
|
||||
const isSuperAdmin = useAuthStore((s) => canManage(s.user?.role));
|
||||
|
||||
const [rows, setRows] = useState<MatchRow[]>([]);
|
||||
const [phase, setPhase] = useState<Phase>('select');
|
||||
const [overwrite, setOverwrite] = useState(true); // 대부분 placeholder 이미지라 기본 덮어쓰기
|
||||
const [matching, setMatching] = useState(false);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// 파일 선택/드롭 → 전체 상품을 받아 파일명=상품코드 매칭표를 만든다(업로드는 아직 안 한다).
|
||||
const handleFiles = async (files: FileList | File[]) => {
|
||||
const picked = [...files].filter((f) => f.type.startsWith('image/'));
|
||||
if (picked.length === 0) {
|
||||
showToast('이미지 파일이 없습니다. (jpg/png 등 이미지만 지원)', 'error');
|
||||
return;
|
||||
}
|
||||
setMatching(true);
|
||||
try {
|
||||
const products = await loadProducts();
|
||||
setRows(buildRows(picked, products, myUserId, isSuperAdmin));
|
||||
setPhase('select');
|
||||
} catch (err) {
|
||||
showToast(err instanceof Error ? err.message : '상품 목록 조회에 실패했습니다.', 'error');
|
||||
} finally {
|
||||
setMatching(false);
|
||||
}
|
||||
};
|
||||
|
||||
const uploadTargets = rows.filter((r) => isUploadable(r, overwrite));
|
||||
const skippedByImage = rows.filter((r) => !r.issue && r.product && !overwrite && r.hasImage);
|
||||
|
||||
// 업로드 실행 — 파일별 순차: 이미지 업로드 → 받은 URL 을 상품 수정으로 저장. 실패해도 멈추지 않는다.
|
||||
const handleRun = async () => {
|
||||
setPhase('running');
|
||||
let ok = 0;
|
||||
let fail = 0;
|
||||
for (const row of rows) {
|
||||
if (!isUploadable(row, overwrite)) continue;
|
||||
setRowState(setRows, row.file, { state: 'uploading' });
|
||||
try {
|
||||
const up = await uploadItemImage({ file: row.file as unknown as string });
|
||||
if (up.result?.success === false) throw new Error(up.result.desc || '이미지 업로드 실패');
|
||||
if (!up.image_url) throw new Error('업로드 응답에 URL 이 없습니다.');
|
||||
const res = await updateItem(row.product!.item_id ?? '', { image_url: up.image_url });
|
||||
if (res.result?.success === false) throw new Error(res.result.desc || '상품 수정 거부');
|
||||
setRowState(setRows, row.file, { state: 'done' });
|
||||
ok += 1;
|
||||
} catch (err) {
|
||||
setRowState(setRows, row.file, {
|
||||
state: 'failed',
|
||||
reason: err instanceof Error ? err.message : '업로드 실패',
|
||||
});
|
||||
fail += 1;
|
||||
}
|
||||
}
|
||||
await queryClient.invalidateQueries({ queryKey: ['/v1/item/list'] });
|
||||
setPhase('done');
|
||||
showToast(
|
||||
fail === 0 ? `${ok}개 상품 이미지가 연결되었습니다.` : `${ok}개 성공 · ${fail}개 실패`,
|
||||
fail === 0 ? 'success' : 'error',
|
||||
);
|
||||
};
|
||||
|
||||
if (!open) return null;
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-xs">
|
||||
<div className="w-full max-w-3xl bg-card border border-border rounded-lg shadow-2xl p-6 max-h-[90vh] overflow-y-auto animate-scale-up font-mono">
|
||||
{/* 헤더 */}
|
||||
<div className="flex items-center justify-between pb-3 border-b border-border">
|
||||
<Typography variant="h3">상품 이미지 일괄 업로드</Typography>
|
||||
<button
|
||||
onClick={onClose}
|
||||
disabled={phase === 'running'}
|
||||
className="p-1 rounded text-muted-foreground hover:bg-muted cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"
|
||||
>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<Typography as="p" variant="small" className="text-[11px] text-muted-foreground mt-3">
|
||||
파일명(확장자 제외)을 <Typography as="span" variant="small" className="text-[11px] font-bold text-foreground">상품코드</Typography>로
|
||||
매칭합니다. 예: <Typography as="span" variant="small" className="text-[11px] font-semibold text-foreground">ABC-001.jpg → 상품코드 ABC-001</Typography>
|
||||
</Typography>
|
||||
|
||||
{/* 파일 선택 존 */}
|
||||
<div
|
||||
onClick={() => phase !== 'running' && fileRef.current?.click()}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
if (phase !== 'running') handleFiles(e.dataTransfer.files);
|
||||
}}
|
||||
className={`mt-4 rounded-md border-2 border-dashed border-border p-6 text-center transition-colors ${
|
||||
phase === 'running' ? 'opacity-50' : 'cursor-pointer hover:border-primary hover:bg-primary/5'
|
||||
}`}
|
||||
>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
if (e.target.files) handleFiles(e.target.files);
|
||||
e.target.value = ''; // 같은 파일 재선택 허용
|
||||
}}
|
||||
/>
|
||||
{matching ? (
|
||||
<Typography as="div" variant="small" className="flex items-center justify-center gap-2 text-muted-foreground">
|
||||
<Loader2 size={14} className="animate-spin" /> 상품 목록과 매칭 중…
|
||||
</Typography>
|
||||
) : (
|
||||
<>
|
||||
<ImagePlus size={20} className="mx-auto text-muted-foreground" />
|
||||
<Typography as="p" variant="small" className="mt-2 text-xs text-muted-foreground">
|
||||
이미지를 끌어다 놓거나 클릭해서 선택 (여러 장 가능)
|
||||
</Typography>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 옵션 + 매칭표 */}
|
||||
{rows.length > 0 && (
|
||||
<>
|
||||
<label className="mt-4 flex items-center gap-2 cursor-pointer w-fit">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={overwrite}
|
||||
disabled={phase === 'running'}
|
||||
onChange={(e) => setOverwrite(e.target.checked)}
|
||||
className="h-3.5 w-3.5 rounded border-border accent-primary cursor-pointer"
|
||||
/>
|
||||
<Typography as="span" variant="small" className="text-xs">
|
||||
기존 이미지가 있는 상품도 덮어쓰기
|
||||
</Typography>
|
||||
</label>
|
||||
|
||||
<div className="mt-3 border border-border rounded-md overflow-hidden">
|
||||
<div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_8.5rem] gap-x-3 px-3 py-2 bg-muted/40 border-b border-border">
|
||||
<Typography as="span" variant="mono" className="text-[10px] text-muted-foreground">파일명</Typography>
|
||||
<Typography as="span" variant="mono" className="text-[10px] text-muted-foreground">매칭 상품</Typography>
|
||||
<Typography as="span" variant="mono" className="text-[10px] text-muted-foreground text-right">상태</Typography>
|
||||
</div>
|
||||
<div className="max-h-64 overflow-y-auto divide-y divide-border">
|
||||
{rows.map((r, i) => (
|
||||
<div key={`${r.file.name}-${i}`} className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_8.5rem] gap-x-3 px-3 py-1.5 items-center">
|
||||
<Typography as="span" variant="small" className="text-[11px] truncate" title={r.file.name}>
|
||||
{r.file.name}
|
||||
</Typography>
|
||||
<Typography as="span" variant="small" className="text-[11px] truncate text-muted-foreground" title={r.product?.name ?? ''}>
|
||||
{r.product ? r.product.name : '—'}
|
||||
</Typography>
|
||||
<span className="text-right">{renderStatus(r, overwrite)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 요약 + 실행 */}
|
||||
<div className="mt-4 flex items-center justify-between gap-3">
|
||||
<Typography as="p" variant="small" className="text-[11px] text-muted-foreground">
|
||||
업로드 대상 {uploadTargets.length}건
|
||||
{skippedByImage.length > 0 && ` · 기존 이미지로 건너뜀 ${skippedByImage.length}건`}
|
||||
{rows.filter((r) => r.issue).length > 0 && ` · 제외 ${rows.filter((r) => r.issue).length}건`}
|
||||
</Typography>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" size="sm" onClick={onClose} disabled={phase === 'running'}>
|
||||
{phase === 'done' ? '닫기' : '취소'}
|
||||
</Button>
|
||||
{phase !== 'done' && (
|
||||
<Button size="sm" onClick={handleRun} disabled={phase === 'running' || uploadTargets.length === 0}>
|
||||
{phase === 'running' ? (
|
||||
<>
|
||||
<Loader2 size={13} className="animate-spin" /> 업로드 중…
|
||||
</>
|
||||
) : (
|
||||
`업로드 시작 (${uploadTargets.length})`
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 파일 → 상품 매칭표. 코드 비교는 공백 제거 + 대소문자 무시(엑셀·수기 등록 코드 표기가 섞여 있어서).
|
||||
function buildRows(
|
||||
files: File[],
|
||||
products: Product[],
|
||||
myUserId: string | undefined,
|
||||
isSuperAdmin: boolean,
|
||||
): MatchRow[] {
|
||||
const byCode = new Map<string, Product[]>();
|
||||
for (const p of products) {
|
||||
const code = String(p.code ?? '').trim().toLowerCase();
|
||||
if (!code) continue;
|
||||
byCode.set(code, [...(byCode.get(code) ?? []), p]);
|
||||
}
|
||||
const seenBases = new Set<string>();
|
||||
return files.map((file) => {
|
||||
const base = file.name.replace(/\.[^.]+$/, '').trim();
|
||||
const key = base.toLowerCase();
|
||||
const matches = byCode.get(key) ?? [];
|
||||
const product = matches.length === 1 ? matches[0] : undefined;
|
||||
let issue: RowIssue | undefined;
|
||||
if (matches.length === 0) issue = 'unmatched';
|
||||
else if (matches.length > 1) issue = 'dup_code';
|
||||
else if (seenBases.has(key)) issue = 'dup_file';
|
||||
else if (!isSuperAdmin && product?.user_id !== myUserId) issue = 'forbidden';
|
||||
seenBases.add(key);
|
||||
const hasImage = !!product?.image_url && !product.image_url.includes(PLACEHOLDER_IMAGE_MARK);
|
||||
return { file, base, product, issue, hasImage, state: issue ? 'skip' : 'ready' } as MatchRow;
|
||||
});
|
||||
}
|
||||
|
||||
function isUploadable(row: MatchRow, overwrite: boolean): boolean {
|
||||
if (row.issue || !row.product) return false;
|
||||
if (!overwrite && row.hasImage) return false;
|
||||
return row.state === 'ready' || row.state === 'uploading' || row.state === 'failed';
|
||||
}
|
||||
|
||||
// 특정 파일 행의 상태만 갱신(불변 업데이트).
|
||||
function setRowState(
|
||||
setRows: React.Dispatch<React.SetStateAction<MatchRow[]>>,
|
||||
file: File,
|
||||
patch: Partial<Pick<MatchRow, 'state' | 'reason'>>,
|
||||
) {
|
||||
setRows((prev) => prev.map((r) => (r.file === file ? { ...r, ...patch } : r)));
|
||||
}
|
||||
|
||||
const ISSUE_LABEL: Record<RowIssue, string> = {
|
||||
unmatched: '코드 미매칭',
|
||||
dup_code: '코드 중복',
|
||||
dup_file: '파일명 중복',
|
||||
forbidden: '권한 없음',
|
||||
};
|
||||
|
||||
function renderStatus(row: MatchRow, overwrite: boolean) {
|
||||
if (row.issue) {
|
||||
return (
|
||||
<Typography as="span" variant="small" className="text-[10px] px-1.5 py-0.5 rounded bg-rose-500/10 text-rose-600 dark:text-rose-400">
|
||||
{ISSUE_LABEL[row.issue]}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
if (row.state === 'uploading') {
|
||||
return (
|
||||
<Typography as="span" variant="small" className="text-[10px] inline-flex items-center gap-1 text-muted-foreground">
|
||||
<Loader2 size={10} className="animate-spin" /> 업로드 중
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
if (row.state === 'done') {
|
||||
return (
|
||||
<Typography as="span" variant="small" className="text-[10px] px-1.5 py-0.5 rounded bg-emerald-500/10 text-emerald-700 dark:text-emerald-400">
|
||||
완료
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
if (row.state === 'failed') {
|
||||
return (
|
||||
<Typography as="span" variant="small" className="text-[10px] px-1.5 py-0.5 rounded bg-rose-500/10 text-rose-600 dark:text-rose-400" title={row.reason}>
|
||||
실패
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
if (!overwrite && row.hasImage) {
|
||||
return (
|
||||
<Typography as="span" variant="small" className="text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground">
|
||||
이미지 있음 · 건너뜀
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Typography as="span" variant="small" className="text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary">
|
||||
{row.hasImage ? '덮어쓰기' : '업로드 대기'}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import { Input } from '@/components/ui/input';
|
||||
import { Sheet } from '@/components/ui/sheet';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { useAuthStore, canManage } from '@/stores/auth';
|
||||
import { useCompanySettings, useLabels, useHiddenFields } from '@/features/settings/useCompanySettings';
|
||||
import { useCompanySettings, useLabels, useHiddenFields, useVatMode } from '@/features/settings/useCompanySettings';
|
||||
import { CustomFieldInputs, useCustomFieldValues } from '@/features/settings/CustomFieldInputs';
|
||||
import { ItemSuppliersManager } from './ItemSuppliersManager';
|
||||
import { NewItemSuppliersPicker, type PickedSupplier } from './NewItemSuppliersPicker';
|
||||
@@ -141,6 +141,7 @@ export function ProductFormSheet({
|
||||
|
||||
const label = useLabels(); // 회사 설정 용어
|
||||
const isHidden = useHiddenFields();
|
||||
const vatUnified = useVatMode() === 'unified_excluded'; // 부가세 전체 통일(VAT 별도) 회사
|
||||
// 숨김 필드는 DOM 에서 제거하지 않고 감추기만 한다 — 수정 시 기존 값이 그대로 유지·전송되도록.
|
||||
const hideCls = (key: string, base = 'space-y-1') => (isHidden(key) ? `${base} hidden` : base);
|
||||
const hideCls2 = (hidden: boolean, base: string) => (hidden ? `${base} hidden` : base);
|
||||
@@ -178,7 +179,8 @@ export function ProductFormSheet({
|
||||
delivery_type: v.shippingType,
|
||||
moq: v.moq,
|
||||
lead_time: v.leadTime,
|
||||
vat_yn: v.vatYn,
|
||||
// 부가세를 관리하지 않는 회사(전체 통일 모드·숨김)는 값을 쓰지 않는다 — 스위치 기본값(포함)이 몰래 저장되는 것 방지.
|
||||
vat_yn: isHidden('vat_yn') ? undefined : v.vatYn,
|
||||
delivery_fee_yn: v.deliveryFeeYn,
|
||||
internet_lowest_price_yn: v.internetLowestPriceYn,
|
||||
internet_lowest_price: v.minPrice,
|
||||
@@ -293,6 +295,12 @@ export function ProductFormSheet({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 전체 통일 회사는 가격 입력 기준을 폼에서 못 박는다 — 상품별 VAT 입력이 없어 달리 알 길이 없다. */}
|
||||
{vatUnified && (
|
||||
<Typography as="p" variant="caption" className="text-muted-foreground -mb-2">
|
||||
모든 가격은 VAT 별도(제외) 기준으로 입력합니다.
|
||||
</Typography>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{/* Price */}
|
||||
<div className={hideCls('price')}>
|
||||
|
||||
@@ -111,6 +111,14 @@ export function ProductTable({
|
||||
cellClassName: 'font-mono font-bold text-foreground',
|
||||
cell: (prod) => `₩${(prod.price || 0).toLocaleString()}`,
|
||||
},
|
||||
{
|
||||
field: 'purchase_price',
|
||||
header: label('item.purchase_price'),
|
||||
align: 'right',
|
||||
cellClassName: 'font-mono font-bold text-foreground',
|
||||
cell: (prod) =>
|
||||
prod.purchase_price != null ? `₩${Number(prod.purchase_price).toLocaleString()}` : '-',
|
||||
},
|
||||
{
|
||||
field: 'internet_lowest_price',
|
||||
header: label('item.internet_lowest_price'),
|
||||
|
||||
@@ -6,7 +6,7 @@ import { useListItems, useGetItem } from '@/api/generated/item/item';
|
||||
import { useListSuppliers } from '@/api/generated/supplier/supplier';
|
||||
import { useListCards } from '@/api/generated/card/card';
|
||||
import { mapCardData } from '@/features/cards/types';
|
||||
import { useLabels } from '@/features/settings/useCompanySettings';
|
||||
import { useLabels, useVatMode } from '@/features/settings/useCompanySettings';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Typography, typographyVariants } from '@/components/ui/typography';
|
||||
import { cn } from '@/lib/utils';
|
||||
@@ -117,6 +117,7 @@ export function QuotationCreateModal({
|
||||
// 선택 상품의 협력사별 공급유형(제조/유통/총판/없음) — 협력사 리스트에 배지로 덧붙인다(리스트 자체는 재조회 안 함).
|
||||
const supplyTypeQuery = useListItemSupplyTypes(productId, { query: { enabled: !!productId } });
|
||||
const label = useLabels(); // 회사 설정 용어(목표 마진 등)
|
||||
const vatUnified = useVatMode() === 'unified_excluded'; // 부가세 전체 통일 — 목표가 입력 기준 안내
|
||||
const supplyTypeBySupplier = useMemo(() => {
|
||||
const m = new Map<string, number>();
|
||||
(supplyTypeQuery.data?.suppliers ?? []).forEach((s) => m.set(s.supplier_id, s.supply_type));
|
||||
@@ -556,6 +557,7 @@ export function QuotationCreateModal({
|
||||
{autoTarget != null
|
||||
? '위에서 선택한 후보값이 목표가(1순위)로 입력됩니다. 수정 가능.'
|
||||
: '자동 산출값이 없어 직접 입력이 필요합니다.'}
|
||||
{vatUnified && ' 금액은 VAT 별도(제외) 기준입니다.'}
|
||||
</Typography>
|
||||
{!targetReady && (
|
||||
<Typography as="p" variant="small" className="text-rose-600 leading-snug">
|
||||
|
||||
@@ -8,12 +8,12 @@ import SlateRenderer from '@/components/SlateRenderer';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { StatusPill, sessionStatusTone } from './StatusPill';
|
||||
import { type Product, type Partner, sessionStatusLabel } from '../../types';
|
||||
import { maskPrices } from '@/lib/utils';
|
||||
import { useCompanySettings } from '@/features/settings/useCompanySettings';
|
||||
import { renderEmphasis } from '@/lib/emphasis';
|
||||
import { renderCardScriptPreview } from '@/features/cards/editor';
|
||||
|
||||
// 협상로그 JSON 다운로드(IMK #9). 가격·비율 숫자는 maskPrices 로 가려 내보낸다(화면 표기와 동일 규칙).
|
||||
// 협상로그 JSON 다운로드(IMK #9). 가격·인하율은 실값 그대로 내보낸다 — 이 탭을 열 수 있는 사람이
|
||||
// 이미 공개 대상(해당 견적 담당자∪최고관리자, 조회 게이팅)뿐이라 마스킹이 하던 차단 역할이 없다.
|
||||
// target_price 등 숫자 필드는 아예 제외 — 양식은 대화 흐름(순번/발화자/스텝/멘트/카드사용) 중심.
|
||||
function exportChatJson(
|
||||
session: SessionData | undefined,
|
||||
@@ -37,7 +37,7 @@ function exportChatJson(
|
||||
seq: m.index,
|
||||
sender: m.sender === ChatSender.BOT ? 'BOT' : 'PARTNER',
|
||||
step: m.step ?? null,
|
||||
script: maskPrices(String(m.script ?? '')),
|
||||
script: String(m.script ?? ''),
|
||||
card: card
|
||||
? {
|
||||
number: card.number ?? null,
|
||||
@@ -153,7 +153,7 @@ export function ChatTab({
|
||||
type="button"
|
||||
onClick={() => exportChatJson(currentSession, currentSupplierName, currentProduct?.name, chatMessages, serverCards)}
|
||||
disabled={chatMessages.length === 0}
|
||||
title="협상로그 JSON 내보내기 (금액 숫자는 가려서 저장)"
|
||||
title="협상로그 JSON 내보내기"
|
||||
className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded border border-border text-[10px] font-mono text-muted-foreground hover:bg-muted disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"
|
||||
>
|
||||
<Download size={11} />
|
||||
@@ -243,7 +243,7 @@ function BotBubble({
|
||||
)}
|
||||
{m.script && !usedCard && (
|
||||
<Typography as="p" variant="small" className="text-xs whitespace-pre-line leading-relaxed text-inherit">
|
||||
{renderEmphasis(maskPrices(m.script))}
|
||||
{renderEmphasis(m.script)}
|
||||
</Typography>
|
||||
)}
|
||||
<UsedCardBox
|
||||
@@ -259,7 +259,7 @@ function BotBubble({
|
||||
);
|
||||
}
|
||||
|
||||
// 협력사(우측) 말풍선. 협력사 입력값을 보여주되, 채팅 '내용'에 제시 금액이 노출되지 않도록 maskPrices 로 가린다.
|
||||
// 협력사(우측) 말풍선. 제시 금액은 실값 그대로 — 열람 가능자가 곧 공개 대상(조회 게이팅)이다.
|
||||
function PartnerBubble({
|
||||
message,
|
||||
currentSupplierName,
|
||||
@@ -288,7 +288,7 @@ function PartnerBubble({
|
||||
)}
|
||||
{m.script && (
|
||||
<Typography as="p" variant="small" className="text-xs whitespace-pre-line leading-relaxed text-inherit">
|
||||
{maskPrices(m.script)}
|
||||
{m.script}
|
||||
</Typography>
|
||||
)}
|
||||
<UsedCardBox
|
||||
@@ -387,7 +387,7 @@ function UsedCardBox({
|
||||
</div>
|
||||
) : usedCard.script ? (
|
||||
<Typography as="p" variant="small" className="mt-1.5 text-xs leading-relaxed whitespace-pre-line text-foreground/85">
|
||||
{renderCardScriptPreview(maskPrices(usedCard.script))}
|
||||
{renderCardScriptPreview(usedCard.script)}
|
||||
</Typography>
|
||||
) : null}
|
||||
|
||||
|
||||
+13
-7
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
import { MessageSquare, Copy, Mail, MailCheck, Send, Trophy, ClipboardList, X } from 'lucide-react';
|
||||
import { MessageSquare, Copy, Mail, MailCheck, Send, Trophy, ClipboardList, X, Loader2 } from 'lucide-react';
|
||||
import { showToast } from '@/lib/notify';
|
||||
import { confirm } from '@/lib/confirm';
|
||||
import { cn } from '@/lib/utils';
|
||||
@@ -141,7 +141,7 @@ export function SessionsStatusTab({
|
||||
}
|
||||
className="flex items-center gap-2 px-3 py-2 bg-primary text-primary-foreground text-xs font-bold rounded hover:opacity-95 cursor-pointer transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Mail size={14} />
|
||||
{sendingAll ? <Loader2 size={14} className="animate-spin" /> : <Mail size={14} />}
|
||||
<span>{sendingAll ? '발송 중…' : `초청 메일 발송${unsentCount > 0 ? ` (${unsentCount})` : ''}`}</span>
|
||||
</button>
|
||||
</div>
|
||||
@@ -296,10 +296,10 @@ export function SessionsStatusTab({
|
||||
<TooltipTrigger render={
|
||||
<button
|
||||
onClick={() => handleOne(sess.session_id, sess.supplier_name, !!sess.email_sent_at)}
|
||||
disabled={!canNotify || sendingId === sess.session_id}
|
||||
disabled={!canNotify || sendingAll || sendingId === sess.session_id}
|
||||
className="p-1 rounded text-primary hover:bg-primary/10 transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Send size={12} />
|
||||
{sendingId === sess.session_id ? <Loader2 size={12} className="animate-spin" /> : <Send size={12} />}
|
||||
</button>
|
||||
} />
|
||||
<TooltipContent>
|
||||
@@ -429,14 +429,20 @@ export function SessionsStatusTab({
|
||||
)}
|
||||
<button
|
||||
onClick={() => handleOne(sess.session_id, sess.supplier_name, !!sess.email_sent_at)}
|
||||
disabled={!canNotify || sendingId === sess.session_id}
|
||||
disabled={!canNotify || sendingAll || sendingId === sess.session_id}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-[10px] cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed',
|
||||
sess.email_sent_at ? 'text-success' : 'text-primary',
|
||||
)}
|
||||
>
|
||||
{sess.email_sent_at ? <MailCheck size={12} /> : <Mail size={12} />}
|
||||
{sess.email_sent_at ? '메일 재발송' : '메일 발송'}
|
||||
{sendingId === sess.session_id ? (
|
||||
<Loader2 size={12} className="animate-spin" />
|
||||
) : sess.email_sent_at ? (
|
||||
<MailCheck size={12} />
|
||||
) : (
|
||||
<Mail size={12} />
|
||||
)}
|
||||
{sendingId === sess.session_id ? '발송 중…' : sess.email_sent_at ? '메일 재발송' : '메일 발송'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
||||
+4
-2
@@ -2,7 +2,7 @@ import { X, Check } from 'lucide-react';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { useGetTargetBreakdown } from '@/api/generated/quotation/quotation';
|
||||
import { useScrollLock } from '@/lib/useScrollLock';
|
||||
import { useLabels } from '@/features/settings/useCompanySettings';
|
||||
import { useLabels, useVatMode } from '@/features/settings/useCompanySettings';
|
||||
|
||||
// 세션 목표가 산정내역 모달. 후보·채택·앵커링가는 백엔드 /target-breakdown 이 산정한 값을 '표시만' 한다.
|
||||
// (프론트 재계산 없음 → 저장된 목표가와 항상 일치. 산정 로직은 백엔드 _candidates 단일 출처.)
|
||||
@@ -39,6 +39,8 @@ export function TargetPriceModal({
|
||||
}: TargetPriceModalProps) {
|
||||
useScrollLock(); // 모달은 열릴 때만 마운트(부모 게이트) → 배경 스크롤 잠금
|
||||
const label = useLabels(); // 회사 설정 용어
|
||||
// 부가세 전체 통일 회사는 상품 vat_yn 잔존값과 무관하게 'VAT별도' 고정.
|
||||
const vatUnified = useVatMode() === 'unified_excluded';
|
||||
const CANDIDATE_SUB = candidateSub(`${label('target_margin')}`);
|
||||
const { data: bd, isLoading } = useGetTargetBreakdown(sessionId, { query: { enabled: !!sessionId } });
|
||||
const candidates = bd?.candidates ?? [];
|
||||
@@ -64,7 +66,7 @@ export function TargetPriceModal({
|
||||
견적번호: {qtNumber} · 상품: {itemName}
|
||||
</Typography>
|
||||
<Typography as="p" variant="small" className="text-[11px] font-semibold text-rose-500 mt-1">
|
||||
배송비: {deliveryFeeYn ? '배송비포함' : '배송비별도'} · 부가세: {vatYn ? 'VAT포함' : 'VAT별도'}
|
||||
배송비: {deliveryFeeYn ? '배송비포함' : '배송비별도'} · 부가세: {!vatUnified && vatYn ? 'VAT포함' : 'VAT별도'}
|
||||
</Typography>
|
||||
|
||||
{isLoading || !bd ? (
|
||||
|
||||
@@ -180,7 +180,9 @@ export function QuotationTable({ data, products, onOpenDetail, onFilterChain, se
|
||||
},
|
||||
{
|
||||
header: '생성일',
|
||||
cellClassName: 'font-mono text-muted-foreground whitespace-nowrap',
|
||||
// 10컬럼 표라 좁은 데스크톱(xl~2xl)에선 부차 정보인 생성일을 접어 가로 스크롤을 줄인다.
|
||||
headClassName: 'hidden 2xl:table-cell',
|
||||
cellClassName: 'hidden 2xl:table-cell font-mono text-muted-foreground whitespace-nowrap',
|
||||
cell: (est) => (
|
||||
<Typography as="span" variant="small" className="text-xs text-inherit">{est.createdDate ?? '-'}</Typography>
|
||||
),
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { Fragment, useEffect, useMemo, useRef, useState, type ElementType } from 'react';
|
||||
import { useSearchParams } from 'react-router';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Palette, Tags, ListPlus, MessageSquareText, Plus, Trash2, RotateCcw, Download, Upload, X } from 'lucide-react';
|
||||
import { showToast } from '@/lib/notify';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import ImageDropzone from '@/components/ImageDropzone';
|
||||
import { uploadItemImage } from '@/api/generated/item/item';
|
||||
import { previewInviteEmail } from '@/api/generated/company-settings/company-settings';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
|
||||
@@ -19,6 +21,8 @@ import {
|
||||
DEFAULT_GUIDE_NOTICES,
|
||||
NEGO_BASELINE_OPTIONS,
|
||||
DEFAULT_NEGO_BASELINE_FIELD,
|
||||
VAT_MODE_OPTIONS,
|
||||
DEFAULT_VAT_MODE,
|
||||
type CompanySettings,
|
||||
type CustomFieldDef,
|
||||
type CustomFieldType,
|
||||
@@ -48,6 +52,12 @@ const SETTINGS_TAB_ICON: Record<SettingsTab, ElementType> = {
|
||||
fields: ListPlus,
|
||||
};
|
||||
|
||||
// branding 의 문자열 서브키(helpdesk 만 배열이라 제외). email_* 는 협상 초청 메일 커스텀.
|
||||
type BrandingTextKey =
|
||||
| 'service_name'
|
||||
| 'logo_url'
|
||||
| 'email_greeting';
|
||||
|
||||
export function SettingsView({ tabs = SETTINGS_TABS }: { tabs?: readonly SettingsTab[] }) {
|
||||
const { settings, isLoading, save } = useCompanySettings();
|
||||
|
||||
@@ -141,7 +151,7 @@ export function SettingsView({ tabs = SETTINGS_TABS }: { tabs?: readonly Setting
|
||||
return res.image_url;
|
||||
};
|
||||
|
||||
const setBranding = (key: 'service_name' | 'logo_url' | 'primary_color' | 'email_header', value: string) =>
|
||||
const setBranding = (key: BrandingTextKey, value: string) =>
|
||||
setDraft((d) => ({ ...d, branding: { ...d.branding, [key]: value } }));
|
||||
const setHelpdesk = (lines: string[]) =>
|
||||
setDraft((d) => ({ ...d, branding: { ...d.branding, helpdesk: lines } }));
|
||||
@@ -197,7 +207,7 @@ export function SettingsView({ tabs = SETTINGS_TABS }: { tabs?: readonly Setting
|
||||
<TabsContent value="branding" className="space-y-4">
|
||||
<SectionCard
|
||||
title="서비스 브랜딩"
|
||||
desc="사이드바·타이틀에 노출되는 서비스명과 로고입니다. 비워두면 기본 브랜드(NegoData)가 사용됩니다."
|
||||
desc="회사 CI 입니다. 사이드바·타이틀은 물론 공급사 포털(로그인·버튼)과 협상 초청 메일에도 그대로 적용됩니다. 비워두면 기본 브랜드(NegoData)가 사용됩니다."
|
||||
>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<Field label="서비스명" hint="예: iMarketKorea 구매협상 콘솔">
|
||||
@@ -229,16 +239,32 @@ export function SettingsView({ tabs = SETTINGS_TABS }: { tabs?: readonly Setting
|
||||
{draft.branding?.logo_url ? (
|
||||
<img src={draft.branding.logo_url} alt="로고 미리보기" className="h-4 max-w-24 object-contain" />
|
||||
) : (
|
||||
<span
|
||||
aria-hidden
|
||||
className="size-4 rounded-[5px]"
|
||||
style={{ backgroundColor: draft.branding?.primary_color || 'var(--primary)' }}
|
||||
/>
|
||||
<span aria-hidden className="size-4 rounded-[5px] bg-primary" />
|
||||
)}
|
||||
{draft.branding?.service_name || 'NegoData'}
|
||||
</div>
|
||||
</div>
|
||||
</SectionCard>
|
||||
|
||||
<SectionCard
|
||||
title="협상 초청 메일"
|
||||
desc="공급사 담당자에게 발송되는 협상 초청 메일입니다. 로고·회사명·색은 위 서비스 브랜딩(CI)을 그대로 따르고, 메일에서 바꿀 수 있는 건 인사 문구뿐입니다. 레이아웃은 고정이라 어떤 메일 앱에서도 깨지지 않습니다."
|
||||
>
|
||||
<div className="grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_540px] gap-6">
|
||||
<div className="space-y-4">
|
||||
<Field label="인사 문구" hint="'OO 담당자님,' 다음 줄에 들어갑니다.">
|
||||
<textarea
|
||||
rows={2}
|
||||
className="w-full p-2 bg-background border border-border rounded text-xs resize-none"
|
||||
value={draft.branding?.email_greeting ?? ''}
|
||||
onChange={(e) => setBranding('email_greeting', e.target.value)}
|
||||
placeholder="아래 견적 건의 협상에 참여해 주세요. (기본값)"
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
<InviteEmailPreview branding={draft.branding} />
|
||||
</div>
|
||||
</SectionCard>
|
||||
</TabsContent>
|
||||
|
||||
{/* ---- 공급사 포털 안내 ---- */}
|
||||
@@ -265,7 +291,7 @@ export function SettingsView({ tabs = SETTINGS_TABS }: { tabs?: readonly Setting
|
||||
<LineListEditor
|
||||
lines={draft.branding?.helpdesk ?? []}
|
||||
onChange={setHelpdesk}
|
||||
placeholder="김건우P 02-3708-5832 kw086.kim@imarketkorea.com"
|
||||
placeholder="홍길동P 02-0000-0000 helpdesk@example.com"
|
||||
addLabel="연락처 추가"
|
||||
emptyHint="등록된 연락처가 없습니다. 공급사 포털에 연락처 영역이 표시되지 않습니다."
|
||||
/>
|
||||
@@ -331,7 +357,7 @@ export function SettingsView({ tabs = SETTINGS_TABS }: { tabs?: readonly Setting
|
||||
<TabsContent value="fields" className="space-y-4">
|
||||
<SectionCard
|
||||
title="협상 기준가"
|
||||
desc="협상 중 '기존 OO 대비 N% 인하' 를 계산하는 기준 가격입니다. 우리 회사가 공급사에 실제로 지불 중인 단가를 고르십시오."
|
||||
desc="협상 중 '기존 공급가 대비 N% 인하' 를 계산하는 기준 가격입니다. 우리 회사가 공급사에 실제로 지불 중인 단가를 고르십시오. 공급사 화면 표기는 어느 필드를 고르든 '공급가'로 고정됩니다."
|
||||
>
|
||||
<NegoBaselinePicker
|
||||
value={draft.features?.nego_baseline_field ?? DEFAULT_NEGO_BASELINE_FIELD}
|
||||
@@ -343,6 +369,43 @@ export function SettingsView({ tabs = SETTINGS_TABS }: { tabs?: readonly Setting
|
||||
/>
|
||||
</SectionCard>
|
||||
|
||||
<SectionCard
|
||||
title="부가세(VAT) 관리"
|
||||
desc="가격 정보의 부가세 기준입니다. 전체 통일을 선택하면 상품별 부가세 입력이 폼·엑셀 양식에서 사라지고, 공급사 협상 화면 가격에 'VAT 별도'가 항상 표기됩니다. DB 컬럼과 기존 값은 그대로 남습니다."
|
||||
>
|
||||
<div className="space-y-2">
|
||||
{VAT_MODE_OPTIONS.map((opt) => {
|
||||
const selected = (draft.features?.vat_mode ?? DEFAULT_VAT_MODE) === opt.value;
|
||||
return (
|
||||
<label
|
||||
key={opt.value}
|
||||
className={`flex items-start gap-2.5 p-3 rounded-md border cursor-pointer ${
|
||||
selected ? 'border-primary bg-primary/5' : 'border-border'
|
||||
}`}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="vat_mode"
|
||||
className="mt-1"
|
||||
checked={selected}
|
||||
onChange={() =>
|
||||
setDraft((d) => ({ ...d, features: { ...d.features, vat_mode: opt.value } }))
|
||||
}
|
||||
/>
|
||||
<span className="min-w-0 space-y-1">
|
||||
<Typography as="span" variant="small" className="block font-semibold">
|
||||
{opt.label}
|
||||
</Typography>
|
||||
<Typography as="span" variant="caption" className="block text-muted-foreground">
|
||||
{opt.desc}
|
||||
</Typography>
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</SectionCard>
|
||||
|
||||
<SectionCard
|
||||
title="상품 필드 숨김"
|
||||
desc="체크한 항목은 상품 목록·등록 폼·엑셀 양식에서 감춰집니다. DB 컬럼과 기존 값은 그대로 남습니다."
|
||||
@@ -350,12 +413,23 @@ export function SettingsView({ tabs = SETTINGS_TABS }: { tabs?: readonly Setting
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-2">
|
||||
{HIDEABLE_ITEM_FIELDS.map((f) => {
|
||||
const checked = (draft.hidden_fields ?? []).includes(f.key);
|
||||
// 협상 기준가로 지정된 필드는 숨김 금지(강제) — 입력 화면이 사라지면 신규 상품의
|
||||
// 기준값이 NULL 로 쌓여 인하율 멘트가 통째로 빠진다. 이미 숨겨진 상태면 해제만 허용.
|
||||
const baselineLocked =
|
||||
f.key === (draft.features?.nego_baseline_field ?? DEFAULT_NEGO_BASELINE_FIELD) &&
|
||||
!checked;
|
||||
return (
|
||||
<label key={f.key} className="flex items-start gap-2 py-1 cursor-pointer">
|
||||
<label
|
||||
key={f.key}
|
||||
className={`flex items-start gap-2 py-1 ${
|
||||
baselineLocked ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'
|
||||
}`}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mt-0.5"
|
||||
checked={checked}
|
||||
disabled={baselineLocked}
|
||||
onChange={(e) =>
|
||||
setDraft((d) => {
|
||||
const cur = new Set(d.hidden_fields ?? []);
|
||||
@@ -372,6 +446,11 @@ export function SettingsView({ tabs = SETTINGS_TABS }: { tabs?: readonly Setting
|
||||
<Typography as="span" variant="caption" className="block text-muted-foreground">
|
||||
{f.where}
|
||||
</Typography>
|
||||
{baselineLocked && (
|
||||
<Typography as="span" variant="caption" className="block text-amber-600">
|
||||
⚠ 협상 기준가로 지정된 필드는 숨길 수 없습니다
|
||||
</Typography>
|
||||
)}
|
||||
{f.calcNote && (
|
||||
<Typography as="span" variant="caption" className="block text-amber-600">
|
||||
⚠ {f.calcNote}
|
||||
@@ -484,9 +563,6 @@ function NegoBaselinePicker({
|
||||
<Typography as="span" variant="caption" className="block text-muted-foreground">
|
||||
{opt.desc}
|
||||
</Typography>
|
||||
<Typography as="span" variant="caption" className="block text-muted-foreground">
|
||||
협상 멘트 — 기존 {phrase} 대비 약 3.2% 인하된 금액입니다.
|
||||
</Typography>
|
||||
{selected && hiddenFields.includes(opt.value) && (
|
||||
<Typography as="span" variant="caption" className="block text-amber-600">
|
||||
⚠ 이 필드를 아래에서 숨김 처리했습니다. 값을 입력할 화면이 없어 신규 상품은 기준가가 비어
|
||||
@@ -497,6 +573,10 @@ function NegoBaselinePicker({
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
<Typography variant="caption" className="block text-muted-foreground">
|
||||
협상 멘트(공급사 화면) — 기존 공급가 대비 약 3.2% 인하된 금액입니다. 여기서 고른 필드는 계산에 쓰는
|
||||
값만 정하고, 공급사에게 보이는 호칭은 항상 ‘공급가’입니다.
|
||||
</Typography>
|
||||
<Typography variant="caption" className="block text-amber-600">
|
||||
⚠ 이미 협상을 진행한 회사가 이 값을 바꾸면 가격 수용률 기준이 달라져, 기존 학습분과 이후 데이터가
|
||||
섞입니다. 협상 시작 전에 정하십시오. (진행 중인 협상은 시작 시점 기준을 그대로 유지합니다)
|
||||
@@ -588,6 +668,60 @@ function Field({ label, hint, children }: { label: string; hint?: string; childr
|
||||
);
|
||||
}
|
||||
|
||||
// 초청 메일 미리보기 — 실제 발송과 같은 백엔드 템플릿을 샘플 견적으로 렌더해 iframe 에 띄운다.
|
||||
// 입력 중 매 타자마다 서버를 부르지 않도록 디바운스하고, 갱신 사이엔 직전 렌더를 유지해 깜빡임을 없앤다.
|
||||
function InviteEmailPreview({ branding }: { branding?: CompanySettings['branding'] }) {
|
||||
// 메일 헤더는 회사 CI(로고·서비스명)를 그대로 쓰므로 CI 편집값을 같이 보낸다(미리보기 = 실발송). 색은 솔루션 고정.
|
||||
const emailBranding = JSON.stringify({
|
||||
service_name: branding?.service_name ?? '',
|
||||
logo_url: branding?.logo_url ?? '',
|
||||
email_greeting: branding?.email_greeting ?? '',
|
||||
});
|
||||
const debounced = useDebounced(emailBranding, 400);
|
||||
const { data, isError } = useQuery({
|
||||
queryKey: ['invite-email-preview', debounced],
|
||||
queryFn: () => previewInviteEmail({ branding: JSON.parse(debounced) }),
|
||||
placeholderData: (prev) => prev,
|
||||
});
|
||||
return (
|
||||
<div className="min-w-0 space-y-2">
|
||||
<Typography variant="muted" className="text-[10px] block">
|
||||
미리보기 — 실제 발송 템플릿을 샘플 견적으로 렌더한 것입니다.
|
||||
</Typography>
|
||||
<div className="border border-border rounded-md overflow-hidden">
|
||||
<div className="border-b border-border bg-background px-3 py-2">
|
||||
<Typography variant="caption" className="block text-muted-foreground">제목</Typography>
|
||||
<Typography variant="small" className="block font-semibold truncate">
|
||||
{data?.subject || '미리보기를 불러오는 중...'}
|
||||
</Typography>
|
||||
</div>
|
||||
{isError ? (
|
||||
<Typography variant="muted" className="block p-6 text-center">
|
||||
미리보기를 불러오지 못했습니다. 잠시 후 다시 시도하십시오.
|
||||
</Typography>
|
||||
) : (
|
||||
<iframe
|
||||
title="협상 초청 메일 미리보기"
|
||||
srcDoc={data?.html ?? ''}
|
||||
sandbox=""
|
||||
className="w-full h-[600px] bg-[#f4f5f7]"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 값이 delayMs 동안 잠잠해진 뒤에만 반영되는 디바운스 훅(미리보기 서버호출 절약용).
|
||||
function useDebounced(value: string, delayMs: number): string {
|
||||
const [debounced, setDebounced] = useState(value);
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setDebounced(value), delayMs);
|
||||
return () => clearTimeout(t);
|
||||
}, [value, delayMs]);
|
||||
return debounced;
|
||||
}
|
||||
|
||||
// 커스텀필드 정의 편집 — 표시명을 입력하면 key 를 자동 제안하되 직접 수정도 가능.
|
||||
function CustomFieldsEditor({
|
||||
title,
|
||||
|
||||
@@ -5,6 +5,8 @@ export type CustomFieldType = 'text' | 'number' | 'boolean' | 'select';
|
||||
|
||||
export type NegoBaselineField = 'price' | 'purchase_price';
|
||||
|
||||
export type VatMode = 'per_item' | 'unified_excluded';
|
||||
|
||||
export type CustomFieldDef = {
|
||||
key: string; // custom JSONB 의 키 (영문 snake_case)
|
||||
label: string; // 화면 표시명
|
||||
@@ -16,8 +18,7 @@ export type CompanySettings = {
|
||||
branding?: {
|
||||
service_name?: string; // 사이드바/타이틀 서비스명 (기본 NegoData)
|
||||
logo_url?: string; // 로고 이미지 URL. 없으면 색상 사각형+텍스트
|
||||
primary_color?: string; // 브랜드 색 (hex)
|
||||
email_header?: string; // 초청 메일 헤더 문구 (기본 NEGODATA)
|
||||
email_greeting?: string; // 초청 메일 인사 문구 ('OO 담당자님,' 다음 줄). 메일 헤더는 CI(logo_url·service_name)를 따르고 색은 솔루션 고정
|
||||
helpdesk?: string[]; // 헬프데스크 연락처 — 한 줄 = 담당자 한 명. 공급사 포털 3곳(로그인·메뉴·안내팝업)이 그대로 출력
|
||||
};
|
||||
labels?: Record<string, string>; // 카탈로그 키 → 이 회사 용어 (없으면 기본값)
|
||||
@@ -25,6 +26,9 @@ export type CompanySettings = {
|
||||
// 협상 기준가로 쓸 상품 가격 컬럼. 인하율 멘트의 분모이자 RL 가격 수용률의 기준가다.
|
||||
// 미설정이면 공급가(price) — 단 공급가를 숨긴 회사는 매입가로 폴백(협상 엔진).
|
||||
nego_baseline_field?: NegoBaselineField;
|
||||
// 부가세 관리 방식. 미설정=상품별(per_item). 전체 통일(unified_excluded)이면 상품 VAT 입력을
|
||||
// 숨기고(폼·엑셀) 공급사 협상 화면 가격에 'VAT 별도'를 고정 표기한다(협상 백엔드 chat_service).
|
||||
vat_mode?: VatMode;
|
||||
[key: string]: unknown; // 그 밖의 회사별 동작 플래그
|
||||
};
|
||||
guide_notices?: string[]; // 공급사 포털 협상 유의사항 항목 — 한 줄 = 안내 한 항목. 비면 기본 문구
|
||||
@@ -45,7 +49,7 @@ export type HideableFieldEntry = {
|
||||
|
||||
export const HIDEABLE_ITEM_FIELDS: HideableFieldEntry[] = [
|
||||
{ key: 'made_in', label: '원산지(제조 국가)', where: '상품 등록, 엑셀 양식' },
|
||||
{ key: 'vat_yn', label: '부가세포함', where: '상품 등록, 엑셀 양식' },
|
||||
// vat_yn 은 숨김 목록에서 뺐다 — 부가세는 '부가세(VAT) 관리' 모드(features.vat_mode)로 관리한다.
|
||||
{ key: 'delivery_fee_yn', label: '배송비포함', where: '상품 등록, 엑셀 양식' },
|
||||
{ key: 'spec', label: '규격', where: '상품 등록, 엑셀 양식' },
|
||||
{ key: 'manufacturer', label: '제조사', where: '상품 등록, 엑셀 양식' },
|
||||
@@ -69,7 +73,6 @@ export const HIDEABLE_ITEM_FIELDS: HideableFieldEntry[] = [
|
||||
key: 'price',
|
||||
label: '상품 단가(공급가)',
|
||||
where: '상품 목록·등록, 엑셀 양식',
|
||||
calcNote: '협상 기준가로 고른 경우 숨기지 말 것 — 인하율 멘트의 기준값이 비게 된다',
|
||||
},
|
||||
];
|
||||
// internet_lowest_price 는 숨김 대상에서 뺀다 — 신규 견적의 유일한 목표가 후보라
|
||||
@@ -89,7 +92,8 @@ export const LABEL_CATALOG: LabelCatalogEntry[] = [
|
||||
{ key: 'item.code', base: '상품코드', where: '상품 목록·등록, 엑셀 양식', group: '상품' },
|
||||
{ key: 'item.model_name', base: '모델번호', where: '상품 등록, 엑셀 양식', group: '상품' },
|
||||
{ key: 'category', base: '카테고리', where: '상품 목록·등록·필터, 통계', group: '상품' },
|
||||
{ key: 'item.price', base: '상품 단가', where: '상품 목록·등록, 엑셀 양식', group: '상품' },
|
||||
// 관리자 화면 전용 — 공급사 화면(포털·협상 멘트)의 기준가 표기는 '공급가'로 고정이라 이 용어를 타지 않는다.
|
||||
{ key: 'item.price', base: '상품 단가', where: '상품 목록·등록, 엑셀 양식 (관리자 화면 전용)', group: '상품' },
|
||||
{ key: 'item.purchase_price', base: '매입가', where: '상품 등록, 엑셀 양식', group: '상품' },
|
||||
{ key: 'item.selling_price', base: '판매가', where: '상품 등록, 엑셀 양식', group: '상품' },
|
||||
{ key: 'item.internet_lowest_price', base: '인터넷 최저가', where: '상품 목록·등록, 엑셀 양식', group: '상품' },
|
||||
@@ -155,6 +159,23 @@ export const NEGO_BASELINE_OPTIONS: {
|
||||
|
||||
export const DEFAULT_NEGO_BASELINE_FIELD: NegoBaselineField = 'price';
|
||||
|
||||
export const DEFAULT_VAT_MODE: VatMode = 'per_item';
|
||||
|
||||
// 부가세 관리 모드 선택지. 전체 통일은 'VAT 별도(제외)' 고정만 둔다 — 포함으로 통일하려는
|
||||
// 회사가 나오면 값을 추가한다(지금 만들면 안 쓰는 분기만 는다).
|
||||
export const VAT_MODE_OPTIONS: { value: VatMode; label: string; desc: string }[] = [
|
||||
{
|
||||
value: 'per_item',
|
||||
label: '상품별 관리',
|
||||
desc: '상품마다 부가세 포함 여부를 입력합니다. 공급사 협상 화면에는 상품에 입력된 값대로 VAT 포함/별도가 표기됩니다.',
|
||||
},
|
||||
{
|
||||
value: 'unified_excluded',
|
||||
label: '전체 통일 — VAT 별도(제외)',
|
||||
desc: '모든 가격을 VAT 제외 기준으로 통일합니다. 상품 등록·엑셀 양식에서 부가세 입력이 사라지고, 공급사 협상 화면 가격에는 항상 "VAT 별도"가 표기됩니다.',
|
||||
},
|
||||
];
|
||||
|
||||
// 공급사 포털 협상 유의사항 기본 문구. 설정이 비어 있을 때 포털이 쓰는 값과 같아야 한다
|
||||
// (포털 사본: frontend/src/features/chat/components/popup/GuideContent.tsx).
|
||||
// VAT·배송비 조건은 상품마다 달라 기본 문구에서 뺐다 — 필요한 회사가 항목으로 직접 넣는다.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useGetSettings, updateSettings, getGetSettingsQueryKey } from '@/api/generated/company-settings/company-settings';
|
||||
import { LABEL_DEFAULTS, type CompanySettings } from './catalog';
|
||||
import { LABEL_DEFAULTS, DEFAULT_VAT_MODE, type CompanySettings, type VatMode } from './catalog';
|
||||
|
||||
// 회사 커스터마이징 설정 조회 + 저장.
|
||||
// 조회는 전 유저(브랜딩/라벨 렌더용), 저장은 백엔드가 OWNER 로 게이트한다.
|
||||
@@ -26,18 +26,26 @@ export function useLabels() {
|
||||
}
|
||||
|
||||
// 숨김필드 헬퍼. isHidden('made_in') → 이 회사에서 감출 필드인지.
|
||||
// 부가세 전체 통일(features.vat_mode) 회사는 상품별 VAT 입력이 무의미하므로 vat_yn 을 숨김으로 친다 —
|
||||
// 상품 폼·엑셀 양식·데이터 내보내기가 이 헬퍼 하나를 읽어 함께 사라진다.
|
||||
export function useHiddenFields() {
|
||||
const { settings } = useCompanySettings();
|
||||
const hidden = settings.hidden_fields ?? [];
|
||||
return (key: string): boolean => hidden.includes(key);
|
||||
const vatUnified = settings.features?.vat_mode === 'unified_excluded';
|
||||
return (key: string): boolean => hidden.includes(key) || (vatUnified && key === 'vat_yn');
|
||||
}
|
||||
|
||||
// 브랜딩 헬퍼. 서비스명·로고 — 미설정 시 기본 브랜드(NegoData).
|
||||
// 부가세 관리 모드 헬퍼. 미설정이면 상품별(per_item).
|
||||
export function useVatMode(): VatMode {
|
||||
const { settings } = useCompanySettings();
|
||||
return settings.features?.vat_mode ?? DEFAULT_VAT_MODE;
|
||||
}
|
||||
|
||||
// 브랜딩 헬퍼. 서비스명·로고 — 미설정 시 기본 브랜드(NegoData). 색은 회사별 커스텀 없이 솔루션 고정.
|
||||
export function useBranding() {
|
||||
const { settings } = useCompanySettings();
|
||||
return {
|
||||
serviceName: settings.branding?.service_name || 'NegoData',
|
||||
logoUrl: settings.branding?.logo_url || null,
|
||||
primaryColor: settings.branding?.primary_color || null,
|
||||
};
|
||||
}
|
||||
@@ -23,8 +23,9 @@ export function StatisticsView({ data }: { data: StatData }) {
|
||||
const markupTrend = fillMonths(data.markupTrend, (month) => ({ month, rate: 0 }));
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* 임팩트 요약 KPI */}
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
|
||||
{/* 임팩트 요약 KPI — 6열은 초광폭(2xl)에서만. xl 구간은 사이드바 빼면 타일이 ~170px 로 눌려
|
||||
라벨·증감칩이 여러 줄로 깨진다 → 3열 유지. */}
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 2xl:grid-cols-6">
|
||||
<StatTile
|
||||
label="총 절감액 (목표가 대비)"
|
||||
value={wonCompact(k.totalSavings)}
|
||||
|
||||
@@ -1,307 +0,0 @@
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { Typography } from '@/components/ui/typography';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
CardFooter,
|
||||
} from '@/components/ui/card';
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
|
||||
import {
|
||||
Table,
|
||||
TableHeader,
|
||||
TableBody,
|
||||
TableRow,
|
||||
TableHead,
|
||||
TableCell,
|
||||
} from '@/components/ui/table';
|
||||
import { TablePagination } from '@/components/ui/table-pagination';
|
||||
import {
|
||||
Dialog,
|
||||
DialogTrigger,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogClose,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Drawer,
|
||||
DrawerTrigger,
|
||||
DrawerContent,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
DrawerDescription,
|
||||
DrawerFooter,
|
||||
DrawerClose,
|
||||
} from '@/components/ui/drawer';
|
||||
import { Plus, Upload, TrendingDown, Trash2 } from 'lucide-react';
|
||||
import { showToast } from '@/lib/notify';
|
||||
|
||||
/**
|
||||
* 디자인시스템 쇼케이스 (dev 전용).
|
||||
* 라우터에서 import.meta.env.DEV일 때만 등록되므로 프로덕션 빌드에는 포함되지 않는다.
|
||||
* 토큰/프리미티브의 단일 출처를 눈으로 확인하고 맞추는 곳.
|
||||
*/
|
||||
export default function DevDesignPage() {
|
||||
const [switchOn, setSwitchOn] = useState(true);
|
||||
const [switchOff, setSwitchOff] = useState(false);
|
||||
const [demoPage, setDemoPage] = useState(2);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background text-foreground">
|
||||
<div className="mx-auto max-w-4xl px-6 py-12 space-y-12">
|
||||
<header className="space-y-1">
|
||||
<Typography variant="mono">네고시움 디자인시스템 · 개발 전용</Typography>
|
||||
<Typography variant="h1">디자인시스템</Typography>
|
||||
<Typography variant="muted">
|
||||
텍스트·색·컴포넌트의 단일 출처. 페이지에서 직접 클래스 박지 말고 여기 토큰을 쓴다.
|
||||
</Typography>
|
||||
</header>
|
||||
|
||||
<Section title="타이포그래피">
|
||||
<div className="space-y-2">
|
||||
<Typography variant="h1">H1 · 페이지 타이틀</Typography>
|
||||
<Typography variant="h2">H2 · 섹션 타이틀</Typography>
|
||||
<Typography variant="h3">H3 · 카드/모달 타이틀</Typography>
|
||||
<Typography variant="h4">H4 · 서브 타이틀</Typography>
|
||||
<Typography variant="body">Body · 기본 본문 텍스트입니다.</Typography>
|
||||
<Typography variant="small">Small · 작은 본문 텍스트입니다.</Typography>
|
||||
<Typography variant="muted">Muted · 보조 설명 텍스트입니다.</Typography>
|
||||
<Typography variant="label">Label · 폼 라벨</Typography>
|
||||
<br />
|
||||
<Typography variant="mono">Mono · 콘솔/메타 캡션</Typography>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="색상 토큰">
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||
<Swatch name="background" className="bg-background border border-border" />
|
||||
<Swatch name="card" className="bg-card border border-border" />
|
||||
<Swatch name="muted" className="bg-muted" />
|
||||
<Swatch name="primary" className="bg-primary" />
|
||||
<Swatch name="secondary" className="bg-secondary" />
|
||||
<Swatch name="destructive" className="bg-destructive" />
|
||||
<Swatch name="border" className="bg-border" />
|
||||
<Swatch name="foreground" className="bg-foreground" />
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="버튼">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{(['default', 'outline', 'secondary', 'ghost', 'destructive', 'link'] as const).map((v) => (
|
||||
<Button key={v} variant={v}>{v}</Button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2 pt-3">
|
||||
{(['xs', 'sm', 'default', 'lg'] as const).map((s) => (
|
||||
<Button key={s} size={s}>{s}</Button>
|
||||
))}
|
||||
<Button disabled>disabled</Button>
|
||||
</div>
|
||||
{/* 실제 사용 케이스: 아이콘+라벨, 카운트 배지, 위험 액션 */}
|
||||
<div className="flex flex-wrap items-center gap-2 pt-3">
|
||||
<Button><Plus />신규 등록</Button>
|
||||
<Button variant="outline"><Upload />엑셀 업로드</Button>
|
||||
<Button variant="outline">
|
||||
<TrendingDown />최저가 업데이트
|
||||
<Badge variant="destructive">3</Badge>
|
||||
</Button>
|
||||
<Button variant="destructive"><Trash2 />삭제</Button>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="배지">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{(['default', 'secondary', 'destructive', 'outline', 'ghost', 'link'] as const).map((v) => (
|
||||
<Badge key={v} variant={v}>{v}</Badge>
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="입력창">
|
||||
<div className="max-w-sm space-y-3">
|
||||
<Input placeholder="기본 입력" />
|
||||
<Input placeholder="비활성" disabled />
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="스위치">
|
||||
<div className="flex items-center gap-6">
|
||||
<label className="flex items-center gap-2">
|
||||
<Switch checked={switchOn} onCheckedChange={setSwitchOn} />
|
||||
<Typography variant="small">{switchOn ? '켜짐' : '꺼짐'}</Typography>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<Switch checked={switchOff} onCheckedChange={setSwitchOff} />
|
||||
<Typography variant="small">토글</Typography>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 opacity-60">
|
||||
<Switch checked disabled />
|
||||
<Typography variant="small">disabled</Typography>
|
||||
</label>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="카드">
|
||||
<Card className="max-w-sm">
|
||||
<CardHeader>
|
||||
<CardTitle>카드 타이틀</CardTitle>
|
||||
<CardDescription>shadcn Card 프리미티브. 패딩·보더·그림자 단일 출처.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Typography variant="small">카드 본문 영역입니다.</Typography>
|
||||
</CardContent>
|
||||
<CardFooter className="justify-end gap-2">
|
||||
<Button variant="outline" size="sm">취소</Button>
|
||||
<Button size="sm">확인</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</Section>
|
||||
|
||||
<Section title="탭">
|
||||
<Tabs defaultValue="overview" className="max-w-md">
|
||||
<TabsList>
|
||||
<TabsTrigger value="overview">개요</TabsTrigger>
|
||||
<TabsTrigger value="detail">상세</TabsTrigger>
|
||||
<TabsTrigger value="log">로그</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="overview" className="pt-3">
|
||||
<Typography variant="small">개요 탭 내용.</Typography>
|
||||
</TabsContent>
|
||||
<TabsContent value="detail" className="pt-3">
|
||||
<Typography variant="small">상세 탭 내용.</Typography>
|
||||
</TabsContent>
|
||||
<TabsContent value="log" className="pt-3">
|
||||
<Typography variant="small">로그 탭 내용.</Typography>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</Section>
|
||||
|
||||
<Section title="표">
|
||||
<div className="rounded-lg border border-border overflow-hidden">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>상품명</TableHead>
|
||||
<TableHead>코드</TableHead>
|
||||
<TableHead className="text-right">단가</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{[
|
||||
{ name: '배터리 팩', code: 'PROD-BAT-900', price: 1000000 },
|
||||
{ name: '인버터 블록', code: 'PROD-INV-11', price: 3200000 },
|
||||
].map((r) => (
|
||||
<TableRow key={r.code}>
|
||||
<TableCell className="font-medium">{r.name}</TableCell>
|
||||
<TableCell className="font-mono text-muted-foreground">{r.code}</TableCell>
|
||||
<TableCell className="text-right font-mono">₩{r.price.toLocaleString()}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="페이지네이션 푸터">
|
||||
<div className="rounded-lg border border-border overflow-hidden">
|
||||
<div className="p-4 text-center">
|
||||
<Typography variant="small" className="text-muted-foreground">표 하단에 들어가는 목록 페이지네이션</Typography>
|
||||
</div>
|
||||
<TablePagination
|
||||
page={demoPage}
|
||||
totalPages={12}
|
||||
totalCount={58}
|
||||
pageSize={5}
|
||||
onPageChange={setDemoPage}
|
||||
label="검색 결과"
|
||||
unit="건"
|
||||
/>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="모달">
|
||||
<Dialog>
|
||||
<DialogTrigger render={<Button variant="outline">모달 열기</Button>} />
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>모달 타이틀</DialogTitle>
|
||||
<DialogDescription>
|
||||
base-ui Dialog 프리미티브. 페이지마다 fixed inset-0 직접 짜지 말 것.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<DialogClose render={<Button variant="outline">취소</Button>} />
|
||||
<DialogClose render={<Button>확인</Button>} />
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</Section>
|
||||
|
||||
<Section title="드로어(사이드 패널)">
|
||||
<Drawer direction="right">
|
||||
<DrawerTrigger asChild><Button variant="outline">드로어 열기</Button></DrawerTrigger>
|
||||
<DrawerContent>
|
||||
<DrawerHeader>
|
||||
<DrawerTitle>드로어 타이틀</DrawerTitle>
|
||||
<DrawerDescription>
|
||||
vaul 기반 사이드 드로어. products의 등록/수정 패널이 이걸로 통일돼야 함.
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
<div className="px-4">
|
||||
<Typography variant="small">패널 본문 영역.</Typography>
|
||||
</div>
|
||||
<DrawerFooter>
|
||||
<Button>저장</Button>
|
||||
<DrawerClose asChild><Button variant="outline">닫기</Button></DrawerClose>
|
||||
</DrawerFooter>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
</Section>
|
||||
|
||||
<Section title="토스트">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" onClick={() => showToast('성공적으로 처리되었습니다.', 'success')}>
|
||||
success
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => showToast('참고할 정보입니다.', 'info')}>
|
||||
info
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => showToast('오류가 발생했습니다.', 'error')}>
|
||||
error
|
||||
</Button>
|
||||
</div>
|
||||
<Typography variant="muted" className="pt-2">
|
||||
전역 단일 출처: <code className="font-mono">showToast(message, type)</code> (sonner)
|
||||
</Typography>
|
||||
</Section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({ title, children }: { title: string; children: ReactNode }) {
|
||||
return (
|
||||
<section className="space-y-4 border-t border-border pt-8">
|
||||
<Typography variant="h2">{title}</Typography>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Swatch({ name, className }: { name: string; className: string }) {
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<div className={`h-14 w-full rounded-md ${className}`} />
|
||||
<Typography variant="mono" className="lowercase tracking-normal">{name}</Typography>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from 'react';
|
||||
import { Plus, Upload, TrendingDown, Download, FileDown, FileSpreadsheet, ChevronDown, Trash2 } from 'lucide-react';
|
||||
import { Plus, Upload, TrendingDown, Download, FileDown, FileSpreadsheet, ChevronDown, Trash2, ImagePlus } from 'lucide-react';
|
||||
import { useOverlayRouter } from '@/lib/useOverlayRouter';
|
||||
import { showToast } from '@/lib/notify';
|
||||
import { confirm } from '@/lib/confirm';
|
||||
@@ -18,6 +18,7 @@ import { ProductFormSheet } from '@/features/products/components/ProductFormShee
|
||||
import { PriceUpdateModal } from '@/features/products/components/PriceUpdateModal';
|
||||
import { LowestPriceHistorySheet } from '@/features/products/components/LowestPriceHistorySheet';
|
||||
import { ExcelUploadModal, downloadProductTemplate, downloadProductData } from '@/features/products/components/ExcelUploadModal';
|
||||
import { ImageBulkUploadModal } from '@/features/products/components/ImageBulkUploadModal';
|
||||
import { type Product } from '@/features/products/types';
|
||||
|
||||
export default function ProductsPage() {
|
||||
@@ -135,24 +136,29 @@ export default function ProductsPage() {
|
||||
{selectedIds.length > 0 && <Badge variant="destructive">{selectedIds.length}</Badge>}
|
||||
</Button>
|
||||
|
||||
{/* 엑셀 3종 + 이미지 일괄이 한 메뉴에 있어 버튼명은 '일괄 작업'으로 포괄, 항목에서 엑셀/이미지를 명시한다. */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger render={<Button variant="outline" />}>
|
||||
<FileSpreadsheet />
|
||||
엑셀업로드
|
||||
일괄 작업
|
||||
<ChevronDown />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem onClick={() => overlay.open('modal', 'excel')}>
|
||||
<Upload />
|
||||
일괄 업로드
|
||||
엑셀 일괄 업로드
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => downloadProductTemplate(label, settings.item_fields ?? [], isHidden)}>
|
||||
<Download />
|
||||
양식 다운로드
|
||||
엑셀 양식 다운로드
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={handleExport}>
|
||||
<FileDown />
|
||||
데이터 다운로드
|
||||
엑셀 데이터 다운로드
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => overlay.open('modal', 'images')}>
|
||||
<ImagePlus />
|
||||
이미지 일괄 업로드
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
@@ -242,6 +248,10 @@ export default function ProductsPage() {
|
||||
onClose={overlay.close}
|
||||
/>
|
||||
)}
|
||||
|
||||
{modal === 'images' && (
|
||||
<ImageBulkUploadModal open loadProducts={fetchAllForExport} onClose={overlay.close} />
|
||||
)}
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { Badge } from '@/components/ui/badge';
|
||||
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu';
|
||||
import { keepPreviousData } from '@tanstack/react-query';
|
||||
import { useOverlayRouter } from '@/lib/useOverlayRouter';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import { useAuthStore, canManage } from '@/stores/auth';
|
||||
import { confirm } from '@/lib/confirm';
|
||||
import { showToast } from '@/lib/notify';
|
||||
import { PageContainer } from '@/components/layout/PageContainer';
|
||||
@@ -30,11 +30,13 @@ export default function QuotationPage() {
|
||||
const mineFilter = list.filters.mine;
|
||||
const statusOptions = QUOTATION_STATUS_OPTIONS;
|
||||
const typeOptions = QUOTATION_TYPE_OPTIONS;
|
||||
// 일반(USER)은 본인 견적만 조회 — 작성자 필터를 숨기고 mine 을 고정한다(백엔드도 동일하게 강제).
|
||||
const isManager = useAuthStore((s) => canManage(s.user?.role));
|
||||
const params: ListQuotationsParams = {
|
||||
search: list.debouncedSearch || undefined,
|
||||
status: statusFilter !== 'ALL' ? statusFilter : undefined,
|
||||
type: typeFilter !== 'ALL' ? typeFilter : undefined,
|
||||
mine: mineFilter === 'MINE' ? true : undefined,
|
||||
mine: !isManager || mineFilter === 'MINE' ? true : undefined,
|
||||
page: list.page,
|
||||
size: list.pageSize,
|
||||
};
|
||||
@@ -159,18 +161,20 @@ export default function QuotationPage() {
|
||||
placeholder="견적명 또는 견적 번호로 검색..."
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<Select value={mineFilter} onValueChange={(v) => list.setFilter('mine', v as string)}>
|
||||
<SelectTrigger id="quotation-mine-filter">
|
||||
<SelectValue>
|
||||
{(value) => (value === 'MINE' ? '내 견적' : '전체 작성자 견적')}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="ALL">전체 작성자 견적</SelectItem>
|
||||
<SelectItem value="MINE">내 견적</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className={`grid gap-2 ${isManager ? 'grid-cols-3' : 'grid-cols-2'}`}>
|
||||
{isManager && (
|
||||
<Select value={mineFilter} onValueChange={(v) => list.setFilter('mine', v as string)}>
|
||||
<SelectTrigger id="quotation-mine-filter">
|
||||
<SelectValue>
|
||||
{(value) => (value === 'MINE' ? '내 견적' : '전체 작성자 견적')}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="ALL">전체 작성자 견적</SelectItem>
|
||||
<SelectItem value="MINE">내 견적</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
|
||||
<Select value={statusFilter} onValueChange={(v) => list.setFilter('status', v as string)}>
|
||||
<SelectTrigger id="quotation-status-filter">
|
||||
|
||||
Reference in new issue
Block a user