import re from django.shortcuts import render from collections import defaultdict from hub.services.models import ( ComputePlan, VSHNAppCatPrice, ExternalPricePlans, StoragePlan, ) from django.contrib.admin.views.decorators import staff_member_required from django.db import models def natural_sort_key(name): """Extract numeric part from compute plan name for natural sorting""" match = re.search(r"compute-std-(\d+)", name) return int(match.group(1)) if match else 0 def get_external_price_comparisons(plan, appcat_price, currency, service_level): """Get external price comparisons for a specific compute plan and service""" try: # Filter by service level if external price has one set, ignore currency for comparison external_prices = ExternalPricePlans.objects.filter( compare_to=plan, service=appcat_price.service ).select_related("cloud_provider") # Filter by service level if the external price has it configured if service_level: external_prices = external_prices.filter( models.Q(service_level=service_level) | models.Q(service_level__isnull=True) ) return external_prices except Exception: return [] @staff_member_required def pricelist(request): """Generate comprehensive price list grouped by compute plan groups and service levels""" # Get filter parameters from request show_discount_details = request.GET.get("discount_details", "").lower() == "true" show_price_comparison = request.GET.get("price_comparison", "").lower() == "true" filter_cloud_provider = request.GET.get("cloud_provider", "") filter_service = request.GET.get("service", "") filter_compute_plan_group = request.GET.get("compute_plan_group", "") filter_service_level = request.GET.get("service_level", "") # Fetch all active compute plans with related data compute_plans = ( ComputePlan.objects.filter(active=True) .select_related("cloud_provider", "group") .prefetch_related("prices") .order_by("group__order", "group__name", "cloud_provider__name") ) # Apply compute plan filters if filter_cloud_provider: compute_plans = compute_plans.filter(cloud_provider__name=filter_cloud_provider) if filter_compute_plan_group: if filter_compute_plan_group == "No Group": compute_plans = compute_plans.filter(group__isnull=True) else: compute_plans = compute_plans.filter(group__name=filter_compute_plan_group) # Apply natural sorting for compute plan names compute_plans = sorted( compute_plans, key=lambda x: ( x.group.order if x.group else 999, # No group plans at the end x.group.name if x.group else "ZZZ", x.cloud_provider.name, natural_sort_key(x.name), ), ) # Fetch all appcat price configurations appcat_prices = ( VSHNAppCatPrice.objects.all() .select_related("service", "discount_model") .prefetch_related("base_fees", "unit_rates", "discount_model__tiers") .order_by("service__name") ) # Apply service filter if filter_service: appcat_prices = appcat_prices.filter(service__name=filter_service) pricing_data_by_group_and_service_level = defaultdict(lambda: defaultdict(list)) processed_combinations = set() # Generate pricing combinations for each compute plan and service for plan in compute_plans: plan_currencies = set(plan.prices.values_list("currency", flat=True)) for appcat_price in appcat_prices: # Determine units based on variable unit type if appcat_price.variable_unit == VSHNAppCatPrice.VariableUnit.RAM: units = int(plan.ram) elif appcat_price.variable_unit == VSHNAppCatPrice.VariableUnit.CPU: units = int(plan.vcpus) else: continue base_fee_currencies = set( appcat_price.base_fees.values_list("currency", flat=True) ) service_levels = appcat_price.unit_rates.values_list( "service_level", flat=True ).distinct() # Apply service level filter if filter_service_level: service_levels = [ sl for sl in service_levels if dict(VSHNAppCatPrice.ServiceLevel.choices)[sl] == filter_service_level ] for service_level in service_levels: unit_rate_currencies = set( appcat_price.unit_rates.filter( service_level=service_level ).values_list("currency", flat=True) ) # Find currencies that exist across all pricing components matching_currencies = plan_currencies.intersection( base_fee_currencies ).intersection(unit_rate_currencies) if not matching_currencies: continue for currency in matching_currencies: combination_key = ( plan.cloud_provider.name, plan.name, appcat_price.service.name, service_level, currency, ) # Skip if combination already processed if combination_key in processed_combinations: continue processed_combinations.add(combination_key) # Get pricing components compute_plan_price = plan.get_price(currency) base_fee = appcat_price.get_base_fee(currency) unit_rate = appcat_price.get_unit_rate(currency, service_level) # Skip if any pricing component is missing if any( price is None for price in [compute_plan_price, base_fee, unit_rate] ): continue # Calculate replica enforcement based on service level if service_level == VSHNAppCatPrice.ServiceLevel.GUARANTEED: replica_enforce = appcat_price.ha_replica_min else: replica_enforce = 1 total_units = units * replica_enforce standard_sla_price = base_fee + (total_units * unit_rate) # Apply discount if available discount_breakdown = None if ( appcat_price.discount_model and appcat_price.discount_model.active ): discounted_price = ( appcat_price.discount_model.calculate_discount( unit_rate, total_units ) ) sla_price = base_fee + discounted_price discount_savings = standard_sla_price - sla_price discount_percentage = ( (discount_savings / standard_sla_price) * 100 if standard_sla_price > 0 else 0 ) discount_breakdown = ( appcat_price.discount_model.get_discount_breakdown( unit_rate, total_units ) ) else: sla_price = standard_sla_price discounted_price = total_units * unit_rate discount_savings = 0 discount_percentage = 0 final_price = compute_plan_price + sla_price service_level_display = dict(VSHNAppCatPrice.ServiceLevel.choices)[ service_level ] # Get external price comparisons if enabled external_comparisons = [] if show_price_comparison: external_prices = get_external_price_comparisons( plan, appcat_price, currency, service_level ) for ext_price in external_prices: # Calculate price difference using external price currency difference = ext_price.amount - final_price ratio = ( ext_price.amount / final_price if final_price > 0 else 0 ) external_comparisons.append( { "plan_name": ext_price.plan_name, "provider": ext_price.cloud_provider.name, "description": ext_price.description, "amount": ext_price.amount, "currency": ext_price.currency, # Use external price currency "vcpus": ext_price.vcpus, "ram": ext_price.ram, "storage": ext_price.storage, "replicas": ext_price.replicas, "difference": difference, "ratio": ratio, "source": ext_price.source, "date_retrieved": ext_price.date_retrieved, } ) group_name = plan.group.name if plan.group else "No Group" # Get storage plans for this cloud provider storage_plans = StoragePlan.objects.filter( cloud_provider=plan.cloud_provider ).prefetch_related("prices") # Add pricing data to the grouped structure pricing_data_by_group_and_service_level[group_name][ service_level_display ].append( { "cloud_provider": plan.cloud_provider.name, "service": appcat_price.service.name, "compute_plan": plan.name, "compute_plan_group": group_name, "compute_plan_group_description": ( plan.group.description if plan.group else "" ), "compute_plan_group_node_label": ( plan.group.node_label if plan.group else "" ), "storage_plans": storage_plans, "vcpus": plan.vcpus, "ram": plan.ram, "cpu_mem_ratio": plan.cpu_mem_ratio, "term": plan.get_term_display(), "currency": currency, "compute_plan_price": compute_plan_price, "variable_unit": appcat_price.get_variable_unit_display(), "units": units, "replica_enforce": replica_enforce, "total_units": total_units, "service_level": service_level_display, "sla_base": base_fee, "sla_per_unit": unit_rate, "sla_price": sla_price, "standard_sla_price": standard_sla_price, "discounted_sla_price": ( base_fee + discounted_price if appcat_price.discount_model and appcat_price.discount_model.active else None ), "discount_savings": discount_savings, "discount_percentage": discount_percentage, "discount_breakdown": discount_breakdown, "final_price": final_price, "discount_model": ( appcat_price.discount_model.name if appcat_price.discount_model else None ), "has_discount": bool( appcat_price.discount_model and appcat_price.discount_model.active ), "external_comparisons": external_comparisons, } ) # Order groups correctly, placing "No Group" last ordered_groups_intermediate = {} all_group_names = list(pricing_data_by_group_and_service_level.keys()) if "No Group" in all_group_names: all_group_names.remove("No Group") all_group_names.append("No Group") for group_name_key in all_group_names: ordered_groups_intermediate[group_name_key] = ( pricing_data_by_group_and_service_level[group_name_key] ) # Convert defaultdicts to regular dicts for the template final_context_data = {} for group_key, service_levels_dict in ordered_groups_intermediate.items(): final_context_data[group_key] = { sl_key: list(plans_list) for sl_key, plans_list in service_levels_dict.items() } # Get filter options for dropdowns all_cloud_providers = ( ComputePlan.objects.filter(active=True) .values_list("cloud_provider__name", flat=True) .distinct() .order_by("cloud_provider__name") ) all_services = ( VSHNAppCatPrice.objects.values_list("service__name", flat=True) .distinct() .order_by("service__name") ) all_compute_plan_groups = list( ComputePlan.objects.filter(active=True, group__isnull=False) .values_list("group__name", flat=True) .distinct() .order_by("group__name") ) all_compute_plan_groups.append("No Group") # Add option for plans without groups all_service_levels = [choice[1] for choice in VSHNAppCatPrice.ServiceLevel.choices] context = { "pricing_data_by_group_and_service_level": final_context_data, "show_discount_details": show_discount_details, "show_price_comparison": show_price_comparison, "filter_cloud_provider": filter_cloud_provider, "filter_service": filter_service, "filter_compute_plan_group": filter_compute_plan_group, "filter_service_level": filter_service_level, "all_cloud_providers": all_cloud_providers, "all_services": all_services, "all_compute_plan_groups": all_compute_plan_groups, "all_service_levels": all_service_levels, } return render(request, "services/pricelist.html", context)