Skip to content

Commit

Permalink
feat:Added consume expectation feature
Browse files Browse the repository at this point in the history
  • Loading branch information
rocknroll17 committed Nov 2, 2024
1 parent d0ce269 commit 1f21157
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Router/item.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"})


Expand Down
26 changes: 26 additions & 0 deletions Service/consume_service.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from statistics import mean
from typing import List
from Data.item import *
from Database.models import *
Expand All @@ -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()

0 comments on commit 1f21157

Please sign in to comment.