from django.db.models import Sum, Count from django.db.models.functions import Coalesce from apps.authentication.models import Organization from apps.authentication.services.service import get_all_org_child from apps.core.services.filter.search import DynamicSearchService from apps.product.models import OrganizationQuotaStats class QuotaDashboardService: """ dashboard of quota information """ @staticmethod def get_dashboard(self, org: Organization, start_date: str = None, end_date: str = None, search_fields: list[str] = None): orgs_child = get_all_org_child(org=org) orgs_child.append(org) if org.type.key == 'ADM': org_quota_stats = OrganizationQuotaStats.objects.all() else: org_quota_stats = OrganizationQuotaStats.objects.filter( organization__in=orgs_child ) # filter queryset (transactions & items) by date if start_date and end_date: org_quota_stats = DynamicSearchService( queryset=org_quota_stats, start=start_date, end=end_date, date_field="create_date", search_fields=search_fields ).apply() org_quota_stats = org_quota_stats.aggregate( total_quotas=Count("quota", distinct=True), total_distributed=Coalesce(Sum("total_distributed", ), 0), remaining_amount=Coalesce(Sum("remaining_amount", ), 0), inventory_received=Coalesce(Sum("inventory_received", ), 0), sold_amount=Coalesce(Sum("sold_amount", ), 0), total_amount=Coalesce(Sum("total_amount", ), 0), inventory_entry_balance=Coalesce(Sum("inventory_entry_balance", ), 0), ) return { "quotas_summary": org_quota_stats, }