Skip to content
This repository has been archived by the owner on Dec 13, 2022. It is now read-only.

Commit

Permalink
API refactor
Browse files Browse the repository at this point in the history
 - [x] country api refactor
 - [x] country suppliers api refactor
 - [x] product table refactor
 - [x] country api custom add
 - [x] country detail api custom add
 - [x] test cases updated
  • Loading branch information
sonikabaniya authored and Kushal Raj Shrestha committed Jul 15, 2021
1 parent cd9661d commit dc433fc
Show file tree
Hide file tree
Showing 10 changed files with 127 additions and 88 deletions.
3 changes: 1 addition & 2 deletions country/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,15 +300,14 @@ class Meta:

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["buyer"].queryset = Buyer.objects.filter(country=self.instance.country)
self.fields["supplier"].queryset = Supplier.objects.filter(country=self.instance.country)
self.fields["buyer"].queryset = Buyer.objects.filter(country=self.instance.country)


class TenderAdmin(admin.ModelAdmin):
form = TenderForm
list_display = ("contract_id", "contract_title", "country", "contract_date")
search_fields = ("id", "contract_id", "contract_title")
# autocomplete_fields = ["buyer", "supplier"]
inlines = [
GoodsAndServicesInline,
]
Expand Down
10 changes: 4 additions & 6 deletions country/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def get_amount_usd(self, obj):
None

except Exception:
return obj.tenders.all().aggregate(amount_usd=Sum("goods_services__contract_value_usd"))["amount_usd"]
return obj.tenders.aggregate(amount_usd=Sum("contract_value_usd"))["amount_usd"]

def get_amount_local(self, obj):
try:
Expand All @@ -63,9 +63,7 @@ def get_amount_local(self, obj):
return None

except Exception:
return obj.tenders.all().aggregate(amount_local=Sum("goods_services__contract_value_local"))[
"amount_local"
]
return obj.tenders.aggregate(amount_local=Sum("contract_value_local"))["amount_local"]

def get_tender_count(self, obj):
try:
Expand All @@ -75,7 +73,7 @@ def get_tender_count(self, obj):
return None

except Exception:
return obj.tenders.all().aggregate(tender_count=Count("id"))["tender_count"]
return obj.tenders.aggregate(tender_count=Count("id"))["tender_count"]

def get_last_contract_date(self, obj):
try:
Expand All @@ -85,7 +83,7 @@ def get_last_contract_date(self, obj):
return None

except Exception:
return obj.tenders.all().aggregate(contract_last_date=Max("contract_date"))["contract_last_date"]
return obj.tenders.aggregate(contract_last_date=Max("contract_date"))["contract_last_date"]


class LanguageSerializer(serializers.ModelSerializer, SerializerExtensionsMixin):
Expand Down
6 changes: 3 additions & 3 deletions country/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
class CountryViewTest(TestCase):
def setUp(self):
self.buyer_list_api_url = "BuyerView-list"
self.country_list_api_url = "country-list"
self.country_list_api_url = "country_view"
self.language_list_api_url = "language-list"
self.supplier_list_api_url = "SupplierView-list"
self.tender_list_api_url = "TenderView-list"
self.overview_summary_list_api_url = "OverallStatSummaryView-list"
self.country_choices_api_url = "country-choices"
self.country_choices_api_url = "country_detail_view"
self.data_edit_url = "data_edits"
self.data_imports_url = "data_imports"
self.data_validate_url = "data_validate"
Expand All @@ -28,7 +28,7 @@ def test_country_list_GET(self):
self.assertEquals(response.status_code, status.HTTP_200_OK)

def test_country_choice_list_GET(self):
url = reverse(self.country_choices_api_url)
url = reverse(self.country_choices_api_url, args=["kenya"])
response = self.client.get(url)
self.assertEquals(response.status_code, status.HTTP_200_OK)

Expand Down
1 change: 0 additions & 1 deletion country/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from . import views

router = routers.DefaultRouter()
router.register("api/v1/country", views.CountryView)
router.register("api/v1/language", views.LanguageView)
router.register("api/v1/buyers", views.BuyerView, basename="BuyerView")
router.register("api/v1/suppliers", views.SupplierView, basename="SupplierView")
Expand Down
1 change: 1 addition & 0 deletions country/views/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from .buyer_view import BuyerView
from .country_detail_view import CountryDetailView
from .country_view import CountryView
from .data_edit_view import DataEditView
from .data_import_view import DataImportView
Expand Down
51 changes: 51 additions & 0 deletions country/views/country_detail_view.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import socket

from django.db.models import Count, Max, Sum
from django.http import JsonResponse
from rest_framework.views import APIView

from country.models import Country, Tender


class CountryDetailView(APIView):
def get(self, request, *args, **kwargs):
slug = self.kwargs["slug"]
filter_args = {}
filter_args["country__slug"] = slug

country = Country.objects.filter(slug=slug).first()
country_detail = []
try:
tender_data = Tender.objects.filter(**filter_args).aggregate(
amount_usd=Sum("contract_value_usd"),
amount_local=Sum("contract_value_local"),
tender_count=Count("id"),
contract_last_date=Max("contract_date"),
)

country_detail.append(
{
"url": "https://" + socket.gethostbyname(socket.gethostname()) + "/api/v1/country/" + slug,
"id": country.id,
"continent": country.continent,
"amount_usd": tender_data["amount_usd"],
"amount_local": tender_data["amount_local"],
"tender_count": tender_data["tender_count"],
"last_contract_date": tender_data["contract_last_date"],
"slug": country.slug,
"name": country.name,
"population": country.population,
"gdp": country.gdp,
"country_code": country.country_code,
"country_code_alpha_2": country.country_code_alpha_2,
"currency": country.currency,
"healthcare_budget": country.healthcare_budget,
"healthcare_gdp_pc": country.healthcare_gdp_pc,
"covid_cases_total": country.covid_cases_total,
"covid_deaths_total": country.covid_deaths_total,
"covid_data_last_updated": country.covid_data_last_updated,
}
)
return JsonResponse(country_detail, safe=False)
except Exception:
return JsonResponse([{"error": "Invalid country_code"}], safe=False)
67 changes: 47 additions & 20 deletions country/views/country_view.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,53 @@
from django.utils.translation import gettext_lazy as _
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
import socket

from country.models import Country
from country.serializers import CountrySerializer
from django.db.models import Count, Max, Sum
from django.http import JsonResponse
from rest_framework.views import APIView

from country.models import Country, Tender

class CountryView(viewsets.ModelViewSet):
pagination_class = None
queryset = Country.objects.all()
serializer_class = CountrySerializer
lookup_field = "slug"
extensions_auto_optimize = True

def get_queryset(self):
return Country.objects.all()

@action(detail=False, methods=["get"])
def choices(self, request):
class CountryView(APIView):
def get(self, request):
countries = Country.objects.all().order_by("name")
serializer = self.get_serializer(countries, many=True)
country_id_and_name = [{"id": country["id"], "name": _(country["name"])} for country in serializer.data]
country_detail = []
filter_args = {}

return Response(country_id_and_name)
try:
for country in countries:
filter_args["country__name"] = country
tender_data = Tender.objects.filter(**filter_args).aggregate(
amount_usd=Sum("contract_value_usd"),
amount_local=Sum("contract_value_local"),
tender_count=Count("id"),
contract_last_date=Max("contract_date"),
)
country_detail.append(
{
"url": "https://"
+ socket.gethostbyname(socket.gethostname())
+ "/api/v1/country/"
+ country.slug,
"id": country.id,
"continent": country.continent,
"amount_usd": tender_data["amount_usd"],
"amount_local": tender_data["amount_local"],
"tender_count": tender_data["tender_count"],
"last_contract_date": tender_data["contract_last_date"],
"slug": country.slug,
"name": country.name,
"population": country.population,
"gdp": country.gdp,
"country_code": country.country_code,
"country_code_alpha_2": country.country_code_alpha_2,
"currency": country.currency,
"healthcare_budget": country.healthcare_budget,
"healthcare_gdp_pc": country.healthcare_gdp_pc,
"covid_cases_total": country.covid_cases_total,
"covid_deaths_total": country.covid_deaths_total,
"covid_data_last_updated": country.covid_data_last_updated,
}
)
return JsonResponse(country_detail, safe=False)
except Exception:
return JsonResponse([{"error": "Invalid country_code"}], safe=False)
3 changes: 3 additions & 0 deletions covidadmin/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
# from wagtail.core import urls as wagtail_urls
from wagtail.documents import urls as wagtaildocs_urls

from country.views import CountryDetailView, CountryView
from visualization.views import InsightsView, SlugBlogShow, SlugStaticPageShow, UpcomingEventView

from .api import api_router
Expand All @@ -40,6 +41,8 @@
path("api/staticpage/<str:type>", SlugStaticPageShow.as_view()),
path("api/upcoming-events", UpcomingEventView.as_view()),
path("api/contents/insights", InsightsView.as_view(), name="insights_view"),
path("api/v1/country", CountryView.as_view(), name="country_view"),
path("api/v1/country/<str:slug>", CountryDetailView.as_view(), name="country_detail_view"),
path("", include("country.urls")),
path("api-auth/", include("rest_framework.urls")),
path("cms/", include(wagtailadmin_urls)),
Expand Down
69 changes: 15 additions & 54 deletions visualization/views/country_suppliers_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def get(self, request):
**filter_args, supplier__isnull=False, goods_services__goods_services_category__isnull=False
)
.values("supplier__id", "goods_services__goods_services_category__id")
.annotate(usd=Sum("goods_services__contract_value_usd"))
.annotate(usd=Sum("contract_value_usd"))
.exclude(usd__isnull=True)
.order_by("-usd")
)
Expand All @@ -49,14 +49,11 @@ def get(self, request):
if len(suppliers_dict[i["goods_services__goods_services_category__id"]]["countwise"]) <= 5:
suppliers_dict[i["goods_services__goods_services_category__id"]]["countwise"].append(i["supplier__id"])

final_suppliers_list_countwise = list(
itertools.chain.from_iterable([i["countwise"] for i in suppliers_dict.values()])
)
final_suppliers_list_amountwise = list(
itertools.chain.from_iterable([i["amountwise"] for i in suppliers_dict.values()])
)

by_value_supplier_product = (
product_supplier = (
Tender.objects.filter(
**filter_args,
supplier__id__in=final_suppliers_list_amountwise,
Expand All @@ -70,13 +67,13 @@ def get(self, request):
"goods_services__goods_services_category__category_name",
)
.annotate(
local=Sum("goods_services__contract_value_local"),
usd=Sum("goods_services__contract_value_usd"),
local=Sum("contract_value_local"),
usd=Sum("contract_value_usd"),
count=Count("id"),
)
.order_by("-usd")[:count]
)
by_value_product_buyer = (

product_buyer = (
Tender.objects.filter(
**filter_args,
supplier__id__in=final_suppliers_list_amountwise,
Expand All @@ -90,53 +87,17 @@ def get(self, request):
"buyer__buyer_name",
)
.annotate(
local=Sum("goods_services__contract_value_local"),
usd=Sum("goods_services__contract_value_usd"),
local=Sum("contract_value_local"),
usd=Sum("contract_value_usd"),
count=Count("id"),
)
.order_by("-usd")[:count]
)

by_number_supplier_product = (
Tender.objects.filter(
**filter_args,
supplier__id__in=final_suppliers_list_countwise,
supplier__isnull=False,
goods_services__goods_services_category__isnull=False,
)
.values(
"supplier__id",
"supplier__supplier_name",
"goods_services__goods_services_category__id",
"goods_services__goods_services_category__category_name",
)
.annotate(
local=Sum("goods_services__contract_value_local"),
usd=Sum("goods_services__contract_value_usd"),
count=Count("id"),
)
.order_by("-count")[:count]
)
by_number_product_buyer = (
Tender.objects.filter(
**filter_args,
supplier__id__in=final_suppliers_list_countwise,
buyer__isnull=False,
goods_services__goods_services_category__isnull=False,
)
.values(
"goods_services__goods_services_category__id",
"goods_services__goods_services_category__category_name",
"buyer__id",
"buyer__buyer_name",
)
.annotate(
local=Sum("goods_services__contract_value_local"),
usd=Sum("goods_services__contract_value_usd"),
count=Count("id"),
)
.order_by("-count")[:count]
)
by_value_product_buyer = (product_buyer.order_by("-usd"))[:count]
by_number_product_buyer = (product_buyer.order_by("-count"))[:count]

by_value_product_supplier = (product_supplier.order_by("-usd"))[:count]
by_number_product_supplier = (product_supplier.order_by("-count"))[:count]

results = {
"by_number": {
Expand All @@ -162,7 +123,7 @@ def get(self, request):
"supplier_name": i["supplier__supplier_name"],
"tender_count": i["count"],
}
for i in by_number_supplier_product
for i in by_number_product_supplier
],
},
"by_value": {
Expand All @@ -188,7 +149,7 @@ def get(self, request):
"supplier_name": i["supplier__supplier_name"],
"tender_count": i["count"],
}
for i in by_value_supplier_product
for i in by_value_product_supplier
],
},
}
Expand Down
4 changes: 2 additions & 2 deletions visualization/views/product_table_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ def get(self, request):
)
.annotate(
total=Count("id", distinct=True),
local=Sum("goods_services__contract_value_local"),
usd=Sum("goods_services__contract_value_usd"),
local=Sum("contract_value_local"),
usd=Sum("contract_value_usd"),
buyer=Count("buyer", distinct=True),
supplier=Count("supplier", distinct=True),
)
Expand Down

0 comments on commit dc433fc

Please sign in to comment.