[feat] negodata: 알림함 — 견적 마감 결과(낙찰/재생성/결렬) 자동 통지

- company.notifications 테이블 + NotificationType(SUCCESS/REGENERATED/FAILURE)
- 백엔드 알림 조회/읽음 API + close_and_decide 결과 분기마다 알림 생성
- 헤더 알림 벨(안읽음 배지) + 알림 페이지(읽음·딥링크)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
minaChoiandClaude Opus 4.8 committed 2026-06-30 17:24:59 +09:00
1 parent b42cc41b5e
commit 1d111a031e
30 files changed
+995 -3

No files matched your search

@@ -65,6 +65,19 @@ class users(MainTableMixin, MAIN_BASE):
role = Column(SmallInteger, nullable=False, default=UserRole.USER.value)
class notifications(MainTableMixin, MAIN_BASE):
__tablename__ = "notifications"
__table_args__ = {"schema": "company"}
notification_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
user_id = Column(UUID(as_uuid=True), nullable=False, index=True) # 수신자(users.user_id) = 견적 작성자
type = Column(SmallInteger, nullable=False) # NotificationType: 1=success(낙찰) 2=regenerated(재생성) 3=failure(결렬)
ref_qt_id = Column(UUID(as_uuid=True), nullable=True) # 관련 견적(quotations.qt_id)
ref_session_id = Column(UUID(as_uuid=True), nullable=True) # 관련 세션(sessions.session_id)
data = Column(JSONB, nullable=True) # 렌더 스냅샷(유형별)
read_at = Column(DateTime(timezone=True), nullable=True) # 읽은 시각(NULL=안읽음)
class items(MainTableMixin, MAIN_BASE):
__tablename__ = "items"
__table_args__ = {"schema": "partner"}
+9
View File
@@ -172,6 +172,15 @@ class CloseOutcome(Enum):
REGEN_FAILED = "regen_failed" # 재생성 시도했으나 실패 — 원본은 CLOSED 인데 다음 라운드가 없음(체인 끊김, 모니터링 필요)
class NotificationType(CodeEnum):
"""company.notifications.type 코드값. 견적 생애 이벤트를 작성자에게 통지. 마감 결과 3종(SUCCESS/REGENERATED/FAILURE)은 close_and_decide 와 1:1. 네이밍은 KTC."""
SUCCESS = 1 # 낙찰(단독 최저가) — KTC SUCCESS
REGENERATED = 2 # 다음 라운드 자동 생성(동가/미참여) — KTC 대응어 없어 negodata 유지
FAILURE = 3 # 결렬: 낙찰 없이 마감(거절/부분/한도) — KTC FAILURE
CREATED = 4 # 견적 생성됨(작성 직후) — 생성 알림
class ChatSender(CodeEnum):
"""negotiation.chats.sender 코드값. 채팅 발신 주체."""
+107
View File
@@ -0,0 +1,107 @@
from abc import ABC, abstractmethod
from typing import Tuple
from sqlalchemy import select, func, update
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import notifications
from common.enums import ErrorType
from common.logger import LOG
# 알림 CRUD. 항상 user_id(수신자)로 스코프한다.
class INotificationCRUD(ABC):
@abstractmethod
async def list_for_user(self, cdb: AsyncSession, user_id, skip, limit) -> Tuple[ErrorType, list, int]:
pass
@abstractmethod
async def count_unread(self, cdb: AsyncSession, user_id) -> Tuple[ErrorType, int]:
pass
@abstractmethod
async def mark_read(self, cdb: AsyncSession, user_id, notification_id, ts) -> ErrorType:
pass
@abstractmethod
async def mark_all_read(self, cdb: AsyncSession, user_id, ts) -> ErrorType:
pass
class NotificationCRUD(INotificationCRUD):
async def list_for_user(self, cdb: AsyncSession, user_id, skip, limit) -> Tuple[ErrorType, list, int]:
try:
cnt_err, cnt_rows = await DB_SESSION_MNG.execute(
cdb,
select(func.count()).select_from(notifications).where(
notifications.user_id == user_id, notifications.deleted == False # noqa: E712
),
)
if cnt_err != ErrorType.SUCCESS:
return cnt_err, [], 0
total = int(cnt_rows[0] or 0) if cnt_rows else 0
list_err, rows = await DB_SESSION_MNG.execute(
cdb,
select(notifications)
.where(notifications.user_id == user_id, notifications.deleted == False) # noqa: E712
.order_by(notifications.created_at.desc())
.offset(skip)
.limit(limit),
)
if list_err != ErrorType.SUCCESS:
return list_err, [], 0
return ErrorType.SUCCESS, list(rows), total
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, [], 0
async def count_unread(self, cdb: AsyncSession, user_id) -> Tuple[ErrorType, int]:
try:
err_type, rows = await DB_SESSION_MNG.execute(
cdb,
select(func.count()).select_from(notifications).where(
notifications.user_id == user_id,
notifications.read_at.is_(None),
notifications.deleted == False, # noqa: E712
),
)
if err_type != ErrorType.SUCCESS:
return err_type, 0
return ErrorType.SUCCESS, (int(rows[0] or 0) if rows else 0)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0
async def mark_read(self, cdb: AsyncSession, user_id, notification_id, ts) -> ErrorType:
try:
query = (
update(notifications)
.where(
notifications.notification_id == notification_id,
notifications.user_id == user_id, # 남의 알림 못 건드리게 수신자 스코프
notifications.read_at.is_(None),
)
.values(read_at=ts, updated_at=ts)
)
return await DB_SESSION_MNG.add(cdb, query)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED
async def mark_all_read(self, cdb: AsyncSession, user_id, ts) -> ErrorType:
try:
query = (
update(notifications)
.where(
notifications.user_id == user_id,
notifications.read_at.is_(None),
notifications.deleted == False, # noqa: E712
)
.values(read_at=ts, updated_at=ts)
)
return await DB_SESSION_MNG.add(cdb, query)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED
+2
View File
@@ -18,6 +18,7 @@ import router.v1.card.card
import router.v1.quotation.quotation
import router.v1.quotation_setting.quotation_setting
import router.v1.dashboard.dashboard
import router.v1.notification.notification
API_SERVER_START_TIME = GTime.UTCStr()
@@ -71,3 +72,4 @@ app.include_router(router.v1.card.card.router)
app.include_router(router.v1.quotation.quotation.router)
app.include_router(router.v1.quotation_setting.quotation_setting.router)
app.include_router(router.v1.dashboard.dashboard.router)
app.include_router(router.v1.notification.notification.router)
@@ -0,0 +1,32 @@
from uuid import UUID
from fastapi import APIRouter, Depends
from common.models.gmodel import PageParams, UserInfo
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse
from services.notification import NotificationService
from .protocol import Res_NotificationList, Res_NotificationRead
# 알림(인박스) 라우터. 항상 로그인 유저(user_info.user_id) 기준으로 조회/처리한다.
router = APIRouter(prefix="/v1/notification", tags=["Notification"], responses={404: {"description": "Not found"}})
@router.get(path="/list", response_model=Res_NotificationList, summary="알림 목록(+안읽음 수)")
async def list_notifications(
service: NotificationService = Depends(),
user_info: UserInfo = Depends(IsValidAccessToken),
pg: PageParams = Depends(),
):
return RemoveNoneResponse(await service.list_notifications(user_info.user_id, pg))
@router.post(path="/read-all", response_model=Res_NotificationRead, summary="전체 읽음 처리")
async def read_all(service: NotificationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
return RemoveNoneResponse(await service.mark_all_read(user_info.user_id))
@router.post(path="/{notification_id}/read", response_model=Res_NotificationRead, summary="알림 읽음 처리")
async def read_one(
notification_id: UUID, service: NotificationService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)
):
return RemoveNoneResponse(await service.mark_read(user_info.user_id, str(notification_id)))
@@ -0,0 +1,33 @@
import uuid
from datetime import datetime
from typing import Any, Optional
from pydantic import ConfigDict
from common.enums import NotificationType
from common.models.gmodel import Res_PageProtocol, Res_WebPacketProtocol, WebPacketProtocol
class NotificationProtocol(WebPacketProtocol):
pass
class NotificationData(WebPacketProtocol):
model_config = ConfigDict(from_attributes=True)
notification_id: uuid.UUID
type: NotificationType
ref_qt_id: Optional[uuid.UUID] = None
ref_session_id: Optional[uuid.UUID] = None
data: Optional[Any] = None # 렌더 스냅샷(유형별 필드)
read_at: Optional[datetime] = None
created_at: Optional[datetime] = None
class Res_NotificationList(Res_PageProtocol):
notifications: list[NotificationData] = []
unread: int = 0 # 안읽음 총수(헤더 빨콩이)
class Res_NotificationRead(Res_WebPacketProtocol):
pass
+88
View File
@@ -0,0 +1,88 @@
import uuid
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import notifications
from common.enums import DBWRType, ErrorType, NotificationType
from common.logger import LOG
from common.models.gmodel import PageParams
from common.utils.gtime import GTime
from crud.notification_crud import INotificationCRUD, NotificationCRUD
from router.v1.notification.protocol import NotificationData, Res_NotificationList, Res_NotificationRead
def _as_uuid(v):
return uuid.UUID(v) if isinstance(v, str) else v
async def create_notification(
user_id,
ntype: NotificationType,
data: dict,
ref_qt_id=None,
ref_session_id=None,
) -> None:
"""알림 1건 기록(인박스). 수신자=user_id(견적 작성자), data=렌더 스냅샷(유형별 필드).
부가 효과라 실패해도 본 흐름을 막지 않는다(raise 안 함, 로그만)."""
notif = notifications(
user_id=_as_uuid(user_id),
type=ntype.value,
ref_qt_id=_as_uuid(ref_qt_id) if ref_qt_id else None,
ref_session_id=_as_uuid(ref_session_id) if ref_session_id else None,
data=data,
)
err = await DB_SESSION_MNG.execute_lambda_run(
[notifications.DBType()],
[lambda s: DB_SESSION_MNG.insert(s, notif, raise_error=False)],
)
if err != ErrorType.SUCCESS:
LOG.e_no_callstack(f"[notify] 알림 기록 실패 user={user_id} type={ntype.name}")
class NotificationService:
"""알림 조회/읽음 처리(헤더 벨·알림 페이지). 항상 로그인 유저(user_id)로 스코프."""
def __init__(self, crud: INotificationCRUD = Depends(NotificationCRUD)):
self.crud = crud
async def list_notifications(self, user_id: str, pg: PageParams) -> Res_NotificationList:
res = Res_NotificationList(page=pg.page, size=pg.size)
uid = uuid.UUID(user_id)
err_type, rows, total = await DB_SESSION_MNG.execute_lambda(
notifications.DBType(),
DBWRType.DB_READ.value,
lambda s: self.crud.list_for_user(s, uid, pg.skip, pg.size),
)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
res.notifications = [NotificationData.model_validate(r) for r in rows]
res.total = total
_e, unread = await DB_SESSION_MNG.execute_lambda(
notifications.DBType(),
DBWRType.DB_READ.value,
lambda s: self.crud.count_unread(s, uid),
)
res.unread = unread if _e == ErrorType.SUCCESS else 0
return res
async def mark_read(self, user_id: str, notification_id: str) -> Res_NotificationRead:
res = Res_NotificationRead()
err_type = await DB_SESSION_MNG.execute_lambda_run(
[notifications.DBType()],
[lambda s: self.crud.mark_read(s, uuid.UUID(user_id), uuid.UUID(notification_id), GTime.UTC())],
)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
async def mark_all_read(self, user_id: str) -> Res_NotificationRead:
res = Res_NotificationRead()
err_type = await DB_SESSION_MNG.execute_lambda_run(
[notifications.DBType()],
[lambda s: self.crud.mark_all_read(s, uuid.UUID(user_id), GTime.UTC())],
)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
+30 -1
View File
@@ -7,7 +7,7 @@ from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import quotations, sessions, chats, versions, version_nego_cards, version_wild_cards
from common.enums import CloseOutcome, DBWRType, ErrorType, QuotationStatus, QuotationType, SessionStatus
from common.enums import CloseOutcome, DBWRType, ErrorType, NotificationType, QuotationStatus, QuotationType, SessionStatus
from common.logger import LOG
from common.models.gmodel import PageParams
from common.utils.gtime import GTime
@@ -34,6 +34,7 @@ from router.v1.quotation.protocol import (
TargetCandidate,
)
from services.email import EmailUnavailable, build_invite_email, send_email
from services.notification import create_notification
class QuotationService:
@@ -620,6 +621,13 @@ class QuotationService:
# 1) 단독 낙찰 → 확정
if winner is not None:
await self._award_and_close(qt_uuid, winner)
winner_price = min((int(bp) for _, bp, _ in done if bp is not None), default=None)
await create_notification(
original.user_id, NotificationType.SUCCESS,
{"qt_name": original.name, "qt_number": original.number,
"winner_name": winner["name"], "winner_price": winner_price},
ref_qt_id=qt_uuid,
)
return CloseOutcome.AWARDED
# 동가/미참여 재생성은 사유별 한도(각 1번, 순서 무관) 확인 후
@@ -637,10 +645,21 @@ class QuotationService:
f"code={regen.result.code}({regen.result.desc})"
)
return CloseOutcome.REGEN_FAILED
await create_notification(
original.user_id, NotificationType.REGENERATED,
{"qt_name": original.name, "qt_number": original.number, "reason": "equal",
"next_round": original.round + 1, "tied_price": equal["price"], "tied_count": len(equal["suppliers"])},
ref_qt_id=regen.qt_id,
)
return CloseOutcome.REGENERATED
# 3) 협상거부 있음 → 마감만 (재생성 안 함)
if has_rejected:
await self._just_close(qt_uuid)
await create_notification(
original.user_id, NotificationType.FAILURE,
{"qt_name": original.name, "qt_number": original.number, "reason": "rejected"},
ref_qt_id=qt_uuid,
)
return CloseOutcome.CLOSED
# 4) 전원 미참여 → 공급사 전체로 다음 라운드 (체인에 미참여 재생성 이력 없을 때만)
if not done and rows and no_part_used < self.MAX_REGEN_PER_CAUSE:
@@ -654,9 +673,19 @@ class QuotationService:
f"code={regen.result.code}({regen.result.desc})"
)
return CloseOutcome.REGEN_FAILED
await create_notification(
original.user_id, NotificationType.REGENERATED,
{"qt_name": original.name, "qt_number": original.number, "reason": "no_show", "next_round": original.round + 1},
ref_qt_id=regen.qt_id,
)
return CloseOutcome.REGENERATED
# 5) 그 외 / 한도 도달 → 마감만
await self._just_close(qt_uuid)
await create_notification(
original.user_id, NotificationType.FAILURE,
{"qt_name": original.name, "qt_number": original.number, "reason": "closed"},
ref_qt_id=qt_uuid,
)
return CloseOutcome.CLOSED
async def _chain_regen_counts(self, number: str, current_round: int) -> tuple[int, int]: