class RedFlagSummaryView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): filter_args = {} country_code = self.request.GET.get("country", None) if country_code: country_code = str(country_code).upper() filter_args["country__country_code_alpha_2"] = country_code filter_args["red_flag__isnull"] = False result = [] equity_summary = (Tender.objects.filter( **filter_args).annotate(month=TruncMonth("contract_date")).values( "month", "red_flag", "red_flag__title", "red_flag__implemented").annotate( total=Count("id"), local=Sum("contract_value_local"), usd=Sum("contract_value_usd"), ).order_by("-month")) for detail in equity_summary: if detail["red_flag__implemented"]: data = { "amount_local": detail["local"], "amount_usd": detail["usd"], "red_flag": detail["red_flag__title"], "red_flag_id": detail["red_flag"], "month": detail["month"], "tender_count": detail["total"], } result.append(data) return JsonResponse(result, safe=False)
class CountryMapView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): country_code = self.request.GET.get("country", None) try: country_instance = Country.objects.get( country_code_alpha_2=country_code) if country_code is not None and country_instance is not None: tender_instance = Tender.objects.filter( country__country_code_alpha_2=country_code).aggregate( total_usd=Sum("contract_value_usd"), total_local=Sum("contract_value_local"), ) count = Tender.objects.filter( country__country_code_alpha_2=country_code).count() final = { "country_code": country_instance.country_code_alpha_2, "country": country_instance.name, "country_continent": country_instance.continent, "amount_usd": tender_instance["total_usd"], "amount_local": tender_instance["total_local"], "tender_count": count, } return JsonResponse(final) except Exception: return JsonResponse({"result": "Invalid Alpha Code"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class SupplierTrendView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): temp = {} tender_temp = {} data = [] count = (Tender.objects.annotate( month=TruncMonth("contract_date")).values("month").annotate( total_buyer_count=Count("supplier__id", distinct=True), sum=Sum("contract_value_usd")).order_by("month")) countries = Country.objects.all() for i in count: result = {} end_date = i["month"] + dateutil.relativedelta.relativedelta( months=1) start_date = i["month"] result["details"] = [] result["month"] = str(start_date.year) + "-" + str( start_date.month) for j in countries: b = {} tender = Tender.objects.filter( country__country_code_alpha_2=j.country_code_alpha_2, contract_date__gte=start_date, contract_date__lte=end_date, ).aggregate( total_supplier_count=Count("supplier__id", distinct=True), amount_usd=Sum("contract_value_usd"), ) b["country"] = j.name b["country_code"] = j.country_code_alpha_2 b["country_continent"] = j.continent supplier_count = tender["total_supplier_count"] if tender["amount_usd"] is None: tender_val = 0 else: tender_val = tender["amount_usd"] if supplier_count is None: supplier_val = 0 else: supplier_val = supplier_count if bool(temp) and j.name in temp.keys(): current_val = temp[j.name] cum_value = current_val + tender_val temp[j.name] = cum_value b["amount_usd"] = cum_value else: temp[j.name] = tender_val b["amount_usd"] = tender_val if bool(tender_temp) and j.name in tender_temp.keys(): current_val = tender_temp[j.name] cum_value = current_val + supplier_val tender_temp[j.name] = cum_value b["supplier_count"] = cum_value else: tender_temp[j.name] = supplier_val b["supplier_count"] = supplier_val result["details"].append(b) data.append(result) return JsonResponse({"result": data})
class ProductSpendingComparison(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): filter_args = {} product_id = self.request.GET.get("product", None) if product_id: product_category = GoodsServicesCategory.objects.filter( id=product_id).first() filter_args[ "goods_services__goods_services_category__id"] = product_id month_wise_data = (Tender.objects.filter(**filter_args).annotate( month=TruncMonth("contract_date")).values( "country__country_code_alpha_2", "country__currency", "month", ).annotate(usd=Sum("contract_value_usd"), local=Sum("contract_value_local"), count=Count("id", distinct=True)).order_by("-month")) result = [{ "amount_usd": i["usd"], "amount_local": i["local"], "tender_count": i["count"], "country_code": i["country__country_code_alpha_2"], "currency": i["country__currency"], "month": i["month"].strftime("%Y-%m"), "product_id": product_category.id, "product_name": product_category.category_name, } for i in month_wise_data] return JsonResponse(result, safe=False) else: return JsonResponse([], safe=False)
class ContractRedFlagsView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): filter_args = {} country_code = self.request.GET.get("country", None) supplier_id = self.request.GET.get("supplier", None) buyer_id = self.request.GET.get("buyer", None) product = self.request.GET.get("product", None) if country_code: country_code = str(country_code).upper() filter_args["country__country_code_alpha_2"] = country_code if supplier_id: filter_args = add_filter_args("supplier", supplier_id, filter_args) if buyer_id: filter_args = add_filter_args("buyer", buyer_id, filter_args) if product: filter_args[ "goods_services__goods_services_category__id"] = product red_flags = RedFlag.objects.filter(implemented=True) value = [] result = {"result": value} for red_flag in red_flags: count = Tender.objects.filter( **filter_args, red_flag__pk=red_flag.id).distinct().count() data = {} data["red_flag_id"] = red_flag.id data["red_flag"] = red_flag.title data["tender_count"] = count value.append(data) return JsonResponse(result, safe=False)
class CountryPartnerView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): filter_args = {} country_code = self.request.GET.get("country", None) if country_code: country_code = str(country_code).upper() filter_args["country__country_code_alpha_2"] = country_code try: data_provider = CountryPartner.objects.filter(**filter_args) result = [] if data_provider: for i in data_provider: data = { "name": i.name, "description": i.description, "email": i.email, "website": i.website, "logo": str(i.logo), "order": i.order, "country": str(i.country), } result.append(data) return JsonResponse(result, safe=False, status=status.HTTP_200_OK) except Exception: result = {"error": "Country Partner not found for this country"} return JsonResponse(result, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class TopBuyers(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): country_code = self.request.GET.get("country", None) supplier_id = self.request.GET.get("supplier") filter_args = { "country__isnull": False, "summary__tender_count__isnull": False, "summary__amount_local__isnull": False, "summary__amount_usd__isnull": False, } if country_code: country_code = str(country_code).upper() filter_args["country__country_code_alpha_2"] = country_code if supplier_id: filter_args["tenders__supplier_id"] = supplier_id for_value = top_buyer(order_by="amount_usd", **filter_args) for_number = top_buyer(order_by="tender_count", **filter_args) by_number = [] by_value = [] for value in for_value: by_value.append(formatted(value)) for value in for_number: by_number.append(formatted(value)) return JsonResponse({"by_number": by_number, "by_value": by_value})
class SupplierProfileView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request, *args, **kwargs): pk = self.kwargs["pk"] try: instance = Supplier.objects.get(id=pk) supplier_detail = (Tender.objects.filter(supplier_id=pk).values( "country__name", "country__country_code_alpha_2").annotate( total_usd=Sum("contract_value_usd"), total_local=Sum("contract_value_local"), )) tender_count = Tender.objects.filter(supplier_id=pk).count() data = { "name": instance.supplier_name, "id": pk, "code": instance.supplier_id, "address": instance.supplier_address, "amount_usd": supplier_detail[0]["total_usd"], "amount_local": supplier_detail[0]["total_local"], "tender_count": tender_count, "country_code": supplier_detail[0]["country__country_code_alpha_2"], "country_name": supplier_detail[0]["country__name"], } return JsonResponse(data, safe=False) except Exception: error = {"error": "Enter valid ID"} return JsonResponse(error, safe=False)
class QuantityCorrelation(APIView): today = datetime.datetime.now() @method_decorator(cache_page(page_expire_period())) def get(self, request): country_code = self.request.GET.get("country", None) filter_args = {} if country_code: country_code = str(country_code).upper() filter_args["country__country_code_alpha_2"] = country_code contracts_quantity = (Tender.objects.filter( **filter_args).annotate( month=TruncMonth("contract_date")).values( "month", "country__currency").annotate( count=Count("id"), usd=Sum("contract_value_usd"), local=Sum("contract_value_local"), ).order_by("-month")) else: contracts_quantity = (Tender.objects.annotate( month=TruncMonth("contract_date")).values("month").annotate( count=Count("id"), usd=Sum("contract_value_usd")).order_by("-month")) contracts_quantity_list = [] for i in contracts_quantity: active_case = CovidMonthlyActiveCases.objects.filter( **filter_args, covid_data_date__year=i["month"].year, covid_data_date__month=i["month"].month).values( "active_cases_count", "death_count") active_case_count = 0 death_count = 0 try: for j in active_case: if j["active_cases_count"] and j["death_count"]: active_case_count += j["active_cases_count"] death_count += j["death_count"] except Exception: pass contracts_quantity_list.append({ "active_cases": active_case_count, "death_cases": death_count, "amount_local": i["local"] if "local" in i else "", "amount_usd": i["usd"], "local_currency_code": i["country__currency"] if "country__currency" in i else "", "month": i["month"], "tender_count": i["count"], }) return JsonResponse(contracts_quantity_list, safe=False)
class ProductTableView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): filter_args = {} country_code = self.request.GET.get("country", None) if country_code: country_code = str(country_code).upper() filter_args["country__country_code_alpha_2"] = country_code filter_args["goods_services__goods_services_category__isnull"] = False result = [] product_tables = ( Tender.objects.filter(**filter_args) .values( "goods_services__goods_services_category__category_name", "goods_services__goods_services_category__id" ) .annotate( total=Count("id", distinct=True), local=Sum("contract_value_local"), usd=Sum("contract_value_usd"), buyer=Count("buyer", distinct=True), supplier=Count("supplier", distinct=True), ) ) for product in product_tables: data = { "amount_local": product["local"], "amount_usd": product["usd"], "product_id": product["goods_services__goods_services_category__id"], "product_name": product["goods_services__goods_services_category__category_name"], "buyer_count": product["buyer"], "supplier_count": product["supplier"], "tender_count": product["total"], } result.append(data) return JsonResponse(result, safe=False)
class GlobalOverview(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): temp = {} tender_temp = {} data = [] count = (Tender.objects.annotate( month=TruncMonth("contract_date")).values("month").annotate( total_contract=Count("id"), total_amount=Sum("contract_value_usd"), ).order_by("month")) countries = Country.objects.all().exclude(country_code_alpha_2="gl") for item in count: result = {} end_date = item["month"] + dateutil.relativedelta.relativedelta( months=1) start_date = item["month"] result["details"] = [] result["month"] = str(start_date.year) + "-" + str( start_date.month) for country in countries: b = {} tender = Tender.objects.filter( country__country_code_alpha_2=country.country_code_alpha_2, contract_date__gte=start_date, contract_date__lte=end_date, ).aggregate(Sum("contract_value_usd"), Count("id")) b["country"] = country.name b["country_code"] = country.country_code_alpha_2 b["country_continent"] = country.continent if tender["contract_value_usd__sum"] is None: tender_val = 0 else: tender_val = tender["contract_value_usd__sum"] if tender["id__count"] is None: contract_val = 0 else: contract_val = tender["id__count"] if bool(temp) and country.name in temp.keys(): current_val = temp[country.name] cum_value = current_val + tender_val temp[country.name] = cum_value b["amount_usd"] = cum_value else: temp[country.name] = tender_val b["amount_usd"] = tender_val if bool(tender_temp) and country.name in tender_temp.keys(): current_val = tender_temp[country.name] cum_value = current_val + contract_val tender_temp[country.name] = cum_value b["tender_count"] = cum_value else: tender_temp[country.name] = contract_val b["tender_count"] = contract_val result["details"].append(b) data.append(result) return JsonResponse({"result": data})
class DirectOpen(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): country_code = self.request.GET.get("country", None) buyer_id = self.request.GET.get("buyer") supplier_id = self.request.GET.get("supplier") filter_args = {} country_currency = "" results = {} if buyer_id: filter_args = add_filter_args("buyer", buyer_id, filter_args) results = procurement_procedure_amount(**filter_args) if supplier_id: filter_args = add_filter_args("supplier", supplier_id, filter_args) results = procurement_procedure_amount(**filter_args) if country_code: country_code = str(country_code).upper() country_obj = Country.objects.get( country_code_alpha_2=country_code) country_currency = country_obj.currency filter_args = add_filter_args("country__country_code_alpha_2", country_code, filter_args, append_only=True) results = procurement_procedure_amount(**filter_args) if not country_code and not supplier_id and not buyer_id: results = procurement_procedure_amount(**filter_args) response = [] for result in results: response.append({ "amount_local": result["local"] if result["local"] else 0, "amount_usd": result["usd"] if result["usd"] else 0, "tender_count": result["count"], "local_currency_code": country_currency, "status": result["procurement_procedure"] if result["procurement_procedure"] else "", }) return JsonResponse(response, safe=False)
class ContractStatusView(APIView): """ Returns status wise grouped info about contracts """ @method_decorator(cache_page(page_expire_period())) def get(self, request): filter_args = {} result = list() currency_code = "" country_code = self.request.GET.get("country", None) buyer_id = self.request.GET.get("buyer") if country_code: country_code = str(country_code).upper() filter_args["country__country_code_alpha_2"] = country_code if buyer_id: filter_args = add_filter_args("buyer", buyer_id, filter_args) if country_code: try: country_res = Country.objects.get( country_code_alpha_2=country_code) currency_code = country_res.currency except Exception as e: return JsonResponse( {"error": str(e)}, safe=False, status=status_code.HTTP_500_INTERNAL_SERVER_ERROR) status_query_set = (Tender.objects.filter( **filter_args).values("status").annotate( amount_usd=Sum("contract_value_usd"), amount_local=Sum("contract_value_local"), tender_count=Count("id"), )) for status in status_query_set: data = { "amount_local": status["amount_local"], "amount_usd": status["amount_usd"], "tender_count": status["tender_count"], "local_currency_code": currency_code, "status": status["status"], } result.append(data) return JsonResponse(result, safe=False)
class SlugStaticPageShow(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request, *args, **kwargs): page_type = self.kwargs["type"] result = {} try: if page_type: results = StaticPage.objects.filter( page_type=page_type.title()).values("page_type", "body") result["page_type"] = results[0]["page_type"] result["body"] = results[0]["body"] except Exception: result = [{"error": "Content doest not exists"}] return JsonResponse(result, safe=False)
class UpcomingEventView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): result = {} today = datetime.datetime.now() results = EventsPage.objects.filter(event_date__gte=today).values( "title", "description", "event_date", "time_from", "time_to", "location", "event_image_id") result["title"] = results[0]["title"] result["description"] = results[0]["description"] result["event_date"] = results[0]["event_date"] result["time_from"] = results[0]["time_from"] result["time_to"] = results[0]["time_to"] result["location"] = results[0]["location"] return JsonResponse(result, safe=False)
class ProductTimelineView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): filter_args = {} country_code = self.request.GET.get("country", None) buyer_id = self.request.GET.get("buyer") supplier_id = self.request.GET.get("supplier") if country_code: country_code = str(country_code).upper() filter_args["country__country_code_alpha_2"] = country_code if buyer_id: filter_args = add_filter_args("buyer", buyer_id, filter_args) if supplier_id: filter_args = add_filter_args("supplier", supplier_id, filter_args) result = [] try: tenders_assigned = ( Tender.objects.filter(**filter_args) .exclude(goods_services__goods_services_category=None) .annotate(month=TruncMonth("contract_date")) .values( "month", "goods_services__goods_services_category__category_name", "goods_services__goods_services_category__id", "country__currency", ) .annotate( count=Count("id"), local=Sum("contract_value_local"), usd=Sum("contract_value_usd"), ) .order_by("-month") ) for tender in tenders_assigned: data = { "amount_local": tender["local"], "amount_usd": tender["usd"], "date": tender["month"], "local_currency_code": tender["country__currency"], "product_id": tender["goods_services__goods_services_category__id"], "product_name": tender["goods_services__goods_services_category__category_name"], "tender_count": tender["count"], } result.append(data) return JsonResponse(result, safe=False) except Exception: return JsonResponse([{"error": "Invalid country_code"}], safe=False)
class TotalContractsView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): """ Return a list of all contracts. """ # Calculating total tender country_code = self.request.GET.get("country", None) buyer_id = self.request.GET.get("buyer") supplier_id = self.request.GET.get("supplier") total_contract = 0 bar_chart_list = [] filter_args = {} if country_code: country_code = str(country_code).upper() filter_args["country__country_code_alpha_2"] = country_code if buyer_id: filter_args = add_filter_args("buyer", buyer_id, filter_args) if supplier_id: filter_args = add_filter_args("supplier", supplier_id, filter_args) bar_chart = (Tender.objects.filter( **filter_args).values("procurement_procedure").annotate( count=Count("procurement_procedure"), total_contract=Count("id"))) for i in bar_chart: total_contract += i["total_contract"] bar_chart_list.append({ "method": i["procurement_procedure"], "value": i["count"] }) line_chart = (Tender.objects.filter(**filter_args).annotate( month=TruncMonth("contract_date")).values("month").annotate( total=Count("id")).order_by("-month")) line_chart_list = [{ "date": i["month"], "value": i["total"] } for i in line_chart] result = { "total": total_contract, "line_chart": line_chart_list, "bar_chart": bar_chart_list, } return JsonResponse(result)
class SupplierSummaryView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): filter_args = {} country_code = self.request.GET.get("country", None) result = {} trend = [] current_time = datetime.datetime.now() previous_month_date = current_time - dateutil.relativedelta.relativedelta( months=-1) previous_month = previous_month_date.replace(day=1).date() if country_code: country_code = str(country_code).upper() filter_args["country__country_code_alpha_2"] = country_code supplier_details = (Tender.objects.filter(**filter_args).exclude( supplier__isnull=True ).annotate(month=TruncMonth("contract_date")).values("month").annotate( count=Count("supplier_id", distinct=True)).order_by("-month")) totals = (Tender.objects.filter(**filter_args).exclude( supplier__isnull=True).values("supplier").distinct().aggregate( total=Count("supplier"))) for details in supplier_details: data = { "supplier_count": details["count"], "month": details["month"] } trend.append(data) try: dates_in_details = [i["month"] for i in supplier_details] final_current_month_count = [ supplier_details[0]["count"] if current_time.replace( day=1).date() in dates_in_details else 0 ] final_previous_month_count = [ supplier_details[1]["count"] if previous_month in dates_in_details else 0 ] percentage = round( ((final_current_month_count[0] - final_previous_month_count[0]) / final_previous_month_count[0]) * 100) except Exception: percentage = 0 result["total"] = totals["total"] result["percentage"] = percentage result["trend"] = trend return JsonResponse(result, safe=False)
class FilterParametersStatic(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): countries = Country.objects.values("id", "country_code", "name") products = GoodsServicesCategory.objects.values("id", "category_name") equities = EquityCategory.objects.values("id", "category_name") red_flags = RedFlag.objects.filter(implemented=True).values("id", "title") result_country = [] result_product = [] result_equity = [] result_red_flag = [] result = {} if countries: result_country = [ {"id": country["id"], "code": country["country_code"], "name": country["name"]} for country in countries ] if products: result_product = [{"id": product["id"], "name": product["category_name"]} for product in products] if equities: result_equity = [{"id": equity["id"], "name": equity["category_name"]} for equity in equities] if red_flags: result_red_flag = [{"id": red_flag["id"], "name": red_flag["title"]} for red_flag in red_flags] result["method"] = [ {"label": "Direct", "value": "direct"}, {"label": "Limited", "value": "limited"}, {"label": "Open", "value": "open"}, {"label": "Other", "value": "other"}, {"label": "Selective", "value": "selective"}, {"label": "Not Identified", "value": "not_identified"}, ] result["status"] = [ {"label": "Active", "value": "active"}, {"label": "Cancelled", "value": "cancelled"}, {"label": "Completed", "value": "completed"}, {"label": "Other", "value": "other"}, {"label": "Not Identified", "value": "not_identified"}, ] result["country"] = result_country result["products"] = result_product result["equity"] = result_equity result["red_flag"] = result_red_flag return JsonResponse(result, safe=False)
class AverageBidsView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): """ Returns average bids for contracts """ country_code = self.request.GET.get("country", None) buyer_id = self.request.GET.get("buyer") filter_args = {} filter_args["no_of_bidders__gte"] = 1 if country_code: country_code = str(country_code).upper() filter_args["country__country_code_alpha_2"] = country_code if buyer_id: filter_args = add_filter_args("buyer", buyer_id, filter_args) # Month wise average of number of bids for contracts monthwise_data = ( Tender.objects.filter(**filter_args) .annotate(month=TruncMonth("contract_date")) .values("month") .annotate(count=Count("id"), sum=Sum("no_of_bidders")) .order_by("-month") ) final_line_chart_data = [ { "date": monthwise_data[i]["month"], "value": round(monthwise_data[i]["sum"] / monthwise_data[i]["count"], 1) if monthwise_data[i]["sum"] else 0, } for i in range(len(monthwise_data)) ] # Difference percentage calculation result = { "average": round(sum(item["value"] for item in final_line_chart_data) / len(final_line_chart_data), 1) if len(final_line_chart_data) > 0 else 0, "line_chart": final_line_chart_data, } return JsonResponse(result)
class ProductSummaryView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): filter_args = {} country_code = self.request.GET.get("country", None) currency = "USD" if country_code: country_code = str(country_code).upper() filter_args["country__country_code_alpha_2"] = country_code instance = Country.objects.get(country_code_alpha_2=country_code) currency = instance.currency result = [] tenders_assigned = (Tender.objects.filter(**filter_args).exclude( goods_services__goods_services_category=None ).annotate(category=Count( "goods_services__goods_services_category__category_name")).values( "goods_services__goods_services_category__category_name", "goods_services__goods_services_category__id").annotate( count=Count("id"), local=Sum("contract_value_local"), usd=Sum("contract_value_usd"), )) for tender in tenders_assigned: data = { "amount_local": tender["local"], "amount_usd": tender["usd"], "local_currency_code": currency, "product_id": tender["goods_services__goods_services_category__id"], "product_name": tender[ "goods_services__goods_services_category__category_name"], "tender_count": tender["count"], } result.append(data) return JsonResponse(result, safe=False)
class MonopolizationView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): filter_args = {} country_code = self.request.GET.get("country", None) buyer_id = self.request.GET.get("buyer") if country_code: country_code = str(country_code).upper() filter_args["country__country_code_alpha_2"] = country_code if buyer_id: filter_args = add_filter_args("buyer", buyer_id, filter_args) filter_args["supplier_id__isnull"] = False # Month wise average of number of bids for contracts monthwise_data = (Tender.objects.filter(**filter_args).annotate( month=TruncMonth("contract_date")).values("month").annotate( count_supplier=Count("supplier__supplier_id", distinct=True), count_contract=Count("id")).order_by("-month")) final_line_chart_data = [{ "date": monthwise_data[i]["month"], "value": round( monthwise_data[i]["count_contract"] / monthwise_data[i]["count_supplier"], 1) if monthwise_data[i]["count_supplier"] and monthwise_data[i]["count_contract"] else 0, } for i in range(len(monthwise_data))] # Difference percentage calculation result = { "average": round( sum(item["value"] for item in final_line_chart_data) / len(final_line_chart_data), 1) if len(final_line_chart_data) > 0 else 0, "line_chart": final_line_chart_data, } return JsonResponse(result)
class ProductDistributionView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): filter_args = {} country_code = self.request.GET.get("country", None) buyer_id = self.request.GET.get("buyer", None) if country_code: country_code = str(country_code).upper() filter_args["country__country_code_alpha_2"] = country_code if buyer_id: filter_args["contract__buyer__buyer_id"] = buyer_id if buyer_id == "notnull": filter_args["contract__buyer__isnull"] = False result = [] goods_services = ( GoodsServices.objects.filter(**filter_args) .values("goods_services_category__category_name", "goods_services_category__id") .annotate( tender=Count("goods_services_category"), local=Sum("contract_value_local"), usd=Sum("contract_value_usd"), ) ) for goods in goods_services: data = { "product_name": goods["goods_services_category__category_name"], "product_id": goods["goods_services_category__id"], "local_currency_code": "USD", } if country_code: instance = Country.objects.get(country_code_alpha_2=country_code) data["local_currency_code"] = instance.currency data["tender_count"] = goods["tender"] data["amount_local"] = goods["local"] data["amount_usd"] = goods["usd"] result.append(data) return JsonResponse(result, safe=False)
class FilterParametersSuppliers(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): country_code = self.request.GET.get("country", None) buyer_id = self.request.GET.get("buyer", None) filter_args = {"supplier__isnull": False} if buyer_id: filter_args = add_filter_args("buyer", buyer_id, filter_args) if country_code: country_code = str(country_code).upper() filter_args["country__country_code_alpha_2"] = country_code try: suppliers = (Tender.objects.filter(**filter_args).values( "supplier__id", "supplier__supplier_name").distinct()) result = [] for supplier in suppliers: data = { "id": supplier["supplier__id"], "name": supplier["supplier__supplier_name"] } if country_code: data["country_code"] = country_code result.append(data) return JsonResponse(result, safe=False) except Exception: return JsonResponse([{ "error": "Country code does not exists" }], safe=False)
class BuyerProfileView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request, *args, **kwargs): pk = self.kwargs["pk"] try: buyer = Buyer.objects.get(id=pk) tenders = buyer.tenders buyer_detail = (tenders.values( "country__name", "country__country_code_alpha_2").annotate( total_usd=Sum("contract_value_usd"), total_local=Sum("contract_value_local"), ).first()) data = { "name": buyer.buyer_name, "id": pk, "code": buyer.buyer_id, "address": buyer.buyer_address, "amount_usd": buyer_detail.get("total_usd", 0), "amount_local": buyer_detail.get("total_local", 0), "tender_count": tenders.distinct().count(), "country_code": buyer_detail.get("country__country_code_alpha_2", ""), "country_name": buyer_detail.get("country__name", ""), } return JsonResponse(data, safe=False, status=status.HTTP_200_OK) except Exception as E: error = {"error": str(E)} return JsonResponse(error, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class SlugBlogShow(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request, *args, **kwargs): content_type = self.kwargs["type"] slug = self.kwargs["slug"] result = {} try: if content_type: results = InsightsPage.objects.filter( contents_type=content_type.title(), slug=slug).values("title", "published_date", "body", "author", "country_id", "featured", "content_image_id") result["title"] = results[0]["title"] result["published_date"] = results[0]["published_date"] result["body"] = results[0]["body"] result["author"] = results[0]["author"] result["featured"] = results[0]["featured"] result["country_id"] = results[0]["country_id"] result["content_image_id"] = results[0]["content_image_id"] except Exception: result = [{"error": "Content doest not exists"}] return JsonResponse(result, safe=False)
class FilterParams(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request, *args, **kwargs): try: buyers = Buyer.objects.values("id", "buyer_name") suppliers = Supplier.objects.values("id", "supplier_name") countries = Country.objects.values("id", "country_code", "name") products = GoodsServicesCategory.objects.values( "id", "category_name") result_buyer = [] result_supplier = [] result_country = [] result_product = [] result = {} if buyers: result_buyer = [{ "id": buyer["id"], "name": buyer["buyer_name"] } for buyer in buyers] if suppliers: result_supplier = [{ "id": supplier["id"], "name": supplier["supplier_name"] } for supplier in suppliers] if countries: result_country = [{ "id": country["id"], "code": country["country_code"], "name": country["name"] } for country in countries] if products: result_product = [{ "id": product["id"], "name": product["category_name"] } for product in products] result = { "buyer": result_buyer, "contracts": { "method": [ { "label": "Direct", "value": "direct" }, { "label": "Limited", "value": "limited" }, { "label": "Open", "value": "open" }, { "label": "Other", "value": "other" }, { "label": "Selective", "value": "selective" }, ], "status": [ { "label": "Active", "value": "active" }, { "label": "Cancelled", "value": "cancelled" }, { "label": "Completed", "value": "completed" }, { "label": "Other", "value": "other" }, ], }, "country": result_country, "product": result_product, "supplier": result_supplier, } return JsonResponse(result, safe=False) except Exception: return JsonResponse( [{ "error": "No buyer and supplier data available" }], safe=False)
class ProductFlowView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request, *args, **kwargs): product_id = self.kwargs["pk"] temp_country_list = [] by_value_product_country = [] temp_tender_country_list = [] by_number_product_country = [] usd_amountwise_sorted = (Tender.objects.filter( goods_services__goods_services_category__id=product_id, supplier__isnull=False, goods_services__goods_services_category__isnull=False, ).values( "supplier__id", "goods_services__goods_services_category__id", "country__id", "country__name", "goods_services__goods_services_category__category_name", ).exclude(contract_value_usd__isnull=True).annotate( count=Count("id"), product_name=F( "goods_services__goods_services_category__category_name"), product_id=F("goods_services__goods_services_category__id"), contract_value_usd=F("contract_value_usd"), contract_value_local=F("contract_value_local"), ).order_by("-contract_value_usd")) tender_countwise_sorted = (Tender.objects.filter( goods_services__goods_services_category__id=product_id, supplier__isnull=False, goods_services__goods_services_category__isnull=False, ).values( "supplier__id", "goods_services__goods_services_category__id", "country__id", "country__name", "goods_services__goods_services_category__category_name", ).annotate( count=Count("id"), product_name=F( "goods_services__goods_services_category__category_name"), product_id=F("goods_services__goods_services_category__id"), contract_value_usd=F("contract_value_usd"), contract_value_local=F("contract_value_local"), ).exclude(count__isnull=True).order_by("-count")) for i in usd_amountwise_sorted: if i["country__id"] not in temp_country_list: temp_country_list.append(i["country__id"]) by_value_product_country.append(i) for i in tender_countwise_sorted: if i["country__id"] not in temp_tender_country_list: temp_tender_country_list.append(i["country__id"]) by_number_product_country.append(i) by_number_supplier_product = (Supplier.objects.filter( tenders__goods_services__goods_services_category__id=product_id, tenders__goods_services__goods_services_category__isnull=False, ).values( "tenders__supplier__id", "tenders__goods_services__goods_services_category__id", "tenders__goods_services__goods_services_category__category_name", "tenders__supplier__supplier_name", ).annotate( count=Count("tenders__id"), contract_value_usd=Sum("tenders__contract_value_usd"), contract_value_local=Sum("tenders__contract_value_local"), ).order_by("-count")) by_value_supplier_product = (Supplier.objects.filter( tenders__goods_services__goods_services_category__id=product_id, tenders__goods_services__goods_services_category__isnull=False, ).values( "tenders__supplier__id", "tenders__goods_services__goods_services_category__id", "tenders__goods_services__goods_services_category__category_name", "tenders__supplier__supplier_name", ).annotate( count=Count("tenders__id"), contract_value_usd=Sum("tenders__contract_value_usd"), contract_value_local=Sum("tenders__contract_value_local"), ).order_by("-contract_value_usd")) results = { "by_number": { "product_country": [{ "amount_local": i["contract_value_local"], "amount_usd": i["contract_value_usd"], "country_id": i["country__id"], "country_name": i["country__name"], "product_id": i["product_id"], "product_name": i["product_name"], "tender_count": i["count"], } for i in by_number_product_country], "supplier_product": [{ "amount_local": i["contract_value_local"], "amount_usd": i["contract_value_usd"], "product_id": i["tenders__goods_services__goods_services_category__id"], "product_name": i["tenders__goods_services__goods_services_category__category_name"], "supplier_id": i["tenders__supplier__id"], "supplier_name": i["tenders__supplier__supplier_name"], "tender_count": i["count"], } for i in by_number_supplier_product[:5]], }, "by_value": { "product_country": [{ "amount_local": i["contract_value_local"], "amount_usd": i["contract_value_usd"], "country_id": i["country__id"], "country_name": i["country__name"], "product_id": i["product_id"], "product_name": i["product_name"], "tender_count": i["count"], } for i in by_value_product_country], "supplier_product": [{ "amount_local": i["contract_value_local"], "amount_usd": i["contract_value_usd"], "product_id": i["tenders__goods_services__goods_services_category__id"], "product_name": i["tenders__goods_services__goods_services_category__category_name"], "supplier_id": i["tenders__supplier__id"], "supplier_name": i["tenders__supplier__supplier_name"], "tender_count": i["count"], } for i in by_value_supplier_product[:5]], }, } return JsonResponse(results)
class TotalSpendingsView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): """ Return a list of all contracts. """ # Calculating total tender country_code = self.request.GET.get("country", None) buyer_id = self.request.GET.get("buyer") supplier_id = self.request.GET.get("supplier") filter_args = {} exclude_args = {"status": "canceled"} if country_code: country_code = str(country_code).upper() filter_args["country__country_code_alpha_2"] = country_code if buyer_id: filter_args = add_filter_args("buyer", buyer_id, filter_args) if supplier_id: filter_args = add_filter_args("supplier", supplier_id, filter_args) total_country_tender_amount = ( Tender.objects.filter(**filter_args) .exclude(**exclude_args) .aggregate(usd=Sum("contract_value_usd"), local=Sum("contract_value_local")) ) bar_chart = ( Tender.objects.filter(**filter_args) .exclude(**exclude_args) .values("procurement_procedure") .annotate(usd=Sum("contract_value_usd"), local=Sum("contract_value_local")) ) selective_sum_local = 0 limited_sum_local = 0 open_sum_local = 0 direct_sum_local = 0 limited_total = 0 open_total = 0 selective_total = 0 direct_total = 0 not_identified_total = 0 not_identified_sum_local = 0 for i in bar_chart: if i["procurement_procedure"] == "selective": selective_total = i["usd"] selective_sum_local = i["local"] elif i["procurement_procedure"] == "limited": limited_total = i["usd"] limited_sum_local = i["local"] elif i["procurement_procedure"] == "open": open_total = i["usd"] open_sum_local = i["local"] elif i["procurement_procedure"] == "direct": direct_total = i["usd"] direct_sum_local = i["local"] elif i["procurement_procedure"] == "not_identified": not_identified_total = i["usd"] not_identified_sum_local = i["local"] line_chart = ( Tender.objects.filter(**filter_args) .exclude(**exclude_args) .annotate(month=TruncMonth("contract_date")) .values("month") .annotate(usd=Sum("contract_value_usd"), local=Sum("contract_value_local")) .order_by("-month") ) line_chart_local_list = [{"date": i["month"], "value": i["local"]} for i in line_chart] line_chart_list = [{"date": i["month"], "value": i["usd"]} for i in line_chart] result = { "usd": { "total": total_country_tender_amount["usd"], "line_chart": line_chart_list, "bar_chart": [ {"method": "open", "value": open_total}, {"method": "limited", "value": limited_total}, {"method": "selective", "value": selective_total}, {"method": "direct", "value": direct_total}, {"method": "not_identified", "value": not_identified_total}, ], }, "local": { "total": total_country_tender_amount["local"], "line_chart": line_chart_local_list, "bar_chart": [ {"method": "open", "value": open_sum_local}, {"method": "limited", "value": limited_sum_local}, {"method": "selective", "value": selective_sum_local}, {"method": "direct", "value": direct_sum_local}, {"method": "not_identified", "value": not_identified_sum_local}, ], }, } return JsonResponse(result)
class GlobalSuppliersView(APIView): @method_decorator(cache_page(page_expire_period())) def get(self, request): count = int(self.request.GET.get("count", 5)) supplier = self.request.GET.get("supplier", None) product = self.request.GET.get("product", None) usd_amountwise_sorted = (Tender.objects.filter( supplier__isnull=False, goods_services__goods_services_category__isnull=False).values( "supplier__id", "goods_services__goods_services_category__id").annotate( usd=Sum("contract_value_usd")).exclude( usd__isnull=True).order_by("-usd")) countwise_sorted = (Tender.objects.filter( supplier__isnull=False, goods_services__goods_services_category__isnull=False).values( "supplier__id", "goods_services__goods_services_category__id").annotate( count=Count("id")).exclude( count__isnull=True).order_by("-count")) suppliers_dict = defaultdict(lambda: { "countwise": [], "amountwise": [] }) for i in usd_amountwise_sorted: if len(suppliers_dict[ i["goods_services__goods_services_category__id"]] ["amountwise"]) <= count: suppliers_dict[ i["goods_services__goods_services_category__id"]][ "amountwise"].append(i["supplier__id"]) for i in countwise_sorted: if len(suppliers_dict[ i["goods_services__goods_services_category__id"]] ["countwise"]) <= count: suppliers_dict[ i["goods_services__goods_services_category__id"]][ "countwise"].append(i["supplier__id"]) if supplier: final_suppliers_list_countwise = [supplier] final_suppliers_list_amountwise = [supplier] else: 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()])) if product: by_value_supplier_product = (Tender.objects.filter( goods_services__goods_services_category__id=product, supplier__id__in=final_suppliers_list_amountwise, 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("contract_value_local"), usd=Sum("contract_value_usd"), count=Count("id"), ).order_by("-usd")) by_value_product_country = (Tender.objects.filter( goods_services__goods_services_category__id=product, supplier__id__in=final_suppliers_list_amountwise, supplier__isnull=False, goods_services__goods_services_category__isnull=False, ).values( "goods_services__goods_services_category__id", "goods_services__goods_services_category__category_name", "country__id", "country__name", ).annotate( local=Sum("contract_value_local"), usd=Sum("contract_value_usd"), count=Count("id"), ).order_by("-usd")) by_number_supplier_product = (Tender.objects.filter( goods_services__goods_services_category__id=product, 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("contract_value_local"), usd=Sum("contract_value_usd"), count=Count("id"), ).order_by("-count")) by_number_product_country = (Tender.objects.filter( goods_services__goods_services_category__id=product, supplier__id__in=final_suppliers_list_countwise, supplier__isnull=False, goods_services__goods_services_category__isnull=False, ).values( "goods_services__goods_services_category__id", "goods_services__goods_services_category__category_name", "country__id", "country__name", ).annotate( local=Sum("contract_value_local"), usd=Sum("contract_value_usd"), count=Count("id"), ).order_by("-count")) else: by_value_supplier_product = (Tender.objects.filter( supplier__id__in=final_suppliers_list_amountwise, 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("contract_value_local"), usd=Sum("contract_value_usd"), count=Count("id"), ).order_by("-usd")) by_value_product_country = (Tender.objects.filter( supplier__id__in=final_suppliers_list_amountwise, supplier__isnull=False, goods_services__goods_services_category__isnull=False, ).values( "goods_services__goods_services_category__id", "goods_services__goods_services_category__category_name", "country__id", "country__name", ).annotate( local=Sum("contract_value_local"), usd=Sum("contract_value_usd"), count=Count("id"), ).order_by("-usd")) by_number_supplier_product = (Tender.objects.filter( 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("contract_value_local"), usd=Sum("contract_value_usd"), count=Count("id"), ).order_by("-count")) by_number_product_country = (Tender.objects.filter( supplier__id__in=final_suppliers_list_countwise, supplier__isnull=False, goods_services__goods_services_category__isnull=False, ).values( "goods_services__goods_services_category__id", "goods_services__goods_services_category__category_name", "country__id", "country__name", ).annotate( local=Sum("contract_value_local"), usd=Sum("contract_value_usd"), count=Count("id"), ).order_by("-count")) results = { "by_number": { "product_country": [{ "amount_local": i["local"], "amount_usd": i["usd"], "country_id": i["country__id"], "country_name": i["country__name"], "product_id": i["goods_services__goods_services_category__id"], "product_name": i["goods_services__goods_services_category__category_name"], "tender_count": i["count"], } for i in by_number_product_country], "supplier_product": [{ "amount_local": i["local"], "amount_usd": i["usd"], "product_id": i["goods_services__goods_services_category__id"], "product_name": i["goods_services__goods_services_category__category_name"], "supplier_id": i["supplier__id"], "supplier_name": i["supplier__supplier_name"], "tender_count": i["count"], } for i in by_number_supplier_product], }, "by_value": { "product_country": [{ "amount_local": i["local"], "amount_usd": i["usd"], "country_id": i["country__id"], "country_name": i["country__name"], "product_id": i["goods_services__goods_services_category__id"], "product_name": i["goods_services__goods_services_category__category_name"], "tender_count": i["count"], } for i in by_value_product_country], "supplier_product": [{ "amount_local": i["local"], "amount_usd": i["usd"], "product_id": i["goods_services__goods_services_category__id"], "product_name": i["goods_services__goods_services_category__category_name"], "supplier_id": i["supplier__id"], "supplier_name": i["supplier__supplier_name"], "tender_count": i["count"], } for i in by_value_supplier_product], }, } return JsonResponse(results)