[feat] negodata: 협력사↔상품 매핑(취급상품·공급유형) + 견적 픽리스트 서버검색 콤보박스
- partner.supplier_items 매핑테이블 신설: supply_type(0없음/1유통/2제조/3총판), 부분 유니크 인덱스(soft-delete 인지). quotations.supplier_type와 의미단위 달라 컬럼명 supply_type. - 백엔드: supplier_item CRUD/service/router(/v1/supplier-item, by-supplier·by-item·create·bulk·update·delete). 소유권 company 스코프. ErrorType.SUPPLIER_ITEM_NOT_FOUND 추가. - DDL: 01-schema/04-alter(날짜접미 리네임) + dev DB 반영. - 프론트(feature): 협력사 엑셀 '취급상품' 컬럼(콤마 상품명→일괄매핑, 이름 미매칭 스킵+리포트, 유형 안받고 없음), 협력사 상세 취급상품 관리(추가/삭제/유형변경 즉시반영), 견적모달 협력사 리스트에 선택상품 공급유형 배지. - 재사용 서버검색 Combobox 신설 → 취급상품·견적상품·협력사초청·협상카드 픽리스트에 적용(size 100 캡 해소, 검색은 서버 ILIKE). 견적 선택상품 파생값은 useGetItem 단건조회로 안정화. - orval 재생성(supplier-item 클라이언트/모델). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
ed175c5b65
commit
43dbcbcd96
37 files changed
+1871
-91
No files matched your search
@@ -124,7 +124,19 @@ class suppliers(MainTableMixin, MAIN_BASE):
|
||||
manager_name = Column(String(50), nullable=True)
|
||||
manager_email = Column(String(255), nullable=True)
|
||||
manager_contact_number = Column(String(20), nullable=True) # ERD 오타(manger) 교정
|
||||
total_revenue = Column(BigInteger, nullable=True) # 총매출액(원)
|
||||
total_revenue = Column(BigInteger, nullable=True) # 총매출액
|
||||
|
||||
|
||||
class supplier_items(MainTableMixin, MAIN_BASE):
|
||||
__tablename__ = "supplier_items"
|
||||
# (supplier_id, item_id) 유일성은 soft-delete 인지 부분 유니크 인덱스(uq_supplier_items, WHERE deleted=FALSE)로 DB에서 보장.
|
||||
__table_args__ = {"schema": "partner"}
|
||||
|
||||
supplier_item_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
supplier_id = Column(UUID(as_uuid=True), nullable=False, index=True) # suppliers.supplier_id
|
||||
item_id = Column(UUID(as_uuid=True), nullable=False, index=True) # items.item_id
|
||||
# SupplierType: 이 협력사가 이 상품을 공급하는 방식(0=없음/1=유통/2=제조/3=총판). quotations.supplier_type 와 값은 같으나 의미 단위가 (협력사,상품)이라 컬럼명은 supply_type.
|
||||
supply_type = Column(SmallInteger, nullable=False, server_default=text("0"), default=0)
|
||||
|
||||
|
||||
class nego_cards(MainTableMixin, MAIN_BASE):
|
||||
|
||||
@@ -57,6 +57,7 @@ class ErrorType(Enum):
|
||||
# 협력사 관련 에러
|
||||
SUPPLIER_NOT_FOUND = 1400
|
||||
SUPPLIER_CODE_DUPLICATE = auto()
|
||||
SUPPLIER_ITEM_NOT_FOUND = auto() # 협력사-상품 매핑 미존재
|
||||
|
||||
# 견적 관련 에러
|
||||
QUOTATION_NOT_FOUND = 1500
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
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 supplier_items, items
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
|
||||
|
||||
# 협력사-상품 매핑 CRUD. 스코프는 상위(협력사/상품)가 company_id 로 이미 걸린다.
|
||||
class ISupplierItemCRUD(ABC):
|
||||
@abstractmethod
|
||||
async def list_by_supplier(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, list]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def list_by_item(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, list]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_by_id(self, cdb: AsyncSession, supplier_item_id) -> Tuple[ErrorType, supplier_items]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def existing_item_ids(self, cdb: AsyncSession, supplier_id, item_ids: list) -> Tuple[ErrorType, list]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def find_items_by_names(self, cdb: AsyncSession, company_id, names: list) -> Tuple[ErrorType, list]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def add_many(self, cdb: AsyncSession, mappings: list) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def update_type(self, cdb: AsyncSession, supplier_item_id, supply_type: int) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def soft_delete(self, cdb: AsyncSession, supplier_item_id) -> ErrorType:
|
||||
pass
|
||||
|
||||
|
||||
class SupplierItemCRUD(ISupplierItemCRUD):
|
||||
async def list_by_supplier(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, list]:
|
||||
# 협력사 상세용: 매핑 + 상품명/코드 조인. Row(supplier_item_id, item_id, name, code, supply_type)
|
||||
try:
|
||||
query = (
|
||||
select(
|
||||
supplier_items.supplier_item_id,
|
||||
supplier_items.item_id,
|
||||
items.name,
|
||||
items.code,
|
||||
supplier_items.supply_type,
|
||||
)
|
||||
.join(items, items.item_id == supplier_items.item_id)
|
||||
.where(
|
||||
supplier_items.supplier_id == supplier_id,
|
||||
supplier_items.deleted == False, # noqa: E712
|
||||
items.deleted == False, # noqa: E712
|
||||
)
|
||||
.order_by(supplier_items.created_at.desc())
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, []
|
||||
return ErrorType.SUCCESS, list(rows)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, []
|
||||
|
||||
async def list_by_item(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, list]:
|
||||
# 견적생성 모달용: 이 상품을 취급하는 협력사별 공급유형. Row(supplier_id, supply_type)
|
||||
try:
|
||||
query = select(supplier_items.supplier_id, supplier_items.supply_type).where(
|
||||
supplier_items.item_id == item_id,
|
||||
supplier_items.deleted == False, # noqa: E712
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, []
|
||||
return ErrorType.SUCCESS, list(rows)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, []
|
||||
|
||||
async def get_by_id(self, cdb: AsyncSession, supplier_item_id) -> Tuple[ErrorType, supplier_items]:
|
||||
try:
|
||||
query = select(supplier_items).where(
|
||||
supplier_items.supplier_item_id == supplier_item_id,
|
||||
supplier_items.deleted == False, # noqa: E712
|
||||
).limit(1)
|
||||
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, None
|
||||
if len(row_list) != 1:
|
||||
return ErrorType.DB_INVALID_KEY, None
|
||||
return ErrorType.SUCCESS, row_list[0]
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def existing_item_ids(self, cdb: AsyncSession, supplier_id, item_ids: list) -> Tuple[ErrorType, list]:
|
||||
# 이 협력사에 이미 매핑된 item_id 들(중복 등록 스킵용).
|
||||
try:
|
||||
if not item_ids:
|
||||
return ErrorType.SUCCESS, []
|
||||
query = select(supplier_items.item_id).where(
|
||||
supplier_items.supplier_id == supplier_id,
|
||||
supplier_items.item_id.in_(item_ids),
|
||||
supplier_items.deleted == False, # noqa: E712
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, []
|
||||
return ErrorType.SUCCESS, [r for r in rows if r is not None]
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, []
|
||||
|
||||
async def find_items_by_names(self, cdb: AsyncSession, company_id, names: list) -> Tuple[ErrorType, list]:
|
||||
# 상품명(정확 일치) → 상품. Row(item_id, name). 이름 중복 상품이 있으면 여럿 반환될 수 있다(서비스에서 첫 매칭 사용).
|
||||
try:
|
||||
if not names:
|
||||
return ErrorType.SUCCESS, []
|
||||
query = select(items.item_id, items.name).where(
|
||||
items.company_id == company_id,
|
||||
items.name.in_(names),
|
||||
items.deleted == False, # noqa: E712
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, []
|
||||
return ErrorType.SUCCESS, list(rows)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, []
|
||||
|
||||
async def add_many(self, cdb: AsyncSession, mappings: list) -> ErrorType:
|
||||
try:
|
||||
if not mappings:
|
||||
return ErrorType.SUCCESS
|
||||
return await DB_SESSION_MNG.insert(cdb, mappings)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
|
||||
async def update_type(self, cdb: AsyncSession, supplier_item_id, supply_type: int) -> ErrorType:
|
||||
try:
|
||||
query = (
|
||||
update(supplier_items)
|
||||
.where(supplier_items.supplier_item_id == supplier_item_id)
|
||||
.values(supply_type=supply_type, updated_at=GTime.UTC())
|
||||
)
|
||||
return await DB_SESSION_MNG.add(cdb, query)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
|
||||
async def soft_delete(self, cdb: AsyncSession, supplier_item_id) -> ErrorType:
|
||||
try:
|
||||
query = (
|
||||
update(supplier_items)
|
||||
.where(supplier_items.supplier_item_id == supplier_item_id)
|
||||
.values(deleted=True, updated_at=GTime.UTC())
|
||||
)
|
||||
return await DB_SESSION_MNG.add(cdb, query)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
@@ -14,6 +14,7 @@ import router.v1.auth.account
|
||||
import router.v1.company.user
|
||||
import router.v1.item.item
|
||||
import router.v1.supplier.supplier
|
||||
import router.v1.supplier_item.supplier_item
|
||||
import router.v1.card.card
|
||||
import router.v1.quotation.quotation
|
||||
import router.v1.quotation_setting.quotation_setting
|
||||
@@ -68,6 +69,7 @@ app.include_router(router.v1.auth.account.router)
|
||||
app.include_router(router.v1.company.user.router)
|
||||
app.include_router(router.v1.item.item.router)
|
||||
app.include_router(router.v1.supplier.supplier.router)
|
||||
app.include_router(router.v1.supplier_item.supplier_item.router)
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import ConfigDict
|
||||
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
class SupplierItemProtocol(WebPacketProtocol):
|
||||
pass
|
||||
|
||||
|
||||
class Req_CreateSupplierItem(SupplierItemProtocol):
|
||||
supplier_id: uuid.UUID
|
||||
item_id: uuid.UUID
|
||||
supply_type: int = 0
|
||||
|
||||
|
||||
class Req_UpdateSupplyType(SupplierItemProtocol):
|
||||
supply_type: int
|
||||
|
||||
|
||||
class Req_BulkMapByNames(SupplierItemProtocol):
|
||||
names: list[str] = []
|
||||
|
||||
|
||||
class SupplierItemData(WebPacketProtocol):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
supplier_item_id: uuid.UUID
|
||||
item_id: uuid.UUID
|
||||
item_name: str
|
||||
item_code: Optional[str] = None
|
||||
supply_type: int
|
||||
created_at: Optional[datetime] = None
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class ItemSupplyType(WebPacketProtocol):
|
||||
supplier_id: uuid.UUID
|
||||
supply_type: int
|
||||
|
||||
|
||||
class Res_SupplierItem(Res_WebPacketProtocol):
|
||||
supplier_item: Optional[SupplierItemData] = None
|
||||
|
||||
|
||||
class Res_SupplierItemList(Res_WebPacketProtocol):
|
||||
supplier_items: list[SupplierItemData] = []
|
||||
|
||||
|
||||
class Res_ItemSupplyTypeList(Res_WebPacketProtocol):
|
||||
suppliers: list[ItemSupplyType] = []
|
||||
|
||||
|
||||
class Res_BulkMapByNames(Res_WebPacketProtocol):
|
||||
created_count: int = 0
|
||||
skipped_count: int = 0 # 이미 매핑돼 있어 건너뛴 상품 수
|
||||
unmatched: list[str] = [] # 회사 상품 목록에 이름이 없어 매핑 못한 입력명들
|
||||
@@ -0,0 +1,61 @@
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from common.models.gmodel import Res_WebPacketProtocol, UserInfo
|
||||
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse
|
||||
from services.supplier_item_service import SupplierItemService
|
||||
from .protocol import (
|
||||
Req_BulkMapByNames,
|
||||
Req_CreateSupplierItem,
|
||||
Req_UpdateSupplyType,
|
||||
Res_BulkMapByNames,
|
||||
Res_ItemSupplyTypeList,
|
||||
Res_SupplierItem,
|
||||
Res_SupplierItemList,
|
||||
)
|
||||
|
||||
# 협력사-상품 매핑 라우터. company_id 스코프는 상위 협력사/상품 소유권으로 확인.
|
||||
router = APIRouter(prefix="/v1/supplier-item", tags=["SupplierItem"], responses={404: {"description": "Not found"}})
|
||||
|
||||
|
||||
@router.get(path="/by-supplier/{supplier_id}", response_model=Res_SupplierItemList, summary="협력사 취급상품 목록")
|
||||
async def list_supplier_items(
|
||||
supplier_id: UUID, service: SupplierItemService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)
|
||||
):
|
||||
return RemoveNoneResponse(await service.list_by_supplier(user_info.company_id, str(supplier_id)))
|
||||
|
||||
|
||||
@router.get(path="/by-item/{item_id}", response_model=Res_ItemSupplyTypeList, summary="상품 취급 협력사 공급유형 목록")
|
||||
async def list_item_supply_types(
|
||||
item_id: UUID, service: SupplierItemService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)
|
||||
):
|
||||
return RemoveNoneResponse(await service.list_by_item(user_info.company_id, str(item_id)))
|
||||
|
||||
|
||||
@router.post(path="/create", response_model=Res_SupplierItem, summary="취급상품 매핑 추가")
|
||||
async def create_supplier_item(
|
||||
req: Req_CreateSupplierItem, service: SupplierItemService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)
|
||||
):
|
||||
return RemoveNoneResponse(await service.create(user_info.company_id, req))
|
||||
|
||||
|
||||
@router.post(path="/by-supplier/{supplier_id}/bulk", response_model=Res_BulkMapByNames, summary="취급상품 이름 일괄 매핑(엑셀 업로드)")
|
||||
async def bulk_map_supplier_items(
|
||||
supplier_id: UUID, req: Req_BulkMapByNames, service: SupplierItemService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)
|
||||
):
|
||||
return RemoveNoneResponse(await service.bulk_map_by_names(user_info.company_id, str(supplier_id), req.names))
|
||||
|
||||
|
||||
@router.patch(path="/update/{supplier_item_id}", response_model=Res_WebPacketProtocol, summary="취급상품 공급유형 수정")
|
||||
async def update_supply_type(
|
||||
supplier_item_id: UUID, req: Req_UpdateSupplyType, service: SupplierItemService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)
|
||||
):
|
||||
return RemoveNoneResponse(await service.update_type(user_info.company_id, str(supplier_item_id), req))
|
||||
|
||||
|
||||
@router.delete(path="/delete/{supplier_item_id}", response_model=Res_WebPacketProtocol, summary="취급상품 매핑 삭제")
|
||||
async def delete_supplier_item(
|
||||
supplier_item_id: UUID, service: SupplierItemService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)
|
||||
):
|
||||
return RemoveNoneResponse(await service.delete(user_info.company_id, str(supplier_item_id)))
|
||||
@@ -0,0 +1,264 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import supplier_items
|
||||
from common.enums import DBWRType, ErrorType, SupplierType
|
||||
from common.models.gmodel import Res_WebPacketProtocol
|
||||
from crud.item_crud import IItemCRUD, ItemCRUD
|
||||
from crud.supplier_crud import ISupplierCRUD, SupplierCRUD
|
||||
from crud.supplier_item_crud import ISupplierItemCRUD, SupplierItemCRUD
|
||||
from router.v1.supplier_item.protocol import (
|
||||
ItemSupplyType,
|
||||
Req_CreateSupplierItem,
|
||||
Req_UpdateSupplyType,
|
||||
Res_BulkMapByNames,
|
||||
Res_ItemSupplyTypeList,
|
||||
Res_SupplierItem,
|
||||
Res_SupplierItemList,
|
||||
SupplierItemData,
|
||||
)
|
||||
|
||||
_VALID_SUPPLY_TYPES = {e.value for e in SupplierType}
|
||||
|
||||
|
||||
class SupplierItemService:
|
||||
"""협력사-상품 매핑 로직. 소유권은 상위 협력사/상품의 company_id 로 확인한다(멀티테넌트)."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
supplier_item_crud: ISupplierItemCRUD = Depends(SupplierItemCRUD),
|
||||
supplier_crud: ISupplierCRUD = Depends(SupplierCRUD),
|
||||
item_crud: IItemCRUD = Depends(ItemCRUD),
|
||||
):
|
||||
self.supplier_item_crud = supplier_item_crud
|
||||
self.supplier_crud = supplier_crud
|
||||
self.item_crud = item_crud
|
||||
|
||||
async def _supplier_owned(self, company_uuid: uuid.UUID, supplier_id: uuid.UUID) -> ErrorType:
|
||||
err_type, supplier = await DB_SESSION_MNG.execute_lambda(
|
||||
supplier_items.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.supplier_crud.get_by_id(s, supplier_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or supplier is None or supplier.company_id != company_uuid:
|
||||
return ErrorType.SUPPLIER_NOT_FOUND
|
||||
return ErrorType.SUCCESS
|
||||
|
||||
async def _item_owned(self, company_uuid: uuid.UUID, item_id: uuid.UUID):
|
||||
err_type, item = await DB_SESSION_MNG.execute_lambda(
|
||||
supplier_items.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.item_crud.get_by_id(s, item_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or item is None or item.company_id != company_uuid:
|
||||
return ErrorType.ITEM_NOT_FOUND, None
|
||||
return ErrorType.SUCCESS, item
|
||||
|
||||
async def _fetch_owned_mapping(self, company_uuid: uuid.UUID, supplier_item_id: uuid.UUID):
|
||||
"""매핑 조회 + 소유 협력사 확인. (ErrorType, mapping|None) 반환."""
|
||||
err_type, mapping = await DB_SESSION_MNG.execute_lambda(
|
||||
supplier_items.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.supplier_item_crud.get_by_id(s, supplier_item_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or mapping is None:
|
||||
return ErrorType.SUPPLIER_ITEM_NOT_FOUND, None
|
||||
own_err = await self._supplier_owned(company_uuid, mapping.supplier_id)
|
||||
if own_err != ErrorType.SUCCESS:
|
||||
return ErrorType.SUPPLIER_ITEM_NOT_FOUND, None
|
||||
return ErrorType.SUCCESS, mapping
|
||||
|
||||
async def list_by_supplier(self, company_id: str, supplier_id: str) -> Res_SupplierItemList:
|
||||
res = Res_SupplierItemList()
|
||||
own_err = await self._supplier_owned(uuid.UUID(company_id), uuid.UUID(supplier_id))
|
||||
if own_err != ErrorType.SUCCESS:
|
||||
res.result.SetResult(own_err)
|
||||
return res
|
||||
|
||||
err_type, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
supplier_items.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.supplier_item_crud.list_by_supplier(s, uuid.UUID(supplier_id)),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
# Row(supplier_item_id, item_id, name, code, supply_type)
|
||||
res.supplier_items = [
|
||||
SupplierItemData(
|
||||
supplier_item_id=r[0], item_id=r[1], item_name=r[2], item_code=r[3], supply_type=r[4]
|
||||
)
|
||||
for r in rows
|
||||
]
|
||||
return res
|
||||
|
||||
async def list_by_item(self, company_id: str, item_id: str) -> Res_ItemSupplyTypeList:
|
||||
res = Res_ItemSupplyTypeList()
|
||||
own_err, _ = await self._item_owned(uuid.UUID(company_id), uuid.UUID(item_id))
|
||||
if own_err != ErrorType.SUCCESS:
|
||||
res.result.SetResult(own_err)
|
||||
return res
|
||||
|
||||
err_type, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
supplier_items.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.supplier_item_crud.list_by_item(s, uuid.UUID(item_id)),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
# Row(supplier_id, supply_type)
|
||||
res.suppliers = [ItemSupplyType(supplier_id=r[0], supply_type=r[1]) for r in rows]
|
||||
return res
|
||||
|
||||
async def create(self, company_id: str, req: Req_CreateSupplierItem) -> Res_SupplierItem:
|
||||
res = Res_SupplierItem()
|
||||
company_uuid = uuid.UUID(company_id)
|
||||
|
||||
if req.supply_type not in _VALID_SUPPLY_TYPES:
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
return res
|
||||
|
||||
own_err = await self._supplier_owned(company_uuid, req.supplier_id)
|
||||
if own_err != ErrorType.SUCCESS:
|
||||
res.result.SetResult(own_err)
|
||||
return res
|
||||
item_err, item = await self._item_owned(company_uuid, req.item_id)
|
||||
if item_err != ErrorType.SUCCESS:
|
||||
res.result.SetResult(item_err)
|
||||
return res
|
||||
|
||||
# 활성 중복 매핑 차단(부분 유니크 인덱스와 이중 방어).
|
||||
dup_err, existing = await DB_SESSION_MNG.execute_lambda(
|
||||
supplier_items.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.supplier_item_crud.existing_item_ids(s, req.supplier_id, [req.item_id]),
|
||||
)
|
||||
if dup_err != ErrorType.SUCCESS:
|
||||
res.result.SetResult(dup_err)
|
||||
return res
|
||||
if existing:
|
||||
res.result.SetResult(ErrorType.DB_ALREADY_SAME_KEY)
|
||||
return res
|
||||
|
||||
mapping = supplier_items(supplier_id=req.supplier_id, item_id=req.item_id, supply_type=req.supply_type)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[supplier_items.DBType()],
|
||||
[lambda s: self.supplier_item_crud.add_many(s, [mapping])],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
res.supplier_item = SupplierItemData(
|
||||
supplier_item_id=mapping.supplier_item_id,
|
||||
item_id=item.item_id,
|
||||
item_name=item.name,
|
||||
item_code=item.code,
|
||||
supply_type=req.supply_type,
|
||||
)
|
||||
return res
|
||||
|
||||
async def update_type(self, company_id: str, supplier_item_id: str, req: Req_UpdateSupplyType) -> Res_WebPacketProtocol:
|
||||
res = Res_WebPacketProtocol()
|
||||
if req.supply_type not in _VALID_SUPPLY_TYPES:
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
return res
|
||||
|
||||
err_type, mapping = await self._fetch_owned_mapping(uuid.UUID(company_id), uuid.UUID(supplier_item_id))
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[supplier_items.DBType()],
|
||||
[lambda s: self.supplier_item_crud.update_type(s, mapping.supplier_item_id, req.supply_type)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
async def delete(self, company_id: str, supplier_item_id: str) -> Res_WebPacketProtocol:
|
||||
res = Res_WebPacketProtocol()
|
||||
err_type, mapping = await self._fetch_owned_mapping(uuid.UUID(company_id), uuid.UUID(supplier_item_id))
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[supplier_items.DBType()],
|
||||
[lambda s: self.supplier_item_crud.soft_delete(s, mapping.supplier_item_id)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
async def bulk_map_by_names(self, company_id: str, supplier_id: str, names: list) -> Res_BulkMapByNames:
|
||||
"""엑셀 취급상품 업로드용: 상품명 리스트 → 매핑 생성. 미매칭명은 스킵 후 리포트, 이미 매핑된 상품도 스킵.
|
||||
업로드는 공급유형을 받지 않으므로 전부 없음(0)으로 들어간다(상세에서 편집)."""
|
||||
res = Res_BulkMapByNames()
|
||||
company_uuid = uuid.UUID(company_id)
|
||||
supplier_uuid = uuid.UUID(supplier_id)
|
||||
|
||||
own_err = await self._supplier_owned(company_uuid, supplier_uuid)
|
||||
if own_err != ErrorType.SUCCESS:
|
||||
res.result.SetResult(own_err)
|
||||
return res
|
||||
|
||||
# 입력 정규화: 공백 제거·빈값 제거·중복 제거(원문 순서 유지).
|
||||
seen = set()
|
||||
clean_names = []
|
||||
for raw in names:
|
||||
n = (raw or "").strip()
|
||||
if n and n not in seen:
|
||||
seen.add(n)
|
||||
clean_names.append(n)
|
||||
if not clean_names:
|
||||
return res
|
||||
|
||||
# 이름 → 상품 해석(정확 일치). 이름 중복 상품은 첫 매칭만 사용.
|
||||
find_err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
supplier_items.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.supplier_item_crud.find_items_by_names(s, company_uuid, clean_names),
|
||||
)
|
||||
if find_err != ErrorType.SUCCESS:
|
||||
res.result.SetResult(find_err)
|
||||
return res
|
||||
name_to_item = {}
|
||||
for r in rows: # Row(item_id, name)
|
||||
if r[1] not in name_to_item:
|
||||
name_to_item[r[1]] = r[0]
|
||||
|
||||
res.unmatched = [n for n in clean_names if n not in name_to_item]
|
||||
matched_item_ids = [name_to_item[n] for n in clean_names if n in name_to_item]
|
||||
if not matched_item_ids:
|
||||
return res
|
||||
|
||||
# 이미 이 협력사에 매핑된 상품 제외.
|
||||
exist_err, already = await DB_SESSION_MNG.execute_lambda(
|
||||
supplier_items.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.supplier_item_crud.existing_item_ids(s, supplier_uuid, matched_item_ids),
|
||||
)
|
||||
if exist_err != ErrorType.SUCCESS:
|
||||
res.result.SetResult(exist_err)
|
||||
return res
|
||||
already_set = set(already)
|
||||
to_create = [iid for iid in matched_item_ids if iid not in already_set]
|
||||
res.skipped_count = len(matched_item_ids) - len(to_create)
|
||||
if not to_create:
|
||||
return res
|
||||
|
||||
mappings = [supplier_items(supplier_id=supplier_uuid, item_id=iid, supply_type=0) for iid in to_create]
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[supplier_items.DBType()],
|
||||
[lambda s: self.supplier_item_crud.add_many(s, mappings)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.created_count = len(to_create)
|
||||
return res
|
||||
Reference in new issue
Block a user