Skip to content

Commit

Permalink
chore:update user_service create new user when user_id not exist
Browse files Browse the repository at this point in the history
  • Loading branch information
jingooo5 committed Nov 2, 2024
1 parent 8187161 commit 2b861fc
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 26 deletions.
25 changes: 17 additions & 8 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,6 +11,7 @@
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

Expand All @@ -28,11 +27,15 @@
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 @@ -75,13 +81,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
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 2b861fc

Please sign in to comment.