diff --git a/Router/item.py b/Router/item.py index ec7f439..c12b7dc 100644 --- a/Router/item.py +++ b/Router/item.py @@ -61,6 +61,9 @@ def consume_item(request : Request, user_item_consume: UserItemConsume): return JSONResponse(status_code=HTTP_400_BAD_REQUEST, content={"message": "Item consume failed"}) consume_history = ConsumeService.consume_history_db(user_item_consume) ConsumeService.purchase_history_save(consume_history) + expectation = ConsumeService.calculate_consume_expectation(user_item_consume.user_id, user_item_consume.item_name) + if expectation: + ConsumeService.set_consume_expectation(user_item_consume.user_id, user_item_consume.item_name, expectation) return JSONResponse(status_code=HTTP_200_OK, content={"message": "Item consumed successfully"}) diff --git a/Service/consume_service.py b/Service/consume_service.py index 35cb073..65bd744 100644 --- a/Service/consume_service.py +++ b/Service/consume_service.py @@ -1,3 +1,4 @@ +from statistics import mean from typing import List from Data.item import * from Database.models import * @@ -13,6 +14,31 @@ def purchase_history_save(data : ConsumeHistory): db.add(data) db.commit() + def calculate_consume_expectation(user_id: str, item_name: str): + with get_db() as db: + item_id = db.query(UserItem).filter(UserItem.user_id == user_id, UserItem.item_name == item_name).first().item_id + consume_histories = db.query(ConsumeHistory).filter(ConsumeHistory.item_id == item_id).order_by(ConsumeHistory.date).all() + if len(consume_histories) < 2: + return None + date_differences = [] + for i in range(1, len(consume_histories)): + date_diff = (consume_histories[i].date - consume_histories[i-1].date).days + date_differences.append(date_diff) + + average_difference = round(mean(date_differences)) + if average_difference < 1: + return 1 + return average_difference + + def set_consume_expectation(user_id: str, item_name: str, expectation: int): + with get_db() as db: + item_id = db.query(UserItem).filter(UserItem.user_id == user_id, UserItem.item_name == item_name).first().item_id + user_item = db.query(UserItem).filter(UserItem.item_id == item_id).first() + user_item.consume_expectation = expectation + db.commit() + + + 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() \ No newline at end of file