217 lines
8.9 KiB
Python
217 lines
8.9 KiB
Python
from abc import ABC, abstractmethod
|
|
from typing import Optional, Tuple
|
|
|
|
from sqlalchemy import select, func, and_, or_, update
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from common.database.db_session_manager import DB_SESSION_MNG
|
|
from common.database.model.models import items, users, supplier_items, suppliers
|
|
from common.enums import ErrorType
|
|
from common.logger import LOG
|
|
from common.utils.gtime import GTime
|
|
|
|
|
|
# 상품 CRUD. 모든 조회/변경은 company_id 로 스코프된다(멀티테넌트).
|
|
class IItemCRUD(ABC):
|
|
@abstractmethod
|
|
async def search(self, cdb: AsyncSession, company_id, search, category, skip, limit) -> Tuple[ErrorType, list, int]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def distinct_categories(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def code_exists(self, cdb: AsyncSession, company_id, code) -> Tuple[ErrorType, bool]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def existing_codes(self, cdb: AsyncSession, company_id, codes: list) -> Tuple[ErrorType, list]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_by_id(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, items]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def add_item(self, cdb: AsyncSession, item: items) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def update_item(self, cdb: AsyncSession, item_id, data: dict) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def soft_delete(self, cdb: AsyncSession, item_id) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def user_name_map(self, cdb: AsyncSession, user_ids) -> Tuple[ErrorType, dict]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def supplier_name_map(self, cdb: AsyncSession, item_ids) -> Tuple[ErrorType, dict]:
|
|
pass
|
|
|
|
|
|
class ItemCRUD(IItemCRUD):
|
|
async def search(
|
|
self, cdb: AsyncSession, company_id, search: Optional[str], category: Optional[str], skip: int, limit: int
|
|
) -> Tuple[ErrorType, list, int]:
|
|
try:
|
|
conditions = [items.deleted == False, items.company_id == company_id] # noqa: E712
|
|
if search:
|
|
conditions.append(or_(items.name.ilike(f"%{search}%"), items.code.ilike(f"%{search}%")))
|
|
if category:
|
|
conditions.append(items.category == category)
|
|
where = and_(*conditions)
|
|
|
|
cnt_err, cnt_rows = await DB_SESSION_MNG.execute(cdb, select(func.count()).select_from(items).where(where))
|
|
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(items).where(where).order_by(items.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 distinct_categories(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, list]:
|
|
try:
|
|
query = (
|
|
select(items.category, func.min(items.category_type))
|
|
.where(
|
|
items.company_id == company_id,
|
|
items.deleted == False, # noqa: E712
|
|
items.category.isnot(None),
|
|
items.category != "",
|
|
)
|
|
.group_by(items.category)
|
|
.order_by(items.category)
|
|
)
|
|
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 code_exists(self, cdb: AsyncSession, company_id, code) -> Tuple[ErrorType, bool]:
|
|
try:
|
|
query = select(func.count()).select_from(items).where(
|
|
items.company_id == company_id,
|
|
items.code == code,
|
|
items.deleted == False, # noqa: E712
|
|
)
|
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, False
|
|
cnt = int(rows[0] or 0) if rows else 0
|
|
return ErrorType.SUCCESS, cnt > 0
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, False
|
|
|
|
async def existing_codes(self, cdb: AsyncSession, company_id, codes: list) -> Tuple[ErrorType, list]:
|
|
try:
|
|
if not codes:
|
|
return ErrorType.SUCCESS, []
|
|
query = select(items.code).where(
|
|
items.company_id == company_id,
|
|
items.code.in_(codes),
|
|
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, [c for c in rows if c is not None]
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, []
|
|
|
|
async def get_by_id(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, items]:
|
|
try:
|
|
query = select(items).where(items.item_id == item_id, items.deleted == False).limit(1) # noqa: E712
|
|
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 add_item(self, cdb: AsyncSession, item: items) -> ErrorType:
|
|
try:
|
|
return await DB_SESSION_MNG.insert(cdb, item)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def update_item(self, cdb: AsyncSession, item_id, data: dict) -> ErrorType:
|
|
try:
|
|
if not data:
|
|
return ErrorType.SUCCESS
|
|
query = update(items).where(items.item_id == item_id).values(**data)
|
|
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, item_id) -> ErrorType:
|
|
try:
|
|
query = update(items).where(items.item_id == 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
|
|
|
|
async def user_name_map(self, cdb: AsyncSession, user_ids) -> Tuple[ErrorType, dict]:
|
|
"""user_id 목록 → {user_id: name}. 상품 목록/상세 '등록자(작성자)' 표기용(company.users 조인)."""
|
|
try:
|
|
if not user_ids:
|
|
return ErrorType.SUCCESS, {}
|
|
query = select(users.user_id, users.name).where(users.user_id.in_(user_ids))
|
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, {}
|
|
return ErrorType.SUCCESS, {uid: name for uid, name in rows}
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, {}
|
|
|
|
async def supplier_name_map(self, cdb: AsyncSession, item_ids) -> Tuple[ErrorType, dict]:
|
|
"""item_id 목록 → {item_id: [공급사명...]}. 상품 목록 '공급사' 컬럼용(supplier_items→suppliers 배치 조인)."""
|
|
try:
|
|
if not item_ids:
|
|
return ErrorType.SUCCESS, {}
|
|
query = (
|
|
select(supplier_items.item_id, suppliers.name)
|
|
.join(suppliers, suppliers.supplier_id == supplier_items.supplier_id)
|
|
.where(
|
|
supplier_items.item_id.in_(item_ids),
|
|
supplier_items.deleted == False, # noqa: E712
|
|
suppliers.deleted == False, # noqa: E712
|
|
)
|
|
.order_by(suppliers.name)
|
|
)
|
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, {}
|
|
out: dict = {}
|
|
for item_id, name in rows:
|
|
out.setdefault(item_id, []).append(name)
|
|
return ErrorType.SUCCESS, out
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, {}
|