Skip to content

Commit

Permalink
[#383] Support add segments when create case settings
Browse files Browse the repository at this point in the history
  • Loading branch information
wayangalihpratama committed Jan 7, 2025
1 parent a08b19f commit 4ac43b7
Show file tree
Hide file tree
Showing 5 changed files with 162 additions and 10 deletions.
5 changes: 5 additions & 0 deletions backend/db/crud_case.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ def add_case(session: Session, payload: CaseBase, user: User) -> CaseDict:
for tag_id in payload.tags:
tag = CaseTag(tag=tag_id)
case.case_tags.append(tag)
if payload.segments:
for segment in payload.segments:
# TODO:: add number of farmers
new_segment = Segment(name=segment.name)
case.case_segments.append(new_segment)
session.add(case)
session.commit()
session.flush()
Expand Down
8 changes: 7 additions & 1 deletion backend/models/case.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,12 @@
SimplifiedCaseCommodityDict,
CaseCommodityType,
)
from models.segment import Segment, SegmentDict, SegmentWithAnswersDict
from models.segment import (
Segment,
SegmentDict,
SegmentWithAnswersDict,
CaseSettingSegmentPayload,
)
from models.case_tag import CaseTag


Expand Down Expand Up @@ -336,6 +341,7 @@ class CaseBase(BaseModel):
other_commodities: Optional[List[OtherCommoditysBase]] = None
tags: Optional[List[int]] = None
company: Optional[int] = None
segments: Optional[List[CaseSettingSegmentPayload]] = None


class PaginatedCaseResponse(BaseModel):
Expand Down
21 changes: 13 additions & 8 deletions backend/models/segment.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,33 +40,33 @@ class SegmentWithAnswersDict(TypedDict):


class Segment(Base):
__tablename__ = 'segment'
__tablename__ = "segment"

id = Column(Integer, primary_key=True, nullable=False)
case = Column(Integer, ForeignKey('case.id'))
region = Column(Integer, ForeignKey('region.id'), nullable=True)
case = Column(Integer, ForeignKey("case.id"))
region = Column(Integer, ForeignKey("region.id"), nullable=True)
name = Column(String, nullable=False)
target = Column(Float, nullable=True)
adult = Column(Float, nullable=True)
child = Column(Float, nullable=True)

case_detail = relationship(
'Case',
"Case",
cascade="all, delete",
passive_deletes=True,
back_populates='case_segments'
back_populates="case_segments",
)
segment_answers = relationship(
'SegmentAnswer',
"SegmentAnswer",
cascade="all, delete",
passive_deletes=True,
backref='segment_detail'
backref="segment_detail",
)

def __init__(
self,
name: str,
case: int,
case: Optional[int] = None,
region: Optional[int] = None,
target: Optional[float] = None,
adult: Optional[float] = None,
Expand Down Expand Up @@ -148,3 +148,8 @@ class SegmentUpdateBase(BaseModel):
adult: Optional[float] = None
child: Optional[float] = None
answers: Optional[List[SegmentAnswerBase]] = []


class CaseSettingSegmentPayload(BaseModel):
name: str
number_of_farmers: int
135 changes: 135 additions & 0 deletions backend/tests/test_1001_case_with_segments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import sys
import pytest

from fastapi import FastAPI
from httpx import AsyncClient
from sqlalchemy.orm import Session
from tests.test_000_main import Acc

from models.case import LivingIncomeStudyEnum
from models.case_commodity import CaseCommodityType

sys.path.append("..")

non_admin_account = Acc(email="editor@akvo.org", token=None)
admin_account = Acc(email="super_admin@akvo.org", token=None)


class TestCaseWithSegmentRoute:
@pytest.mark.asyncio
async def test_create_not_private_case(
self, app: FastAPI, session: Session, client: AsyncClient
) -> None:
payload = {
"name": "Bali Rice and Corn with Segment",
"description": "This is a description",
"date": "2024-10-03",
"year": 2024,
"country": 2,
"focus_commodity": 2,
"currency": "USD",
"area_size_unit": "hectare",
"volume_measurement_unit": "liters",
"cost_of_production_unit": "Per-area",
"reporting_period": "Per-season",
"segmentation": False,
"living_income_study": LivingIncomeStudyEnum.better_income.value,
"multiple_commodities": False,
"other_commodities": [
{
"commodity": 3,
"breakdown": True,
"commodity_type": CaseCommodityType.secondary.value,
"volume_measurement_unit": "liters",
"area_size_unit": "hectare",
}
],
"tags": [1],
"company": 1,
"segments": [
{
"name": "Segment 1 Name",
"number_of_farmers": 10,
},
{
"name": "Segment 2 Name",
"number_of_farmers": 8,
},
],
}
# with admin user cred
res = await client.post(
app.url_path_for("case:create"),
headers={"Authorization": f"Bearer {admin_account.token}"},
json=payload,
)
assert res.status_code == 200
res = res.json()
assert res == {
"id": 12,
"name": "Bali Rice and Corn with Segment",
"description": "This is a description",
"date": "2024-10-03",
"year": 2024,
"country": 2,
"focus_commodity": 2,
"currency": "USD",
"area_size_unit": "hectare",
"volume_measurement_unit": "liters",
"cost_of_production_unit": "Per-area",
"reporting_period": "Per-season",
"segmentation": False,
"living_income_study": "better_income",
"multiple_commodities": False,
"logo": None,
"created_by": 1,
"segments": [
{
"id": 4,
"case": 12,
"name": "Segment 1 Name",
"region": None,
"target": None,
"adult": None,
"child": None,
},
{
"id": 5,
"case": 12,
"name": "Segment 2 Name",
"region": None,
"target": None,
"adult": None,
"child": None,
},
],
"case_commodities": [
{
"id": 13,
"commodity": 2,
"breakdown": True,
"commodity_type": "focus",
"area_size_unit": "hectare",
"volume_measurement_unit": "liters",
},
{
"id": 14,
"commodity": 3,
"breakdown": True,
"commodity_type": "secondary",
"area_size_unit": "hectare",
"volume_measurement_unit": "liters",
},
{
"id": 15,
"commodity": None,
"breakdown": True,
"commodity_type": "diversified",
"area_size_unit": "hectare",
"volume_measurement_unit": "liters",
},
],
"private": False,
"tags": [1],
"company": 1,
}
3 changes: 2 additions & 1 deletion backend/tests/test_1010_user_deletion.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ async def test_deleting_a_user_who_has_cases(
"id": 1,
"email": "super_admin@akvo.org",
"cases": [
{"label": "Bali Coffee Production (Private)", "value": 2}
{"label": "Bali Coffee Production (Private)", "value": 2},
{"label": "Bali Rice and Corn with Segment", "value": 12},
],
}
}
Expand Down

0 comments on commit 4ac43b7

Please # to comment.