Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/strategy equal parts #69

Merged
merged 8 commits into from
Jun 18, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 40 additions & 16 deletions src/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,15 +185,13 @@ def get_all_spendings_by_group_id(db: Session, group_id: int):
# UNIQUE SPENDINGS
################################################


def create_unique_spending(
db: Session, spending: schemas.UniqueSpendingCreate, user_id: int
):
def create_unique_spending(db: Session, spending: schemas.UniqueSpendingCreate, user_id: int, category: models.Strategy):
db_spending = models.UniqueSpending(owner_id=user_id, **dict(spending))
db_spending.strategy_data = None
db.add(db_spending)
db.commit()
db.refresh(db_spending)
update_balances_from_spending(db, db_spending)
update_balances_from_spending(db, db_spending, category, spending.strategy_data)
db.refresh(db_spending)
return db_spending

Expand Down Expand Up @@ -394,7 +392,6 @@ def update_invite_status(
# REMINDERS
################################################


def create_payment_reminder(
db: Session, payment_reminder: schemas.PaymentReminderCreate, sender_id: int
):
Expand All @@ -417,16 +414,8 @@ def create_payment_reminder(
# BALANCES
################################################


def update_balances_from_spending(db: Session, spending: models.UniqueSpending):
group = get_group_by_id(db, spending.group_id)
balances = sorted(
get_balances_by_group_id(db, spending.group_id), key=lambda x: x.user_id
)
members = sorted(group.members, key=lambda x: x.id)
# TODO: implement division strategy
# TODO: this truncates decimals
amount_per_member = spending.amount // len(members)
def update_balances_equals(db, spending, members, balances):
amount_per_member = spending.amount / len(members)
for user, balance in zip(members, balances):
amount = -amount_per_member

Expand All @@ -435,9 +424,44 @@ def update_balances_from_spending(db: Session, spending: models.UniqueSpending):

balance.current_balance += amount

def update_balances_percentage(db, spending, members, balances, strategy_data):
for user, balance in zip(members, balances):

amount_per_member = sum([data['value'] if data['user_id'] == user.id else 0 for data in strategy_data])
amount_per_member = spending.amount * (amount_per_member / 100)
amount = spending.amount - amount_per_member if spending.owner_id == user.id else -amount_per_member
balance.current_balance += amount
db.commit()


def update_balances_custom(db, spending, members, balances, strategy_data):
for user, balance in zip(members, balances):
amount_per_member = sum([data['value'] if data['user_id'] == user.id else 0 for data in strategy_data])
amount = spending.amount - amount_per_member if spending.owner_id == user.id else -amount_per_member
balance.current_balance += amount
db.commit()

def update_balances_from_spending(db: Session, spending: models.UniqueSpending, strategy: models.Strategy, strategy_data):
group = get_group_by_id(db, spending.group_id)
balances = sorted(
get_balances_by_group_id(db, spending.group_id), key=lambda x: x.user_id
)
members = sorted(group.members, key=lambda x: x.id)
# TODO: implement division strategy
# TODO: this truncates decimals
# TODO: Refactor to POO
MegaRedHand marked this conversation as resolved.
Show resolved Hide resolved
if strategy == models.Strategy.EQUALPARTS:
update_balances_equals(db, spending, members, balances)
elif strategy == models.Strategy.PERCENTAGE:
update_balances_percentage(db, spending, members, balances, strategy_data)
elif strategy == models.Strategy.CUSTOM:
update_balances_custom(db, spending, members, balances, strategy_data)

db.commit()

################################################
# BALANCES
################################################
def update_balances_from_payment(db: Session, payment: models.Payment):
balances = get_balances_by_group_id(db, payment.group_id)

Expand Down
24 changes: 22 additions & 2 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,25 @@ def list_group_categories(db: DbDependency, user: UserDependency, group_id: int)
check_group_exists_and_user_is_member(user.id, group)
categories = crud.get_categories_by_group_id(db, group_id)
return categories

import json
def check_strategy_data(group: models.Group, category: models.Category, strategy_data, spending_amount: int):
if category.strategy == schemas.Strategy.EQUALPARTS and strategy_data:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, detail="El tipo de estrategia seleccionado no admite el campo 'strategy_data'"
)

if strategy_data:
if any([not user_id_in_group(data['user_id'], group) for data in strategy_data]):
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail=f"El usuario no ha sido encontrado{strategy_data}"
)

if category.strategy == schemas.Strategy.PERCENTAGE and sum([data['value'] for data in strategy_data]) != 100 or \
category.strategy == schemas.Strategy.CUSTOM and sum([data['value'] for data in strategy_data]) != spending_amount:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, detail="La distribucion es incorrecta"
)


################################################
# ALL SPENDINGS
Expand Down Expand Up @@ -327,8 +345,10 @@ def create_unique_spending(
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Categoria inexistente"
)
check_strategy_data(group, category, spending.strategy_data, spending.amount)

return crud.create_unique_spending(db, spending, user.id)
#return crud.create_spending(db, spending, user.id, category.strategy)
MegaRedHand marked this conversation as resolved.
Show resolved Hide resolved
return crud.create_unique_spending(db, spending, user.id, category.strategy)


@app.get("/group/{group_id}/unique-spending")
Expand Down
9 changes: 5 additions & 4 deletions src/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
DateTime,
ForeignKey,
Integer,
Float,
String,
Boolean,
UniqueConstraint,
Expand All @@ -14,7 +15,7 @@
UUID,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from src.schemas import InviteStatus
from src.schemas import InviteStatus, Strategy
from src.database import Base


Expand Down Expand Up @@ -49,8 +50,7 @@ class Category(Base):
group_id = Column(ForeignKey("groups.id"))
name = Column(String)
description = Column(String)
# TODO: move strategy to enums
strategy = Column(String)
strategy = Column(Enum(Strategy))

__table_args__ = (UniqueConstraint("group_id", "name"),)

Expand All @@ -64,6 +64,7 @@ class UniqueSpending(Base):
category_id = Column(ForeignKey("categories.id"))
amount = Column(Integer)
description = Column(String)
strategy_data = Column(String)
date: Mapped[datetime] = mapped_column(DateTime, default=func.now())


Expand All @@ -88,7 +89,7 @@ class RecurringSpending(Base):
owner_id = Column(ForeignKey("users.id"))
group_id = Column(ForeignKey("groups.id"))
category_id = Column(ForeignKey("categories.id"))
amount = Column(Integer)
amount = Column(Float)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Debería ser un entero.

description = Column(String)
date: Mapped[datetime] = mapped_column(DateTime, default=func.now())

Expand Down
20 changes: 18 additions & 2 deletions src/schemas.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from datetime import datetime
from enum import StrEnum, auto
from typing import Optional, Union
from typing import Optional, Union, Dict, List
from typing_extensions import TypedDict
from uuid import UUID
from pydantic import BaseModel, Field

Expand Down Expand Up @@ -83,16 +84,31 @@ class Group(GroupBase):


################################################
# UNIQUE SPENDINGS
# STRATEGY
################################################

class Strategy(StrEnum):
EQUALPARTS = auto()
PERCENTAGE = auto()
CUSTOM = auto()


class Distribution(TypedDict):
user_id: int
value: float
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Que sea un int entre 0 y 100



################################################
# SPENDINGS
################################################

class UniqueSpendingBase(BaseModel):
amount: int
description: str
date: Optional[datetime] = Field(None)
group_id: int
category_id: int
strategy_data: Optional[List[Distribution]] = Field(None)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Podemos moverlo a CreateUniqueSpending, y no guardarlo en la DB



class UniqueSpendingCreate(UniqueSpendingBase):
Expand Down
139 changes: 137 additions & 2 deletions src/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,96 @@ def test_create_new_spending_with_default_date(
assert response_body["category_id"] == some_category.id
assert datetime.datetime.fromisoformat(response_body["date"])

def test_create_new_spending_percentage_category(
client: TestClient,
some_group_members: list[schemas.UserCredentials],
some_credentials: schemas.UserCredentials,
some_group: schemas.Group,
some_category_percentage: schemas.Category,
):
response = client.post(
url="/unique-spending",
json={
"amount": 500,
"description": "bought some féca",
"group_id": some_group.id,
"category_id": some_category_percentage.id,
"strategy_data":[
{
"user_id": some_group_members[0].id,
"value": 20
},
{
"user_id": some_group_members[1].id,
"value": 80
}]
},
headers={"x-user": some_credentials.jwt},
)
assert response.status_code == HTTPStatus.CREATED
response_body = response.json()
assert "id" in response_body
assert response_body["group_id"] == some_group.id
assert response_body["category_id"] == some_category_percentage.id


balances_response = client.get(
url=f"/group/{some_group.id}/balance",
headers={"x-user": some_group_members[0].jwt},
)


balance_list = balances_response.json()
balance_list.sort(key=lambda x: x["user_id"])

assert balance_list[0]["current_balance"] == 400
assert balance_list[1]["current_balance"] == -400

def test_create_new_spending_percentage_custom(
client: TestClient,
some_group_members: list[schemas.UserCredentials],
some_credentials: schemas.UserCredentials,
some_group: schemas.Group,
some_category_custom: schemas.Category,
):
response = client.post(
url="/unique-spending",
json={
"amount": 500,
"description": "bought some féca",
"group_id": some_group.id,
"category_id": some_category_custom.id,
"strategy_data":[
{
"user_id": some_group_members[0].id,
"value": 230
},
{
"user_id": some_group_members[1].id,
"value": 270
}]
},
headers={"x-user": some_credentials.jwt},
)
assert response.status_code == HTTPStatus.CREATED
response_body = response.json()
assert "id" in response_body
assert response_body["group_id"] == some_group.id
assert response_body["category_id"] == some_category_custom.id


balances_response = client.get(
url=f"/group/{some_group.id}/balance",
headers={"x-user": some_group_members[0].jwt},
)


balance_list = balances_response.json()
balance_list.sort(key=lambda x: x["user_id"])

assert balance_list[0]["current_balance"] == 270
assert balance_list[1]["current_balance"] == -270

def test_create_new_spending_with_non_existant_category(
client: TestClient,
some_credentials: schemas.UserCredentials,
Expand Down Expand Up @@ -635,7 +724,7 @@ def some_category(
"name": "cafe",
"description": "really long description 1234",
"group_id": some_group.id,
"strategy": "a cool strategy",
"strategy": "EQUALPARTS",
},
headers={"x-user": some_credentials.jwt},
)
Expand All @@ -646,6 +735,52 @@ def some_category(
assert response_body["group_id"] == some_group.id
return schemas.Category(**response_body)

@pytest.fixture
def some_category_percentage(
client: TestClient,
some_credentials: schemas.UserCredentials,
some_group: schemas.Group,
):
response = client.post(
url="/category",
json={
"name": "servicios",
"description": "really long description 1234",
"group_id": some_group.id,
"strategy": "PERCENTAGE",
},
headers={"x-user": some_credentials.jwt},
)

assert response.status_code == HTTPStatus.CREATED
response_body = response.json()
assert response_body["name"] == "servicios"
assert response_body["group_id"] == some_group.id
return schemas.Category(**response_body)

@pytest.fixture
def some_category_custom(
client: TestClient,
some_credentials: schemas.UserCredentials,
some_group: schemas.Group,
):
response = client.post(
url="/category",
json={
"name": "comida",
"description": "really long description 1234",
"group_id": some_group.id,
"strategy": "CUSTOM",
},
headers={"x-user": some_credentials.jwt},
)

assert response.status_code == HTTPStatus.CREATED
response_body = response.json()
assert response_body["name"] == "comida"
assert response_body["group_id"] == some_group.id
return schemas.Category(**response_body)


def test_create_new_category(client: TestClient, some_category: schemas.Category):
# NOTE: test is inside fixture
Expand Down Expand Up @@ -677,7 +812,7 @@ def test_category_modify_name(
"name": "nuevo nombre categoria",
"description": "otra descripcion",
# TODO: move strategy to enums
"strategy": "equitativo?",
"strategy": "EQUALPARTS",
MegaRedHand marked this conversation as resolved.
Show resolved Hide resolved
},
headers={"x-user": some_credentials.jwt},
)
Expand Down
Loading