Skip to content

Commit

Permalink
ut, drop legacy cash assist stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
marekbiczysko committed Nov 7, 2024
1 parent 353be9a commit ac25916
Show file tree
Hide file tree
Showing 8 changed files with 23 additions and 299 deletions.
56 changes: 0 additions & 56 deletions src/hct_mis_api/apps/payment/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,62 +201,6 @@ class Meta:
)


class CashPlanFilter(FilterSet):
search = CharFilter(method="search_filter")
delivery_type = MultipleChoiceFilter(field_name="delivery_type", choices=DeliveryMechanism.get_choices())
verification_status = MultipleChoiceFilter(
field_name="payment_verification_summary__status", choices=PaymentVerificationPlan.STATUS_CHOICES
)
business_area = CharFilter(
field_name="business_area__slug",
)

class Meta:
fields = {
"program": ["exact"],
"assistance_through": ["exact", "startswith"],
"service_provider__full_name": ["exact", "startswith"],
"start_date": ["exact", "lte", "gte"],
"end_date": ["exact", "lte", "gte"],
"business_area": ["exact"],
}
model = CashPlan

order_by = OrderingFilter(
fields=(
"ca_id",
"status",
"total_number_of_hh",
"total_entitled_quantity",
("payment_verification_summary__status", "verification_status"),
"total_persons_covered",
"total_delivered_quantity",
"total_undelivered_quantity",
"dispersion_date",
"assistance_measurement",
"assistance_through",
"delivery_type",
"start_date",
"end_date",
"program__name",
"id",
"updated_at",
"service_provider__full_name",
)
)

def filter_queryset(self, queryset: QuerySet) -> QuerySet:
queryset = queryset.annotate(total_number_of_hh=Count("payment_items"))
return super().filter_queryset(queryset)

def search_filter(self, qs: QuerySet, name: str, value: str) -> QuerySet:
values = value.split(" ")
q_obj = Q()
for value in values:
q_obj |= Q(ca_id__istartswith=value)
return qs.filter(q_obj)


class PaymentPlanFilter(FilterSet):
business_area = CharFilter(field_name="business_area__slug", required=True)
search = CharFilter(method="search_filter")
Expand Down
27 changes: 9 additions & 18 deletions src/hct_mis_api/apps/payment/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@
from hct_mis_api.apps.payment.models import (
Approval,
ApprovalProcess,
CashPlan,
DeliveryMechanism,
DeliveryMechanismPerPaymentPlan,
FinancialServiceProvider,
Expand All @@ -94,7 +93,6 @@
PaymentVerification,
PaymentVerificationPlan,
PaymentVerificationSummary,
ServiceProvider,
)
from hct_mis_api.apps.payment.services.dashboard_service import (
payment_verification_chart_query,
Expand Down Expand Up @@ -190,13 +188,6 @@ def get_queryset(cls, queryset: QuerySet, info: Any) -> QuerySet:
return queryset.all().allowed_to(business_area_slug)


class ServiceProviderNode(DjangoObjectType):
class Meta:
model = ServiceProvider
interfaces = (relay.Node,)
connection_class = ExtendedConnection


class AgeFilterObject(graphene.ObjectType):
min = graphene.Int()
max = graphene.Int()
Expand Down Expand Up @@ -568,7 +559,7 @@ class PaymentPlanNode(BaseNodePermissionMixin, AdminUrlNodeMixin, DjangoObjectTy
volume_by_delivery_mechanism = graphene.List(VolumeByDeliveryMechanismNode)
split_choices = graphene.List(ChoiceObject)
verification_plans = DjangoPermissionFilterConnectionField(
"hct_mis_api.apps.program.schema.PaymentVerificationPlanNode", # type: ignore
"hct_mis_api.apps.payment.schema.PaymentVerificationPlanNode", # type: ignore
filterset_class=PaymentVerificationPlanFilter,
)
payment_verification_summary = graphene.Field(
Expand Down Expand Up @@ -1157,7 +1148,7 @@ def resolve_sample_size(self, info: Any, input: Dict, **kwargs: Any) -> Dict[str
payment_plan_object: "PaymentPlan" = get_payment_plan_object(input["cash_or_payment_plan_id"])

def get_payment_records(
obj: Union["PaymentPlan", "CashPlan"],
obj: PaymentPlan,
payment_verification_plan: Optional[PaymentVerificationPlan],
verification_channel: str,
) -> QuerySet:
Expand Down Expand Up @@ -1276,9 +1267,9 @@ def resolve_chart_volume_by_delivery_mechanism(

labels = []
data = []
for volume in volume_by_delivery_type:
if volume_value := volume.volume:
dm = DeliveryMechanism.objects.get(id=volume.delivery_type)
for volume_dict in volume_by_delivery_type:
if volume_value := volume_dict.get("volume", None):
dm = DeliveryMechanism.objects.get(id=volume_dict.get("delivery_type"))
labels.append(dm.name)
data.append(volume_value)

Expand Down Expand Up @@ -1411,10 +1402,10 @@ def resolve_chart_total_transferred_cash_by_country(self, info: Any, year: int,
cash_transferred = []
voucher_transferred = []
total_transferred = []
for item in countries_and_amounts:
labels.append(item.business_area_name)
cash_transferred.append(item.total_delivered_cash or 0)
voucher_transferred.append(item.total_delivered_voucher or 0)
for item_dict in countries_and_amounts:
labels.append(item_dict.get("business_area_name"))
cash_transferred.append(item_dict.get("total_delivered_cash", 0))
voucher_transferred.append(item_dict.get("total_delivered_voucher", 0))
total_transferred.append(cash_transferred[-1] + voucher_transferred[-1])

datasets = [
Expand Down
16 changes: 7 additions & 9 deletions src/hct_mis_api/apps/payment/services/sampling.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import abc
from typing import TYPE_CHECKING, Any, Dict, Tuple, Union
from typing import TYPE_CHECKING, Any, Dict, Tuple

from django.db.models import Q, QuerySet

Expand All @@ -11,16 +11,14 @@
from hct_mis_api.apps.payment.utils import get_number_of_samples

if TYPE_CHECKING:
from hct_mis_api.apps.payment.models import CashPlan, PaymentPlan, PaymentRecord
from hct_mis_api.apps.payment.models import Payment, PaymentPlan


class Sampling:
def __init__(
self, input_data: Dict, payment_plan: Union["CashPlan", "PaymentPlan"], payment_records: QuerySet
) -> None:
def __init__(self, input_data: Dict, payment_plan: "PaymentPlan", payment_records: QuerySet["Payment"]) -> None:
self.input_data = input_data
self.payment_plan = payment_plan
self.payment_records: QuerySet = payment_records
self.payment_records = payment_records

def process_sampling(
self, payment_verification_plan: PaymentVerificationPlan
Expand Down Expand Up @@ -83,12 +81,12 @@ def calc_sample_size(self, sample_count: int) -> int:
return get_number_of_samples(sample_count, self.confidence_interval, self.margin_of_error)

@abc.abstractmethod
def sampling(self, payment_records: QuerySet["PaymentRecord"]) -> None:
def sampling(self, payment_records: QuerySet["Payment"]) -> None:
pass


class RandomSampling(BaseSampling):
def sampling(self, payment_records: QuerySet["PaymentRecord"]) -> None:
def sampling(self, payment_records: QuerySet["Payment"]) -> None:
if self.sex is not None:
payment_records = payment_records.filter(household__head_of_household__sex=self.sex)

Expand All @@ -107,7 +105,7 @@ def sampling(self, payment_records: QuerySet["PaymentRecord"]) -> None:


class FullListSampling(BaseSampling):
def sampling(self, payment_records: QuerySet["PaymentRecord"]) -> None:
def sampling(self, payment_records: QuerySet["Payment"]) -> None:
self.payment_records = payment_records.filter(
~(Q(household__admin_area__id__in=self.excluded_admin_areas_decoded))
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@
from hct_mis_api.apps.payment.models import PaymentPlan


def get_payment_records(payment_plan: PaymentPlan, verification_channel: Optional[Any]) -> QuerySet:
def get_payment_records(payment_plan: "PaymentPlan", verification_channel: Optional[Any]) -> QuerySet:
if verification_channel == PaymentVerificationPlan.VERIFICATION_CHANNEL_RAPIDPRO:
return payment_plan.available_payment_records(extra_validation=does_payment_record_have_right_hoh_phone_number)
return payment_plan.available_payment_records()


class VerificationPlanCrudServices:
@classmethod
def create(cls, payment_plan: PaymentPlan, input_data: Dict) -> PaymentVerificationPlan:
def create(cls, payment_plan: "PaymentPlan", input_data: Dict) -> PaymentVerificationPlan:
verifier = PaymentVerificationArgumentVerifier(input_data)
verifier.verify("sampling")
verifier.verify("verification_channel")
Expand Down
97 changes: 3 additions & 94 deletions src/hct_mis_api/apps/program/schema.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
from typing import Any, Dict, List, Tuple, Type
from typing import Any, Dict, List

from django.db.models import (
Case,
Count,
DecimalField,
Exists,
F,
IntegerField,
OuterRef,
Q,
QuerySet,
Sum,
Expand All @@ -16,7 +14,7 @@
)

import graphene
from graphene import Int, relay
from graphene import relay
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField

Expand All @@ -25,7 +23,6 @@
ALL_GRIEVANCES_CREATE_MODIFY,
AdminUrlNodeMixin,
BaseNodePermissionMixin,
BasePermission,
DjangoPermissionFilterConnectionField,
Permissions,
hopeOneOfPermissionClass,
Expand All @@ -46,21 +43,7 @@
decode_id_string,
to_choice_object,
)
from hct_mis_api.apps.payment.filters import (
CashPlanFilter,
PaymentVerificationPlanFilter,
)
from hct_mis_api.apps.payment.models import (
CashPlan,
DeliveryMechanism,
GenericPayment,
PaymentVerificationPlan,
PaymentVerificationSummary,
)
from hct_mis_api.apps.payment.schema import (
PaymentVerificationPlanNode,
PaymentVerificationSummaryNode,
)
from hct_mis_api.apps.payment.models import DeliveryMechanism
from hct_mis_api.apps.payment.utils import get_payment_items_for_dashboard
from hct_mis_api.apps.program.filters import ProgramCycleFilter, ProgramFilter
from hct_mis_api.apps.program.models import Program, ProgramCycle
Expand Down Expand Up @@ -164,46 +147,6 @@ def resolve_can_finish(program: Program, info: Any, **kwargs: Any) -> bool:
return program.can_finish


class CashPlanNode(BaseNodePermissionMixin, DjangoObjectType):
permission_classes: Tuple[Type[BasePermission], ...] = (
hopePermissionClass(Permissions.PAYMENT_VERIFICATION_VIEW_DETAILS),
hopePermissionClass(Permissions.PROGRAMME_VIEW_LIST_AND_DETAILS),
)

bank_reconciliation_success = graphene.Int()
bank_reconciliation_error = graphene.Int()
delivery_type = graphene.String()
total_number_of_households = graphene.Int()
currency = graphene.String(source="currency")
total_delivered_quantity = graphene.Float()
total_entitled_quantity = graphene.Float()
total_undelivered_quantity = graphene.Float()
can_create_payment_verification_plan = graphene.Boolean()
available_payment_records_count = graphene.Int()
verification_plans = DjangoPermissionFilterConnectionField(
PaymentVerificationPlanNode,
filterset_class=PaymentVerificationPlanFilter,
)
payment_verification_summary = graphene.Field(
PaymentVerificationSummaryNode,
source="get_payment_verification_summary",
)
unicef_id = graphene.String(source="ca_id")

class Meta:
model = CashPlan
interfaces = (relay.Node,)
connection_class = ExtendedConnection

def resolve_available_payment_records_count(self, info: Any, **kwargs: Any) -> Int:
return self.payment_items.filter(
status__in=GenericPayment.ALLOW_CREATE_VERIFICATION, delivered_quantity__gt=0
).count()

def resolve_verification_plans(self, info: Any, **kwargs: Any) -> QuerySet:
return self.get_payment_verification_plans


class Query(graphene.ObjectType):
program = relay.Node.Field(ProgramNode)
all_programs = DjangoPermissionFilterConnectionField(
Expand All @@ -227,18 +170,6 @@ class Query(graphene.ObjectType):
program=graphene.String(required=False),
administrative_area=graphene.String(required=False),
)

cash_plan = relay.Node.Field(CashPlanNode)
all_cash_plans = DjangoPermissionFilterConnectionField(
CashPlanNode,
filterset_class=CashPlanFilter,
permission_classes=(
hopePermissionClass(Permissions.PAYMENT_VERIFICATION_VIEW_LIST),
hopePermissionClass(
Permissions.PROGRAMME_VIEW_LIST_AND_DETAILS,
),
),
)
program_status_choices = graphene.List(ChoiceObject)
program_cycle_status_choices = graphene.List(ChoiceObject)
program_frequency_of_payments_choices = graphene.List(ChoiceObject)
Expand Down Expand Up @@ -355,28 +286,6 @@ def resolve_data_collecting_type_choices(self, info: Any, **kwargs: Any) -> List
.order_by("name")
)

def resolve_all_cash_plans(self, info: Any, **kwargs: Any) -> QuerySet[CashPlan]:
payment_verification_summary_qs = PaymentVerificationSummary.objects.filter(payment_plan_id=OuterRef("id"))

return CashPlan.objects.annotate(
custom_order=Case(
When(
Exists(payment_verification_summary_qs.filter(status=PaymentVerificationPlan.STATUS_ACTIVE)),
then=Value(1),
),
When(
Exists(payment_verification_summary_qs.filter(status=PaymentVerificationPlan.STATUS_PENDING)),
then=Value(2),
),
When(
Exists(payment_verification_summary_qs.filter(status=PaymentVerificationPlan.STATUS_FINISHED)),
then=Value(3),
),
output_field=IntegerField(),
default=Value(0),
),
).order_by("-updated_at", "custom_order")

@chart_permission_decorator(permissions=[Permissions.DASHBOARD_VIEW_COUNTRY])
@cached_in_django_cache(24)
def resolve_chart_programmes_by_sector(self, info: Any, business_area_slug: str, year: int, **kwargs: Any) -> Dict:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ def test_getting_individual_with_status_paid(self) -> None:
self.assertIsNotNone(data["info"])
info = data["info"]
self.assertEqual(info["status"], "paid")
self.assertEqual(info["date"], _time(payment.delivery_date))
self.assertEqual(info["date"], payment.delivery_date)

def test_getting_non_existent_household(self) -> None:
response = self.api_client.get("/api/hh-status?registration_id=non-existent")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@
PaymentHouseholdSnapshot,
PaymentPlan,
PaymentPlanSplit,
ServiceProvider,
)
from hct_mis_api.apps.payment.services.payment_household_snapshot_service import (
create_payment_plan_snapshot_data,
Expand Down Expand Up @@ -100,7 +99,7 @@ def setUpTestData(cls) -> None:
{"size": n, "address": "Lorem Ipsum", "country_origin": country_origin, "village": "TEST_VILLAGE"},
)

if ServiceProvider.objects.count() < 3:
if FinancialServiceProvider.objects.count() < 3:
FinancialServiceProviderFactory.create_batch(3)
program = RealProgramFactory()
cls.dm_cash = DeliveryMechanism.objects.get(code="cash")
Expand Down
Loading

0 comments on commit ac25916

Please sign in to comment.