Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
rocknroll17 committed Nov 2, 2024
2 parents 1f21157 + ddce3ef commit 07e7c9f
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 28 deletions.
27 changes: 18 additions & 9 deletions Router/item.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

from fastapi.responses import JSONResponse

from Data.user import LoginUser, UserCreate
from Database.database import get_db
from fastapi import APIRouter
from starlette.status import *
from fastapi import Query, Request
Expand All @@ -13,26 +11,31 @@
from Service.embedding_service import EmbeddingService
from Service.item_service import ItemService
from Service.purchase_service import PurchaseService
from Service.user_service import UserService
from Service.useritem_service import UserItemService
import numpy as np

from Utils.swagger import user_item_list_dict_example

router = APIRouter(tags=["items"], prefix="/items")

"""
물품을 리스트로 추가한다.
"""

@router.post("/addall", summary="여러 품목 구매", description="영수증, 유저 기입 물품 목록 추가", responses={
200: {"description": "성공", "content": {"application/json": {"example": {"message": "Item added successfully"}}}},
500: {"description": "실패"}
})
def add_items(request: Request, itemadd: ItemAdd):
UserItemService.add_userItems(itemadd)
purchase_history_list = PurchaseService.purchase_history_list_db(itemadd)
PurchaseService.purchase_history_list_save(purchase_history_list)
return JSONResponse(status_code=HTTP_200_OK, content={"message": "Item added successfully"})

try:
# 존재하지 않는 유저 아이디 들어오면 새로 생성
user = UserService.get_user_or_create(itemadd.items[0].user_id)
UserItemService.add_userItems(itemadd)
purchase_history_list = PurchaseService.purchase_history_list_db(itemadd)
PurchaseService.purchase_history_list_save(purchase_history_list)
return JSONResponse(status_code=HTTP_200_OK, content={"message": "Item added successfully"})
except Exception as e:
return JSONResponse(status_code=HTTP_500_INTERNAL_SERVER_ERROR, content={"message": str(e)})

"""
유저가 보유한 모든 아이템을 가져온다.
Expand All @@ -42,6 +45,9 @@ def add_items(request: Request, itemadd: ItemAdd):
500: {"description": "실패"}
}, response_model=List[ItemRead])
def get_userItem_all(request : Request, user_id: str):
user = UserService.get_user_by_id(user_id)
if user is None:
return JSONResponse(status_code=HTTP_500_INTERNAL_SERVER_ERROR, content={"message": "User not found"})
user_item_list = UserItemService.get_all_userItem(user_id)
user_item_list_dict = UserItemService.to_userItem_dict(user_item_list)
return JSONResponse(status_code=HTTP_200_OK, content={"items": user_item_list_dict})
Expand Down Expand Up @@ -78,13 +84,16 @@ def consume_item(request : Request, user_item_consume: UserItemConsume):
})
def add_item(request : Request, userItemAdd: UserItemAdd):
try:
user = UserService.get_user_or_create(userItemAdd.user_id)
userItemAdd.user_id = user.user_id
UserItemService.add_userItem(userItemAdd)
purchaseHistory = PurchaseService.purchase_history_db(userItemAdd)
PurchaseService.purchase_history_save(purchaseHistory)
return JSONResponse(status_code=HTTP_200_OK, content={"message": "Item added successfully"})
except OverflowError as e:
return JSONResponse(status_code=HTTP_400_BAD_REQUEST, content={"message": "Too many items added"})

except Exception as e:
return JSONResponse(status_code=HTTP_500_INTERNAL_SERVER_ERROR, content={"message": str(e)})

@router.post("/add/{item_name}/{base_consume_expectation}/{base_price}", summary="아이템 추가")
def add_item(request : Request, item_name: str, base_consume_expectation: int, base_price: int):
Expand Down
14 changes: 3 additions & 11 deletions Router/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from starlette.status import *
from fastapi import Query, Request
from Database.models import User
from Service.user_service import UserService
from Service.useritem_service import UserItemService
from Utils.swagger import signin_response_example

Expand All @@ -17,17 +18,8 @@
500: {"description": "실패"}
})
def signup(request: Request, userCreate: UserCreate):
user = User(
name=userCreate.name,
password=userCreate.password
)
with get_db() as db:
db.add(user)
db.commit()
db.refresh(user)

UserItemService.init_userItem(user.user_id)
return JSONResponse(status_code=HTTP_200_OK, content={"message": "User added successfully"})
user = UserService.get_user_or_create("", userCreate.name, userCreate.password)
return JSONResponse(status_code=HTTP_200_OK, content={"message": "User added successfully", "user_id": user.user_id})


@router.post("/signin", summary="로그인", description="로그인 패스워드 확인안함", responses={
Expand Down
3 changes: 0 additions & 3 deletions Router/price.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
from fastapi.responses import JSONResponse

from Data.user import LoginUser, UserCreate
from Database.database import get_db
from fastapi import APIRouter
from starlette.status import *
from fastapi import Query, Request
from Database.models import User
from Service.item_service import ItemService
from Service.purchase_service import PurchaseService
from Service.useritem_service import UserItemService
Expand Down
2 changes: 1 addition & 1 deletion Service/consume_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,4 @@ def set_consume_expectation(user_id: str, item_name: str, expectation: int):

def get_consume_histories_by_item_id(item_id: str):
with get_db() as db:
return db.query(ConsumeHistory).filter(ConsumeHistory.item_id == item_id).all()
return db.query(ConsumeHistory).filter(ConsumeHistory.item_id == item_id).order_by(ConsumeHistory.date.asc()).all()
22 changes: 22 additions & 0 deletions Service/user_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from Database.database import get_db
from Database.models import User
from Service.useritem_service import UserItemService


class UserService:
@staticmethod
def get_user_by_id(user_id: str):
with get_db() as db:
return db.query(User).filter(User.user_id == user_id).first()

@staticmethod
def get_user_or_create(user_id: str, name=None, password="1234"):
user = UserService.get_user_by_id(user_id)
if user is None:
with get_db() as db:
user = User(name=user_id[:8] if name is None else name, password=password)
db.add(user)
db.commit()
db.refresh(user)
UserItemService.init_userItem(user.user_id)
return user
10 changes: 6 additions & 4 deletions Service/useritem_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from select import select
from typing import Optional, List, Annotated

from sqlalchemy.orm import Session
from sqlalchemy.sql.expression import extract

from Data.item import UserItemAdd, ItemAdd, UserItemConsume
Expand Down Expand Up @@ -53,6 +52,8 @@ def to_userItem_dict(userItemList: List[UserItem]):
def add_userItem(itemAdd: UserItemAdd):
with get_db() as db:
useritem = db.query(UserItem).filter(UserItem.user_id == itemAdd.user_id, UserItem.item_name == itemAdd.item_name).first()
if useritem is None:
raise Exception("UserItem not found")

if useritem.consume_date is None or useritem.count == 0:
useritem.consume_date = itemAdd.purchase_date
Expand All @@ -62,18 +63,19 @@ def add_userItem(itemAdd: UserItemAdd):
db.commit()
return True


@staticmethod
def add_userItems(itemAdd : ItemAdd):
for addItem in itemAdd.items:
with get_db() as db:
with get_db() as db:
for addItem in itemAdd.items:
useritem = db.query(UserItem).filter(UserItem.user_id == addItem.user_id, UserItem.item_name == addItem.item_name).first()

if useritem.consume_date is None or useritem.count == 0:
useritem.consume_date = addItem.purchase_date

useritem.count += addItem.count
useritem.consume_date += timedelta(days=useritem.consume_expectation * addItem.count)
db.commit()
db.commit()
return True

def consume_userItem(userItemConsume: UserItemConsume):
Expand Down

0 comments on commit 07e7c9f

Please sign in to comment.