From 61cabd1b1e49e75914f8360856a7b645b0bfa91c Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Fri, 20 Jun 2025 17:40:38 +0200 Subject: [PATCH 01/60] implement plan pricing --- hub/services/admin/content.py | 2 +- hub/services/admin/services.py | 20 +- .../0037_remove_plan_pricing_planprice.py | 63 ++ hub/services/models/services.py | 36 +- hub/services/static/js/price-calculator.js | 885 +----------------- .../templates/services/offering_detail.html | 213 +---- hub/services/views/offerings.py | 230 +---- 7 files changed, 192 insertions(+), 1257 deletions(-) create mode 100644 hub/services/migrations/0037_remove_plan_pricing_planprice.py diff --git a/hub/services/admin/content.py b/hub/services/admin/content.py index 9d601ae..2b655d1 100644 --- a/hub/services/admin/content.py +++ b/hub/services/admin/content.py @@ -13,7 +13,7 @@ class PlanInline(admin.StackedInline): model = Plan extra = 1 fieldsets = ( - (None, {"fields": ("name", "description", "pricing", "plan_description")}), + (None, {"fields": ("name", "description", "plan_description")}), ) diff --git a/hub/services/admin/services.py b/hub/services/admin/services.py index 44f848b..f679c09 100644 --- a/hub/services/admin/services.py +++ b/hub/services/admin/services.py @@ -5,7 +5,7 @@ Admin classes for services and service offerings from django.contrib import admin from django.utils.html import format_html -from ..models import Service, ServiceOffering, ExternalLink, ExternalLinkOffering, Plan +from ..models import Service, ServiceOffering, ExternalLink, ExternalLinkOffering, Plan, PlanPrice class ExternalLinkInline(admin.TabularInline): @@ -32,7 +32,7 @@ class PlanInline(admin.StackedInline): model = Plan extra = 1 fieldsets = ( - (None, {"fields": ("name", "description", "pricing", "plan_description")}), + (None, {"fields": ("name", "description", "plan_description")}), ) @@ -57,6 +57,18 @@ class OfferingInline(admin.StackedInline): show_change_link = True +class PlanPriceInline(admin.TabularInline): + model = PlanPrice + extra = 1 + + +class PlanAdmin(admin.ModelAdmin): + inlines = [PlanPriceInline] + list_display = ("name", "offering") + search_fields = ("name",) + list_filter = ("offering",) + + @admin.register(Service) class ServiceAdmin(admin.ModelAdmin): """Admin configuration for Service model""" @@ -106,3 +118,7 @@ class ServiceOfferingAdmin(admin.ModelAdmin): list_filter = ("service", "cloud_provider") search_fields = ("service__name", "cloud_provider__name", "description") inlines = [ExternalLinkOfferingInline, PlanInline] + + +admin.site.register(Plan, PlanAdmin) +admin.site.register(PlanPrice) diff --git a/hub/services/migrations/0037_remove_plan_pricing_planprice.py b/hub/services/migrations/0037_remove_plan_pricing_planprice.py new file mode 100644 index 0000000..e5476f1 --- /dev/null +++ b/hub/services/migrations/0037_remove_plan_pricing_planprice.py @@ -0,0 +1,63 @@ +# Generated by Django 5.2 on 2025-06-20 15:28 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ("services", "0036_alter_vshnappcataddonbasefee_options_and_more"), + ] + + operations = [ + migrations.RemoveField( + model_name="plan", + name="pricing", + ), + migrations.CreateModel( + name="PlanPrice", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "currency", + models.CharField( + choices=[ + ("CHF", "Swiss Franc"), + ("EUR", "Euro"), + ("USD", "US Dollar"), + ], + max_length=3, + ), + ), + ( + "amount", + models.DecimalField( + decimal_places=2, + help_text="Price in the specified currency, excl. VAT", + max_digits=10, + ), + ), + ( + "plan", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="plan_prices", + to="services.plan", + ), + ), + ], + options={ + "ordering": ["currency"], + "unique_together": {("plan", "currency")}, + }, + ), + ] diff --git a/hub/services/models/services.py b/hub/services/models/services.py index 5c155b8..aa2e1ba 100644 --- a/hub/services/models/services.py +++ b/hub/services/models/services.py @@ -4,10 +4,14 @@ from django.core.validators import URLValidator from django.urls import reverse from django.utils.text import slugify from django_prose_editor.fields import ProseEditorField +from typing import TYPE_CHECKING, Optional -from .base import Category, ReusableText, ManagedServiceProvider, validate_image_size +from .base import Category, ReusableText, ManagedServiceProvider, validate_image_size, Currency from .providers import CloudProvider +if TYPE_CHECKING: + from .services import PlanPrice + class Service(models.Model): name = models.CharField(max_length=200) @@ -97,10 +101,31 @@ class ServiceOffering(models.Model): ) +class PlanPrice(models.Model): + plan = models.ForeignKey( + 'Plan', on_delete=models.CASCADE, related_name='plan_prices' + ) + currency = models.CharField( + max_length=3, + choices=Currency.choices, + ) + amount = models.DecimalField( + max_digits=10, + decimal_places=2, + help_text="Price in the specified currency, excl. VAT", + ) + + class Meta: + unique_together = ("plan", "currency") + ordering = ["currency"] + + def __str__(self): + return f"{self.plan.name} - {self.amount} {self.currency}" + + class Plan(models.Model): name = models.CharField(max_length=100) description = ProseEditorField(blank=True, null=True) - pricing = ProseEditorField(blank=True, null=True) plan_description = models.ForeignKey( ReusableText, on_delete=models.PROTECT, @@ -122,6 +147,13 @@ class Plan(models.Model): def __str__(self): return f"{self.offering} - {self.name}" + def get_price(self, currency_code: str) -> Optional[float]: + from hub.services.models.services import PlanPrice + price_obj = PlanPrice.objects.filter(plan=self, currency=currency_code).first() + if price_obj: + return price_obj.amount + return None + class ExternalLinkOffering(models.Model): offering = models.ForeignKey( diff --git a/hub/services/static/js/price-calculator.js b/hub/services/static/js/price-calculator.js index 54b2af9..90112b9 100644 --- a/hub/services/static/js/price-calculator.js +++ b/hub/services/static/js/price-calculator.js @@ -982,850 +982,6 @@ Please contact me with next steps for ordering this configuration.`; if (this.instancesValue) this.instancesValue.textContent = '1'; } } - - // Setup order button click handler - setupOrderButton() { - if (this.orderButton) { - this.orderButton.addEventListener('click', (e) => { - e.preventDefault(); - this.handleOrderClick(); - }); - } - } - - // Handle order button click - handleOrderClick() { - if (this.selectedConfiguration) { - // Pre-fill the contact form with configuration details - this.prefillContactForm(); - - // Scroll to the contact form - const contactForm = document.getElementById('order-form'); - if (contactForm) { - contactForm.scrollIntoView({ behavior: 'smooth', block: 'start' }); - } - } - } - - // Pre-fill contact form with selected configuration - prefillContactForm() { - if (!this.selectedConfiguration) return; - - const config = this.selectedConfiguration; - - // Create configuration summary message - const configMessage = this.generateConfigurationMessage(config); - - // Find and fill the message textarea in the contact form - const messageField = document.querySelector('#order-form textarea[name="message"]'); - if (messageField) { - messageField.value = configMessage; - } - - // Store configuration details in hidden field - const detailsField = document.querySelector('#order-form input[name="details"]'); - if (detailsField) { - detailsField.value = JSON.stringify({ - plan: config.planName, - vcpus: config.vcpus, - memory: config.memory, - storage: config.storage, - instances: config.instances, - serviceLevel: config.serviceLevel, - totalPrice: config.totalPrice, - addons: config.addons || [] - }); - } - } - - // Generate human-readable configuration message - generateConfigurationMessage(config) { - let message = `I would like to order the following configuration: - -Plan: ${config.planName} (${config.planGroup}) -vCPUs: ${config.vcpus} -Memory: ${config.memory} GB -Storage: ${config.storage} GB -Instances: ${config.instances} -Service Level: ${config.serviceLevel}`; - - // Add addons to the message if any are selected - if (config.addons && config.addons.length > 0) { - message += '\n\nSelected Add-ons:'; - config.addons.forEach(addon => { - message += `\n- ${addon.name}: CHF ${addon.price}`; - }); - } - - message += `\n\nTotal Monthly Price: CHF ${config.totalPrice} - -Please contact me with next steps for ordering this configuration.`; - - return message; - } - - // Load pricing data from API endpoint - async loadPricingData() { - try { - const response = await fetch(`/offering/${this.currentOffering.provider_slug}/${this.currentOffering.service_slug}/?pricing=json`); - if (!response.ok) { - throw new Error('Failed to load pricing data'); - } - - const data = await response.json(); - this.pricingData = data.pricing || data; - - // Extract addons data from the plans - addons are embedded in each plan - this.extractAddonsData(); - - // Extract storage price from the first available plan - this.extractStoragePrice(); - - this.setupEventListeners(); - this.populatePlanDropdown(); - this.updateAddons(); - this.updatePricing(); - } catch (error) { - console.error('Error loading pricing data:', error); - this.showError('Failed to load pricing information'); - } - } - - // Extract replica information and storage price from pricing data - extractStoragePrice() { - if (!this.pricingData) return; - - // Find the first plan with storage pricing data and replica info - for (const groupName of Object.keys(this.pricingData)) { - const group = this.pricingData[groupName]; - for (const serviceLevel of Object.keys(group)) { - const plans = group[serviceLevel]; - if (plans.length > 0 && plans[0].storage_price !== undefined) { - this.storagePrice = parseFloat(plans[0].storage_price); - this.replicaInfo = { - ha_replica_min: plans[0].ha_replica_min || 1, - ha_replica_max: plans[0].ha_replica_max || 1 - }; - return; - } - } - } - } - - // Extract addons data from pricing plans - extractAddonsData() { - if (!this.pricingData) return; - - this.addonsData = {}; - - // Extract addons from the first available plan for each service level - Object.keys(this.pricingData).forEach(groupName => { - const group = this.pricingData[groupName]; - Object.keys(group).forEach(serviceLevel => { - const plans = group[serviceLevel]; - if (plans.length > 0) { - // Use the first plan's addon data for this service level - const plan = plans[0]; - const allAddons = []; - - // Add mandatory addons - if (plan.mandatory_addons) { - plan.mandatory_addons.forEach(addon => { - allAddons.push({ - ...addon, - is_mandatory: true, - addon_type: addon.addon_type === "Base Fee" ? "BASE_FEE" : "UNIT_RATE" - }); - }); - } - - // Add optional addons - if (plan.optional_addons) { - plan.optional_addons.forEach(addon => { - allAddons.push({ - ...addon, - is_mandatory: false, - addon_type: addon.addon_type === "Base Fee" ? "BASE_FEE" : "UNIT_RATE" - }); - }); - } - - this.addonsData[serviceLevel] = allAddons; - } - }); - }); - } - - // Setup event listeners for calculator controls - setupEventListeners() { - if (!this.cpuRange || !this.memoryRange || !this.storageRange || !this.instancesRange) return; - - // Setup service levels based on available data - this.setupServiceLevels(); - - // Slider event listeners - this.cpuRange.addEventListener('input', () => { - this.cpuValue.textContent = this.cpuRange.value; - this.updatePricing(); - }); - - this.memoryRange.addEventListener('input', () => { - this.memoryValue.textContent = this.memoryRange.value; - this.updatePricing(); - }); - - this.storageRange.addEventListener('input', () => { - this.storageValue.textContent = this.storageRange.value; - this.updatePricing(); - }); - - this.instancesRange.addEventListener('input', () => { - this.instancesValue.textContent = this.instancesRange.value; - this.updatePricing(); - }); - - // Service level change listeners - this.serviceLevelInputs.forEach(input => { - input.addEventListener('change', () => { - this.updateInstancesSlider(); - this.populatePlanDropdown(); - this.updateAddons(); - this.updatePricing(); - }); - }); - - // Plan selection listener - if (this.planSelect) { - this.planSelect.addEventListener('change', () => { - if (this.planSelect.value) { - const selectedPlan = JSON.parse(this.planSelect.value); - - // Update sliders to match selected plan - this.cpuRange.value = selectedPlan.vcpus; - this.memoryRange.value = selectedPlan.ram; - this.cpuValue.textContent = selectedPlan.vcpus; - this.memoryValue.textContent = selectedPlan.ram; - - // Fade out CPU and Memory sliders since plan is manually selected - this.fadeOutSliders(['cpu', 'memory']); - - // Update addons for the new configuration - this.updateAddons(); - // Update pricing with the selected plan - this.updatePricingWithPlan(selectedPlan); - } else { - // Auto-select mode - reset sliders to default values - this.resetSlidersToDefaults(); - - // Auto-select mode - fade sliders back in - this.fadeInSliders(['cpu', 'memory']); - - // Auto-select mode - update addons and recalculate - this.updateAddons(); - this.updatePricing(); - } - }); - } - - // Initialize instances slider - this.updateInstancesSlider(); - } - - // Update instances slider based on service level and replica info - updateInstancesSlider() { - if (!this.instancesRange || !this.replicaInfo) return; - - const serviceLevel = document.querySelector('input[name="serviceLevel"]:checked')?.value; - - if (serviceLevel === 'Guaranteed Availability') { - // For GA, min is ha_replica_min - this.instancesRange.min = this.replicaInfo.ha_replica_min; - this.instancesRange.value = Math.max(this.instancesRange.value, this.replicaInfo.ha_replica_min); - } else { - // For BE, min is 1 - this.instancesRange.min = 1; - this.instancesRange.value = Math.max(this.instancesRange.value, 1); - } - - // Set max to ha_replica_max - this.instancesRange.max = this.replicaInfo.ha_replica_max; - - // Update display value - this.instancesValue.textContent = this.instancesRange.value; - - // Update the min/max display under the slider using direct IDs - const instancesMinDisplay = document.getElementById('instancesMinDisplay'); - const instancesMaxDisplay = document.getElementById('instancesMaxDisplay'); - - if (instancesMinDisplay) instancesMinDisplay.textContent = this.instancesRange.min; - if (instancesMaxDisplay) instancesMaxDisplay.textContent = this.instancesRange.max; - } - - // Setup service levels dynamically from pricing data - setupServiceLevels() { - if (!this.pricingData) return; - - const serviceLevelGroup = document.getElementById('serviceLevelGroup'); - if (!serviceLevelGroup) return; - - // Get all available service levels from the pricing data - const availableServiceLevels = new Set(); - Object.keys(this.pricingData).forEach(groupName => { - const group = this.pricingData[groupName]; - Object.keys(group).forEach(serviceLevel => { - availableServiceLevels.add(serviceLevel); - }); - }); - - // Clear existing service level buttons - serviceLevelGroup.innerHTML = ''; - - // Create buttons for each available service level - let isFirst = true; - availableServiceLevels.forEach(serviceLevel => { - const inputId = `serviceLevel${serviceLevel.replace(/\s+/g, '')}`; - - // Create radio input - const input = document.createElement('input'); - input.type = 'radio'; - input.className = 'btn-check'; - input.name = 'serviceLevel'; - input.id = inputId; - input.value = serviceLevel; - if (isFirst) { - input.checked = true; - isFirst = false; - } - - // Create label - const label = document.createElement('label'); - label.className = 'btn btn-outline-primary'; - label.setAttribute('for', inputId); - label.textContent = serviceLevel; - - // Add event listener - input.addEventListener('change', () => { - this.updateInstancesSlider(); - this.populatePlanDropdown(); - this.updateAddons(); - this.updatePricing(); - }); - - serviceLevelGroup.appendChild(input); - serviceLevelGroup.appendChild(label); - }); - - // Update the serviceLevelInputs reference - this.serviceLevelInputs = document.querySelectorAll('input[name="serviceLevel"]'); - - // Calculate and set slider maximums based on available plans - this will call updateSliderDisplayValues() - this.updateSliderMaximums(); - } - - // Calculate maximum values for sliders based on available plans - updateSliderMaximums() { - if (!this.pricingData || !this.cpuRange || !this.memoryRange) return; - - let maxCpus = 0; - let maxMemory = 0; - - // Find maximum CPU and memory across all plans - Object.keys(this.pricingData).forEach(groupName => { - const group = this.pricingData[groupName]; - Object.keys(group).forEach(serviceLevel => { - group[serviceLevel].forEach(plan => { - const planCpus = parseFloat(plan.vcpus); - const planMemory = parseFloat(plan.ram); - - if (planCpus > maxCpus) maxCpus = planCpus; - if (planMemory > maxMemory) maxMemory = planMemory; - }); - }); - }); - - // Set slider maximums with some padding - if (maxCpus > 0) { - this.cpuRange.max = Math.ceil(maxCpus); - } - - if (maxMemory > 0) { - this.memoryRange.max = Math.ceil(maxMemory); - } - - // Update display values after changing min/max - moved to end and call explicitly - this.updateSliderDisplayValues(); - } - - // Populate plan dropdown based on selected service level - populatePlanDropdown() { - if (!this.planSelect || !this.pricingData) return; - - const serviceLevel = document.querySelector('input[name="serviceLevel"]:checked')?.value; - if (!serviceLevel) return; - - // Clear existing options - this.planSelect.innerHTML = ''; - - // Collect all plans for selected service level - const availablePlans = []; - Object.keys(this.pricingData).forEach(groupName => { - const group = this.pricingData[groupName]; - if (group[serviceLevel]) { - group[serviceLevel].forEach(plan => { - availablePlans.push({ - ...plan, - groupName: groupName - }); - }); - } - }); - - // Sort plans by vCPU, then by RAM - availablePlans.sort((a, b) => { - if (parseInt(a.vcpus) !== parseInt(b.vcpus)) { - return parseInt(a.vcpus) - parseInt(b.vcpus); - } - return parseInt(a.ram) - parseInt(b.ram); - }); - - // Add plans to dropdown - availablePlans.forEach(plan => { - const option = document.createElement('option'); - option.value = JSON.stringify(plan); - option.textContent = `${plan.compute_plan} - ${plan.vcpus} vCPUs, ${plan.ram} GB RAM`; - this.planSelect.appendChild(option); - }); - } - - // Update addons based on current configuration - updateAddons() { - if (!this.addonsContainer || !this.addonsData) { - // Hide addons section if no container or data - const addonsSection = document.getElementById('addonsSection'); - if (addonsSection) addonsSection.style.display = 'none'; - return; - } - - const serviceLevel = document.querySelector('input[name="serviceLevel"]:checked')?.value; - if (!serviceLevel || !this.addonsData[serviceLevel]) { - // Hide addons section if no service level or no addons for this level - const addonsSection = document.getElementById('addonsSection'); - if (addonsSection) addonsSection.style.display = 'none'; - return; - } - - const addons = this.addonsData[serviceLevel]; - - // Clear existing addons - this.addonsContainer.innerHTML = ''; - - // Show or hide addons section based on availability - const addonsSection = document.getElementById('addonsSection'); - if (addons && addons.length > 0) { - if (addonsSection) addonsSection.style.display = 'block'; - } else { - if (addonsSection) addonsSection.style.display = 'none'; - return; - } - - // Add each addon - addons.forEach(addon => { - const addonElement = document.createElement('div'); - addonElement.className = `addon-item mb-2 p-2 border rounded ${addon.is_mandatory ? 'bg-light' : ''}`; - - addonElement.innerHTML = ` -
- - -
- `; - - this.addonsContainer.appendChild(addonElement); - - // Add event listener for optional addons - if (!addon.is_mandatory) { - const checkbox = addonElement.querySelector('.addon-checkbox'); - checkbox.addEventListener('change', () => { - // Update addon prices and recalculate total - this.updateAddonPrices(); - this.updatePricing(); - }); - } - }); - - // Update addon prices - this.updateAddonPrices(); - } // Update addon prices based on current configuration - updateAddonPrices() { - if (!this.addonsContainer) return; - - const cpus = parseInt(this.cpuRange?.value || 2); - const memory = parseInt(this.memoryRange?.value || 4); - const storage = parseInt(this.storageRange?.value || 20); - const instances = parseInt(this.instancesRange?.value || 1); - - // Find the current plan data to get variable_unit for addon calculations - const matchedPlan = this.getCurrentPlan(); - const variableUnit = matchedPlan?.variable_unit || 'CPU'; - const units = variableUnit === 'CPU' ? cpus : memory; - const totalUnits = units * instances; - - const addonCheckboxes = this.addonsContainer.querySelectorAll('.addon-checkbox'); - addonCheckboxes.forEach(checkbox => { - const addon = JSON.parse(checkbox.dataset.addon); - const priceElement = checkbox.parentElement.querySelector('.addon-price-value'); - - let calculatedPrice = 0; - - // Calculate addon price based on type - if (addon.addon_type === 'BASE_FEE') { - // Base fee: price per instance - calculatedPrice = parseFloat(addon.price || 0) * instances; - } else if (addon.addon_type === 'UNIT_RATE') { - // Unit rate: price per unit (CPU or memory) across all instances - calculatedPrice = parseFloat(addon.price_per_unit || 0) * totalUnits; - } - - // Update the display price - if (priceElement) { - priceElement.textContent = calculatedPrice.toFixed(2); - } - - // Store the calculated price for later use in total calculations - checkbox.dataset.calculatedPrice = calculatedPrice.toString(); - }); - } - - // Get current plan based on configuration - getCurrentPlan() { - const cpus = parseInt(this.cpuRange?.value || 2); - const memory = parseInt(this.memoryRange?.value || 4); - const serviceLevel = document.querySelector('input[name="serviceLevel"]:checked')?.value; - - if (this.planSelect?.value) { - return JSON.parse(this.planSelect.value); - } - - return this.findBestMatchingPlan(cpus, memory, serviceLevel); - } - - // Find best matching plan based on requirements - findBestMatchingPlan(cpus, memory, serviceLevel) { - if (!this.pricingData) return null; - - let bestMatch = null; - let bestScore = Infinity; - - // Iterate through all groups and service levels - Object.keys(this.pricingData).forEach(groupName => { - const group = this.pricingData[groupName]; - - if (group[serviceLevel]) { - group[serviceLevel].forEach(plan => { - const planCpus = parseInt(plan.vcpus); - const planMemory = parseInt(plan.ram); - - // Check if plan meets minimum requirements - if (planCpus >= cpus && planMemory >= memory) { - // Calculate efficiency score (lower is better) - const cpuOverhead = planCpus - cpus; - const memoryOverhead = planMemory - memory; - const score = cpuOverhead + memoryOverhead + plan.final_price * 0.1; - - if (score < bestScore) { - bestScore = score; - bestMatch = { - ...plan, - groupName: groupName - }; - } - } - }); - } - }); - - return bestMatch; - } - - // Update pricing with specific plan - updatePricingWithPlan(selectedPlan) { - const storage = parseInt(this.storageRange?.value || 20); - const instances = parseInt(this.instancesRange?.value || 1); - - // Update addon prices first to ensure calculated prices are current - this.updateAddonPrices(); - - this.showPlanDetails(selectedPlan, storage, instances); - this.updateStatusMessage('Plan selected directly!', 'success'); - } - - // Main pricing update function - updatePricing() { - if (!this.pricingData || !this.cpuRange || !this.memoryRange || !this.storageRange || !this.instancesRange) return; - - // Update addon prices first to ensure they're current - this.updateAddonPrices(); - - // Reset plan selection if in auto-select mode - if (!this.planSelect?.value) { - const cpus = parseInt(this.cpuRange.value); - const memory = parseInt(this.memoryRange.value); - const storage = parseInt(this.storageRange.value); - const instances = parseInt(this.instancesRange.value); - const serviceLevel = document.querySelector('input[name="serviceLevel"]:checked')?.value; - - if (!serviceLevel) return; - - // Find best matching plan - const matchedPlan = this.findBestMatchingPlan(cpus, memory, serviceLevel); - - if (matchedPlan) { - this.showPlanDetails(matchedPlan, storage, instances); - this.updateStatusMessage('Perfect match found!', 'success'); - } else { - this.showNoMatch(); - } - } else { - // Plan is directly selected, update storage pricing - const selectedPlan = JSON.parse(this.planSelect.value); - const storage = parseInt(this.storageRange.value); - const instances = parseInt(this.instancesRange.value); - - // Update addon prices for current configuration - this.updateAddonPrices(); - this.showPlanDetails(selectedPlan, storage, instances); - this.updateStatusMessage('Plan selected directly!', 'success'); - } - } - - // Show plan details in the UI - showPlanDetails(plan, storage, instances) { - if (!this.selectedPlanDetails) return; - - // Show plan details section - this.planMatchStatus.style.display = 'block'; - this.selectedPlanDetails.style.display = 'block'; - if (this.noMatchFound) this.noMatchFound.style.display = 'none'; - - // Get current service level - const serviceLevel = document.querySelector('input[name="serviceLevel"]:checked')?.value || 'Best Effort'; - - // Update plan information - if (this.planGroup) this.planGroup.textContent = plan.groupName; - if (this.planName) this.planName.textContent = plan.compute_plan; - if (this.planDescription) this.planDescription.textContent = plan.compute_plan_group_description || ''; - if (this.planCpus) this.planCpus.textContent = plan.vcpus; - if (this.planMemory) this.planMemory.textContent = plan.ram + ' GB'; - if (this.planInstances) this.planInstances.textContent = instances; - if (this.planServiceLevel) this.planServiceLevel.textContent = serviceLevel; - - // Ensure addon prices are calculated with current configuration - this.updateAddonPrices(); - - // Calculate pricing using final price from plan data (which already includes mandatory addons) - // plan.final_price = compute_plan_price + sla_price (where sla_price includes mandatory addons) - const managedServicePricePerInstance = parseFloat(plan.final_price); - - // Collect addon information for display and calculation - let mandatoryAddonTotal = 0; - let optionalAddonTotal = 0; - const mandatoryAddons = []; - const selectedOptionalAddons = []; - - if (this.addonsContainer) { - const addonCheckboxes = this.addonsContainer.querySelectorAll('.addon-checkbox'); - addonCheckboxes.forEach(checkbox => { - const addon = JSON.parse(checkbox.dataset.addon); - const calculatedPrice = parseFloat(checkbox.dataset.calculatedPrice || 0); - - if (addon.is_mandatory) { - // Mandatory addons are already included in plan.final_price - // We collect them for display purposes only - mandatoryAddons.push({ - name: addon.name, - price: calculatedPrice.toFixed(2) - }); - } else if (checkbox.checked) { - // Only count checked optional addons - optionalAddonTotal += calculatedPrice; - selectedOptionalAddons.push({ - name: addon.name, - price: calculatedPrice.toFixed(2) - }); - } - }); - } - - const managedServicePrice = managedServicePricePerInstance * instances; - - // Use storage price from plan data or fallback to instance variable - const storageUnitPrice = plan.storage_price !== undefined ? parseFloat(plan.storage_price) : this.storagePrice; - const storagePriceValue = storage * storageUnitPrice * instances; - - // Total price = managed service price (includes mandatory addons) + storage + optional addons - const totalPriceValue = managedServicePrice + storagePriceValue + optionalAddonTotal; - - // Update pricing display - if (this.managedServicePrice) this.managedServicePrice.textContent = managedServicePrice.toFixed(2); - if (this.storagePriceEl) this.storagePriceEl.textContent = storagePriceValue.toFixed(2); - if (this.storageAmount) this.storageAmount.textContent = storage; - if (this.totalPrice) this.totalPrice.textContent = totalPriceValue.toFixed(2); - - // Update addon pricing display - this.updateAddonPricingDisplay(mandatoryAddons, selectedOptionalAddons); - - // Store current configuration for order button - this.selectedConfiguration = { - planName: plan.compute_plan, - planGroup: plan.groupName, - vcpus: plan.vcpus, - memory: plan.ram, - storage: storage, - instances: instances, - serviceLevel: serviceLevel, - totalPrice: totalPriceValue.toFixed(2), - addons: [...mandatoryAddons, ...selectedOptionalAddons] - }; - } - - // Update addon pricing display in the results panel - updateAddonPricingDisplay(mandatoryAddons, selectedOptionalAddons) { - if (!this.addonPricingContainer) return; - - // Clear existing addon pricing display - this.addonPricingContainer.innerHTML = ''; - - // Add mandatory addons to pricing breakdown (for informational purposes only) - if (mandatoryAddons && mandatoryAddons.length > 0) { - // Add a note explaining mandatory addons are included - const mandatoryNote = document.createElement('div'); - mandatoryNote.className = 'text-muted small mb-2'; - mandatoryNote.innerHTML = 'Required add-ons (included in managed service price):'; - this.addonPricingContainer.appendChild(mandatoryNote); - - mandatoryAddons.forEach(addon => { - const addonRow = document.createElement('div'); - addonRow.className = 'd-flex justify-content-between mb-1 ps-3'; - addonRow.innerHTML = ` - ${addon.name} - CHF ${addon.price} - `; - this.addonPricingContainer.appendChild(addonRow); - }); - - // Add separator if there are also optional addons - if (selectedOptionalAddons && selectedOptionalAddons.length > 0) { - const separator = document.createElement('hr'); - separator.className = 'my-2'; - this.addonPricingContainer.appendChild(separator); - } - } - - // Add optional addons to pricing breakdown (these are added to total) - if (selectedOptionalAddons && selectedOptionalAddons.length > 0) { - selectedOptionalAddons.forEach(addon => { - const addonRow = document.createElement('div'); - addonRow.className = 'd-flex justify-content-between mb-2'; - addonRow.innerHTML = ` - Add-on: ${addon.name} - CHF ${addon.price} - `; - this.addonPricingContainer.appendChild(addonRow); - }); - } - } - - // Show no matching plan found - showNoMatch() { - if (this.planMatchStatus) this.planMatchStatus.style.display = 'none'; - if (this.selectedPlanDetails) this.selectedPlanDetails.style.display = 'none'; - if (this.noMatchFound) this.noMatchFound.style.display = 'block'; - } - - // Update status message - updateStatusMessage(message, type) { - if (!this.planMatchStatus) return; - - const iconClass = type === 'success' ? 'bi-check-circle' : 'bi-info-circle'; - const textClass = type === 'success' ? 'text-success' : ''; - const alertClass = type === 'success' ? 'alert-success' : 'alert-info'; - - this.planMatchStatus.innerHTML = `${message}`; - this.planMatchStatus.className = `alert ${alertClass} mb-3`; - this.planMatchStatus.style.display = 'block'; - } - - // Show error message - showError(message) { - if (this.planMatchStatus) { - this.planMatchStatus.innerHTML = `${message}`; - this.planMatchStatus.className = 'alert alert-danger mb-3'; - this.planMatchStatus.style.display = 'block'; - } - } - - // Fade out specified sliders when plan is manually selected - fadeOutSliders(sliderTypes) { - sliderTypes.forEach(type => { - const sliderContainer = this.getSliderContainer(type); - if (sliderContainer) { - sliderContainer.style.transition = 'opacity 0.3s ease-in-out'; - sliderContainer.style.opacity = '0.3'; - sliderContainer.style.pointerEvents = 'none'; - - // Add visual indicator that sliders are disabled - const slider = sliderContainer.querySelector('.form-range'); - if (slider) { - slider.style.cursor = 'not-allowed'; - } - } - }); - } - - // Fade in specified sliders when auto-select mode is chosen - fadeInSliders(sliderTypes) { - sliderTypes.forEach(type => { - const sliderContainer = this.getSliderContainer(type); - if (sliderContainer) { - sliderContainer.style.transition = 'opacity 0.3s ease-in-out'; - sliderContainer.style.opacity = '1'; - sliderContainer.style.pointerEvents = 'auto'; - - // Remove visual indicator - const slider = sliderContainer.querySelector('.form-range'); - if (slider) { - slider.style.cursor = 'pointer'; - } - } - }); - } - - // Get slider container element by type - getSliderContainer(type) { - switch (type) { - case 'cpu': - return this.cpuRange?.closest('.mb-4'); - case 'memory': - return this.memoryRange?.closest('.mb-4'); - case 'storage': - return this.storageRange?.closest('.mb-4'); - case 'instances': - return this.instancesRange?.closest('.mb-4'); - default: - return null; - } - } } // Initialize calculator when DOM is loaded @@ -1834,4 +990,45 @@ document.addEventListener('DOMContentLoaded', () => { if (document.getElementById('cpuRange')) { new PriceCalculator(); } +}); + +// New simple plan table population for multi-currency pricing + +document.addEventListener('DOMContentLoaded', function() { + const currencySelect = document.getElementById('currencySelect'); + const plansTableBody = document.querySelector('#plansTable tbody'); + if (!currencySelect || !plansTableBody) return; + + let allPlans = []; + + function fetchPlans() { + fetch(window.location.pathname + '?pricing=json') + .then(response => response.json()) + .then(data => { + allPlans = data.plans || []; + updateTable(); + }); + } + + function updateTable() { + const selectedCurrency = currencySelect.value; + plansTableBody.innerHTML = ''; + const filtered = allPlans.filter(plan => plan.currency === selectedCurrency); + if (filtered.length === 0) { + plansTableBody.innerHTML = 'No plans available in this currency.'; + return; + } + filtered.forEach(plan => { + const row = document.createElement('tr'); + row.innerHTML = ` + ${plan.plan_name} + ${plan.description || ''} + ${plan.amount.toFixed(2)} ${plan.currency} + `; + plansTableBody.appendChild(row); + }); + } + + currencySelect.addEventListener('change', updateTable); + fetchPlans(); }); \ No newline at end of file diff --git a/hub/services/templates/services/offering_detail.html b/hub/services/templates/services/offering_detail.html index 000d13d..8d97ada 100644 --- a/hub/services/templates/services/offering_detail.html +++ b/hub/services/templates/services/offering_detail.html @@ -204,199 +204,28 @@
{% if offering.msp == "VS" and price_calculator_enabled and pricing_data_by_group_and_service_level %} - -

Choose your Plan

-
-
- -
-
-
- -
- - -
- 1 - 32 -
-
- - -
- - -
- 1 GB - 128 GB -
-
- - -
- - -
- 10 GB - 1000 GB -
-
- - -
- - -
- 1 - 1 -
-
- - -
- -
- - - - - -
-
- - - - - -
- - -

Selecting a plan will override the slider configuration

-

Interested in a custom plan? Let us know via the contact form.

-
-
-
-
- - -
-
-
-
Your Plan
- - -
- - Finding best matching plan... -
- - - - - - -
-
-
-
+

Available Plans & Pricing

+
+ +
- - - - - -
-

Order Your Configuration

-
-
- {% embedded_contact_form source="Configuration Order" service=offering.service offering_id=offering.id %} -
-
+
+ + + + + + + + + + + +
Plan NameDescriptionPrice
{% elif offering.plans.all %} diff --git a/hub/services/views/offerings.py b/hub/services/views/offerings.py index e135aec..fe01c7c 100644 --- a/hub/services/views/offerings.py +++ b/hub/services/views/offerings.py @@ -242,221 +242,19 @@ def generate_exoscale_marketplace_yaml(offering): def generate_pricing_data(offering): - """Generate pricing data for a specific offering and cloud provider""" - # Fetch compute plans for this cloud provider - compute_plans = ( - ComputePlan.objects.filter(active=True, cloud_provider=offering.cloud_provider) - .select_related("cloud_provider", "group") - .prefetch_related("prices") - .order_by("group__order", "group__name") - ) + """Generate pricing data for a specific offering and its plans with multi-currency support""" + # Fetch all plans for this offering + plans = offering.plans.prefetch_related("plan_prices") - # Apply natural sorting for compute plan names - compute_plans = sorted( - compute_plans, - key=lambda x: ( - x.group.order if x.group else 999, - x.group.name if x.group else "ZZZ", - natural_sort_key(x.name), - ), - ) + pricing_data = [] + for plan in plans: + for plan_price in plan.plan_prices.all(): + pricing_data.append({ + "plan_id": plan.id, + "plan_name": plan.name, + "description": plan.description, + "currency": plan_price.currency, + "amount": float(plan_price.amount), + }) - # Fetch storage plans for this cloud provider - storage_plans = ( - StoragePlan.objects.filter(cloud_provider=offering.cloud_provider) - .prefetch_related("prices") - .order_by("name") - ) - - # Get default storage pricing (use first available storage plan) - storage_price_data = {} - if storage_plans.exists(): - default_storage_plan = storage_plans.first() - for currency in ["CHF", "EUR", "USD"]: # Add currencies as needed - price = default_storage_plan.get_price(currency) - if price is not None: - storage_price_data[currency] = price - - # Fetch pricing for this specific service - try: - appcat_price = ( - VSHNAppCatPrice.objects.select_related("service", "discount_model") - .prefetch_related("base_fees", "unit_rates", "discount_model__tiers") - .get(service=offering.service) - ) - except VSHNAppCatPrice.DoesNotExist: - return None - - pricing_data_by_group_and_service_level = defaultdict(lambda: defaultdict(list)) - processed_combinations = set() - - # Generate pricing combinations for each compute plan - for plan in compute_plans: - plan_currencies = set(plan.prices.values_list("currency", flat=True)) - - # 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() - - 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.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, service_level) - 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 - 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 - else: - sla_price = standard_sla_price - - # Get addons information - addons = appcat_price.addons.filter(active=True) - mandatory_addons = [] - optional_addons = [] - - # Calculate additional price from mandatory addons - addon_total = 0 - - for addon in addons: - addon_price = None - addon_price_per_unit = None - - if addon.addon_type == "BF": # Base Fee - addon_price = addon.get_price(currency, service_level) - elif addon.addon_type == "UR": # Unit Rate - addon_price_per_unit = addon.get_price(currency, service_level) - if addon_price_per_unit: - addon_price = addon_price_per_unit * total_units - - addon_info = { - "id": addon.id, - "name": addon.name, - "description": addon.description, - "commercial_description": addon.commercial_description, - "addon_type": addon.get_addon_type_display(), - "price": addon_price, - "price_per_unit": addon_price_per_unit, # Add per-unit price for frontend calculations - } - - if addon.mandatory: - mandatory_addons.append(addon_info) - if addon_price: - addon_total += addon_price - sla_price += addon_price - else: - optional_addons.append(addon_info) - - final_price = compute_plan_price + sla_price - service_level_display = dict(VSHNAppCatPrice.ServiceLevel.choices)[ - service_level - ] - - group_name = plan.group.name if plan.group else "No Group" - - # Add pricing data to the grouped structure - pricing_data_by_group_and_service_level[group_name][ - service_level_display - ].append( - { - "compute_plan": plan.name, - "compute_plan_group": group_name, - "compute_plan_group_description": ( - plan.group.description if plan.group else "" - ), - "vcpus": plan.vcpus, - "ram": plan.ram, - "currency": currency, - "compute_plan_price": compute_plan_price, - "sla_price": sla_price, - "final_price": final_price, - "storage_price": storage_price_data.get(currency, 0), - "ha_replica_min": appcat_price.ha_replica_min, - "ha_replica_max": appcat_price.ha_replica_max, - "variable_unit": appcat_price.variable_unit, - "units": units, - "total_units": total_units, - "mandatory_addons": mandatory_addons, - "optional_addons": optional_addons, - } - ) - - # Order groups correctly, placing "No Group" last - ordered_groups = {} - 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[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.items(): - final_context_data[group_key] = { - sl_key: list(plans_list) - for sl_key, plans_list in service_levels_dict.items() - } - - return final_context_data + return {"plans": pricing_data} From 3b8eea9c14ae9051d5e729dd99c3b99dde78159b Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Mon, 23 Jun 2025 10:00:19 +0200 Subject: [PATCH 02/60] model for classic plan pricing --- .../0037_remove_plan_pricing_planprice.py | 63 +++++++++++++++++++ hub/services/models/services.py | 37 ++++++++++- 2 files changed, 98 insertions(+), 2 deletions(-) create mode 100644 hub/services/migrations/0037_remove_plan_pricing_planprice.py diff --git a/hub/services/migrations/0037_remove_plan_pricing_planprice.py b/hub/services/migrations/0037_remove_plan_pricing_planprice.py new file mode 100644 index 0000000..5326161 --- /dev/null +++ b/hub/services/migrations/0037_remove_plan_pricing_planprice.py @@ -0,0 +1,63 @@ +# Generated by Django 5.2 on 2025-06-23 07:58 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ("services", "0036_alter_vshnappcataddonbasefee_options_and_more"), + ] + + operations = [ + migrations.RemoveField( + model_name="plan", + name="pricing", + ), + migrations.CreateModel( + name="PlanPrice", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "currency", + models.CharField( + choices=[ + ("CHF", "Swiss Franc"), + ("EUR", "Euro"), + ("USD", "US Dollar"), + ], + max_length=3, + ), + ), + ( + "amount", + models.DecimalField( + decimal_places=2, + help_text="Price in the specified currency, excl. VAT", + max_digits=10, + ), + ), + ( + "plan", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="plan_prices", + to="services.plan", + ), + ), + ], + options={ + "ordering": ["currency"], + "unique_together": {("plan", "currency")}, + }, + ), + ] diff --git a/hub/services/models/services.py b/hub/services/models/services.py index 5c155b8..e5b90cb 100644 --- a/hub/services/models/services.py +++ b/hub/services/models/services.py @@ -5,7 +5,13 @@ from django.urls import reverse from django.utils.text import slugify from django_prose_editor.fields import ProseEditorField -from .base import Category, ReusableText, ManagedServiceProvider, validate_image_size +from .base import ( + Category, + ReusableText, + ManagedServiceProvider, + validate_image_size, + Currency, +) from .providers import CloudProvider @@ -97,10 +103,31 @@ class ServiceOffering(models.Model): ) +class PlanPrice(models.Model): + plan = models.ForeignKey( + "Plan", on_delete=models.CASCADE, related_name="plan_prices" + ) + currency = models.CharField( + max_length=3, + choices=Currency.choices, + ) + amount = models.DecimalField( + max_digits=10, + decimal_places=2, + help_text="Price in the specified currency, excl. VAT", + ) + + class Meta: + unique_together = ("plan", "currency") + ordering = ["currency"] + + def __str__(self): + return f"{self.plan.name} - {self.amount} {self.currency}" + + class Plan(models.Model): name = models.CharField(max_length=100) description = ProseEditorField(blank=True, null=True) - pricing = ProseEditorField(blank=True, null=True) plan_description = models.ForeignKey( ReusableText, on_delete=models.PROTECT, @@ -122,6 +149,12 @@ class Plan(models.Model): def __str__(self): return f"{self.offering} - {self.name}" + def get_price(self, currency_code: str): + price_obj = PlanPrice.objects.filter(plan=self, currency=currency_code).first() + if price_obj: + return price_obj.amount + return None + class ExternalLinkOffering(models.Model): offering = models.ForeignKey( From 656b59904ca5591c5308fa6b6c64338f22f6d5a3 Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Mon, 23 Jun 2025 11:37:26 +0200 Subject: [PATCH 03/60] classic plan new styling --- .../templates/services/offering_detail.html | 137 +++++++++++++----- 1 file changed, 98 insertions(+), 39 deletions(-) diff --git a/hub/services/templates/services/offering_detail.html b/hub/services/templates/services/offering_detail.html index 000d13d..b5c946f 100644 --- a/hub/services/templates/services/offering_detail.html +++ b/hub/services/templates/services/offering_detail.html @@ -7,6 +7,26 @@ {% block extra_js %} + {% endblock %} {% block content %} @@ -400,40 +420,90 @@
{% elif offering.plans.all %} -

Available Plans

-
- {% for plan in offering.plans.all %} -
-
-
-

{{ plan.name }}

- {% if plan.plan_description %} -
- {{ plan.plan_description.text|safe }} +

Choose your Plan

+
+
+ {% for plan in offering.plans.all %} +
+
+
+
+ {{ plan.name }} +
+ + + {% if plan.plan_description %} +
+ Description +
+ {{ plan.plan_description.text|safe }} +
+
+ {% endif %} + + {% if plan.description %} +
+ Details +
+ {{ plan.description|safe }} +
+
+ {% endif %} + + + {% if plan.plan_prices.exists %} +
+
+ Pricing +
+ {% for price in plan.plan_prices.all %} +
+ Monthly Price + {{ price.currency }} {{ price.amount }} +
+ {% endfor %} + + + Prices exclude VAT. Monthly pricing based on 30 days. + +
+ {% else %} +
+
+ Contact us for pricing details +
+
+ {% endif %} + + +
- {% endif %} - {% if plan.description %} -
- {{ plan.description|safe }} -
- {% endif %} - {% if plan.pricing %} -
- {{ plan.pricing|safe }} -
- {% endif %}
+ {% empty %} +
+
+

No plans available yet.

+

I'm interested in this offering

+ {% embedded_contact_form source="Offering Interest" service=offering.service offering_id=offering.id %} +
+
+ {% endfor %}
- {% empty %} -
-
-

No plans available yet.

-

I'm interested in this offering

- {% embedded_contact_form source="Offering Interest" service=offering.service offering_id=offering.id %} +
+ + +
+

Order Your Plan

+
+
+ {% embedded_contact_form source="Plan Order" service=offering.service offering_id=offering.id choices=offering.plans.all choice_label="Select a Plan" %}
- {% endfor %}
{% else %} @@ -443,17 +513,6 @@ {% embedded_contact_form source="Offering Interest" service=offering.service offering_id=offering.id %}
{% endif %} - - {% if offering.plans.exists and not pricing_data_by_group_and_service_level %} -
-

I'm interested in a plan

-
-
- {% embedded_contact_form source="Plan Order" service=offering.service offering_id=offering.id choices=offering.plans.all choice_label="Select a Plan" %} -
-
-
- {% endif %}
From 9e0ccb6025eb4df3721c84487b8fb3465b4a7747 Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Mon, 23 Jun 2025 11:58:09 +0200 Subject: [PATCH 04/60] plan price admin --- hub/services/admin/services.py | 72 +++++++++++++++++++++++++++++++--- hub/settings.py | 2 + 2 files changed, 69 insertions(+), 5 deletions(-) diff --git a/hub/services/admin/services.py b/hub/services/admin/services.py index 44f848b..8d86c08 100644 --- a/hub/services/admin/services.py +++ b/hub/services/admin/services.py @@ -5,7 +5,14 @@ Admin classes for services and service offerings from django.contrib import admin from django.utils.html import format_html -from ..models import Service, ServiceOffering, ExternalLink, ExternalLinkOffering, Plan +from ..models import ( + Service, + ServiceOffering, + ExternalLink, + ExternalLinkOffering, + Plan, + PlanPrice, +) class ExternalLinkInline(admin.TabularInline): @@ -26,14 +33,22 @@ class ExternalLinkOfferingInline(admin.TabularInline): ordering = ("order", "description") +class PlanPriceInline(admin.TabularInline): + """Inline admin for PlanPrice model""" + + model = PlanPrice + extra = 1 + fields = ("currency", "amount") + ordering = ("currency",) + + class PlanInline(admin.StackedInline): """Inline admin for Plan model""" model = Plan extra = 1 - fieldsets = ( - (None, {"fields": ("name", "description", "pricing", "plan_description")}), - ) + fieldsets = ((None, {"fields": ("name", "description", "plan_description")}),) + show_change_link = True # This allows clicking through to the Plan admin where prices can be managed class OfferingInline(admin.StackedInline): @@ -102,7 +117,54 @@ class ServiceAdmin(admin.ModelAdmin): class ServiceOfferingAdmin(admin.ModelAdmin): """Admin configuration for ServiceOffering model""" - list_display = ("service", "cloud_provider") + list_display = ("service", "cloud_provider", "plan_count", "total_prices") list_filter = ("service", "cloud_provider") search_fields = ("service__name", "cloud_provider__name", "description") inlines = [ExternalLinkOfferingInline, PlanInline] + + def plan_count(self, obj): + """Display number of plans for this offering""" + return obj.plans.count() + + plan_count.short_description = "Plans" + + def total_prices(self, obj): + """Display total number of plan prices for this offering""" + total = sum(plan.plan_prices.count() for plan in obj.plans.all()) + return f"{total} prices" + + total_prices.short_description = "Total Prices" + + +@admin.register(Plan) +class PlanAdmin(admin.ModelAdmin): + """Admin configuration for Plan model""" + + list_display = ("name", "offering", "price_summary") + list_filter = ("offering__service", "offering__cloud_provider") + search_fields = ("name", "description", "offering__service__name") + inlines = [PlanPriceInline] + + def price_summary(self, obj): + """Display a summary of prices for this plan""" + prices = obj.plan_prices.all() + if prices: + price_strs = [f"{price.amount} {price.currency}" for price in prices] + return ", ".join(price_strs) + return "No prices set" + + price_summary.short_description = "Prices" + + +@admin.register(PlanPrice) +class PlanPriceAdmin(admin.ModelAdmin): + """Admin configuration for PlanPrice model""" + + list_display = ("plan", "currency", "amount") + list_filter = ( + "currency", + "plan__offering__service", + "plan__offering__cloud_provider", + ) + search_fields = ("plan__name", "plan__offering__service__name") + ordering = ("plan__offering__service__name", "plan__name", "currency") diff --git a/hub/settings.py b/hub/settings.py index 409b3d6..8e6f3e6 100644 --- a/hub/settings.py +++ b/hub/settings.py @@ -255,6 +255,8 @@ JAZZMIN_SETTINGS = { "services.ProgressiveDiscountModel": "single", "services.VSHNAppCatPrice": "single", "services.VSHNAppCatAddon": "single", + "services.ServiceOffering": "single", + "services.Plan": "single", }, "related_modal_active": True, } From c93f8de717a8b5548dba2cb6660198e7441235ea Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Mon, 23 Jun 2025 13:13:27 +0200 Subject: [PATCH 05/60] introduce plan ordering and marking as best --- hub/services/admin/services.py | 18 +++-- .../0038_add_plan_ordering_and_best.py | 32 ++++++++ hub/services/models/services.py | 28 ++++++- .../templates/services/offering_detail.html | 75 +++++++++++++++---- 4 files changed, 132 insertions(+), 21 deletions(-) create mode 100644 hub/services/migrations/0038_add_plan_ordering_and_best.py diff --git a/hub/services/admin/services.py b/hub/services/admin/services.py index 8d86c08..c975884 100644 --- a/hub/services/admin/services.py +++ b/hub/services/admin/services.py @@ -43,11 +43,14 @@ class PlanPriceInline(admin.TabularInline): class PlanInline(admin.StackedInline): - """Inline admin for Plan model""" + """Inline admin for Plan model with sortable ordering""" model = Plan extra = 1 - fieldsets = ((None, {"fields": ("name", "description", "plan_description")}),) + fieldsets = ( + (None, {"fields": ("name", "description", "plan_description")}), + ("Display Options", {"fields": ("is_best",)}), + ) show_change_link = True # This allows clicking through to the Plan admin where prices can be managed @@ -138,12 +141,17 @@ class ServiceOfferingAdmin(admin.ModelAdmin): @admin.register(Plan) class PlanAdmin(admin.ModelAdmin): - """Admin configuration for Plan model""" + """Admin configuration for Plan model with sortable ordering""" - list_display = ("name", "offering", "price_summary") - list_filter = ("offering__service", "offering__cloud_provider") + list_display = ("name", "offering", "is_best", "price_summary", "order") + list_filter = ("offering__service", "offering__cloud_provider", "is_best") search_fields = ("name", "description", "offering__service__name") + list_editable = ("is_best",) inlines = [PlanPriceInline] + fieldsets = ( + (None, {"fields": ("name", "offering", "description", "plan_description")}), + ("Display Options", {"fields": ("is_best", "order")}), + ) def price_summary(self, obj): """Display a summary of prices for this plan""" diff --git a/hub/services/migrations/0038_add_plan_ordering_and_best.py b/hub/services/migrations/0038_add_plan_ordering_and_best.py new file mode 100644 index 0000000..b02be24 --- /dev/null +++ b/hub/services/migrations/0038_add_plan_ordering_and_best.py @@ -0,0 +1,32 @@ +# Generated by Django 5.2 on 2025-06-23 10:34 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ("services", "0037_remove_plan_pricing_planprice"), + ] + + operations = [ + migrations.AlterModelOptions( + name="plan", + options={"ordering": ["order", "name"]}, + ), + migrations.AddField( + model_name="plan", + name="is_best", + field=models.BooleanField( + default=False, help_text="Mark this plan as the best/recommended option" + ), + ), + migrations.AddField( + model_name="plan", + name="order", + field=models.PositiveIntegerField( + default=0, + help_text="Order of this plan in the offering (lower numbers appear first)", + ), + ), + ] diff --git a/hub/services/models/services.py b/hub/services/models/services.py index e5b90cb..8b6984d 100644 --- a/hub/services/models/services.py +++ b/hub/services/models/services.py @@ -139,16 +139,42 @@ class Plan(models.Model): ServiceOffering, on_delete=models.CASCADE, related_name="plans" ) + # Ordering and highlighting fields + order = models.PositiveIntegerField( + default=0, + help_text="Order of this plan in the offering (lower numbers appear first)", + ) + is_best = models.BooleanField( + default=False, help_text="Mark this plan as the best/recommended option" + ) + created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: - ordering = ["name"] + ordering = ["order", "name"] unique_together = [["offering", "name"]] def __str__(self): return f"{self.offering} - {self.name}" + def clean(self): + # Ensure only one plan per offering can be marked as "best" + if self.is_best: + existing_best = Plan.objects.filter( + offering=self.offering, is_best=True + ).exclude(pk=self.pk) + if existing_best.exists(): + from django.core.exceptions import ValidationError + + raise ValidationError( + "Only one plan per offering can be marked as the best option." + ) + + def save(self, *args, **kwargs): + self.clean() + super().save(*args, **kwargs) + def get_price(self, currency_code: str): price_obj = PlanPrice.objects.filter(plan=self, currency=currency_code).first() if price_obj: diff --git a/hub/services/templates/services/offering_detail.html b/hub/services/templates/services/offering_detail.html index b5c946f..ee4f684 100644 --- a/hub/services/templates/services/offering_detail.html +++ b/hub/services/templates/services/offering_detail.html @@ -7,6 +7,39 @@ {% block extra_js %} + + + +{% json_ld_structured_data %} + - {% endblock %} {% block content %} diff --git a/hub/services/templatetags/json_ld_tags.py b/hub/services/templatetags/json_ld_tags.py index e95ba70..eb18007 100644 --- a/hub/services/templatetags/json_ld_tags.py +++ b/hub/services/templatetags/json_ld_tags.py @@ -225,19 +225,21 @@ def json_ld_structured_data(context): # Add offers if available if hasattr(offering, "plans") and offering.plans.exists(): # Get all plans with pricing - plans_with_prices = offering.plans.filter(plan_prices__isnull=False).distinct() - + plans_with_prices = offering.plans.filter( + plan_prices__isnull=False + ).distinct() + if plans_with_prices.exists(): # Create individual offers for each plan offers = [] all_prices = [] - + for plan in plans_with_prices: plan_prices = plan.plan_prices.all() if plan_prices.exists(): first_price = plan_prices.first() all_prices.extend([p.amount for p in plan_prices]) - + offer = { "@type": "Offer", "name": plan.name, @@ -245,25 +247,19 @@ def json_ld_structured_data(context): "priceCurrency": first_price.currency, "availability": "https://schema.org/InStock", "url": offering_url + "#plan-order-form", - "seller": { - "@type": "Organization", - "name": "VSHN" - } + "seller": {"@type": "Organization", "name": "VSHN"}, } offers.append(offer) - + # Add aggregate offer with all individual offers data["offers"] = { "@type": "AggregateOffer", "availability": "https://schema.org/InStock", "offerCount": len(offers), "offers": offers, - "seller": { - "@type": "Organization", - "name": "VSHN" - } + "seller": {"@type": "Organization", "name": "VSHN"}, } - + # Add lowPrice, highPrice and priceCurrency if we have prices if all_prices: data["offers"]["lowPrice"] = str(min(all_prices)) @@ -272,7 +268,7 @@ def json_ld_structured_data(context): first_plan_with_prices = plans_with_prices.first() first_currency = first_plan_with_prices.plan_prices.first().currency data["offers"]["priceCurrency"] = first_currency - + # Note: aggregateRating and review fields are not included as this is a B2B # service marketplace without a review system. These could be added in the future # if customer reviews/ratings are implemented. @@ -289,10 +285,7 @@ def json_ld_structured_data(context): "@type": "AggregateOffer", "availability": "https://schema.org/InStock", "offerCount": offering.plans.count(), - "seller": { - "@type": "Organization", - "name": "VSHN" - } + "seller": {"@type": "Organization", "name": "VSHN"}, } else: From 25d4164bae8f51821779131bb4e41a5f6f4cd40b Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Mon, 23 Jun 2025 14:22:33 +0200 Subject: [PATCH 09/60] only run tests on main and PRs --- .forgejo/workflows/test.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.forgejo/workflows/test.yaml b/.forgejo/workflows/test.yaml index a0cb310..1bc048c 100644 --- a/.forgejo/workflows/test.yaml +++ b/.forgejo/workflows/test.yaml @@ -2,7 +2,7 @@ name: Django Tests on: push: - branches: ["*"] + branches: [main] pull_request: jobs: @@ -31,4 +31,4 @@ jobs: -w /app \ -e SECRET_KEY=dummysecretkey \ website:test \ - sh -c 'uv run --extra dev manage.py migrate --noinput && uv run --extra dev manage.py test hub.services.tests --verbosity=2' \ No newline at end of file + sh -c 'uv run --extra dev manage.py migrate --noinput && uv run --extra dev manage.py test hub.services.tests --verbosity=2' From 0a3837d1e197c37062e5f16b94fbb1c251054932 Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Mon, 23 Jun 2025 14:22:52 +0200 Subject: [PATCH 10/60] set service level for test --- hub/services/tests/test_pricing_edge_cases.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/hub/services/tests/test_pricing_edge_cases.py b/hub/services/tests/test_pricing_edge_cases.py index 8a59104..0363ea8 100644 --- a/hub/services/tests/test_pricing_edge_cases.py +++ b/hub/services/tests/test_pricing_edge_cases.py @@ -1,6 +1,5 @@ from decimal import Decimal from django.test import TestCase -from django.core.exceptions import ValidationError from django.utils import timezone from datetime import timedelta @@ -10,16 +9,12 @@ from ..models.services import Service from ..models.pricing import ( ComputePlan, ComputePlanPrice, - StoragePlan, - StoragePlanPrice, ProgressiveDiscountModel, DiscountTier, VSHNAppCatPrice, VSHNAppCatBaseFee, VSHNAppCatUnitRate, VSHNAppCatAddon, - VSHNAppCatAddonBaseFee, - VSHNAppCatAddonUnitRate, ExternalPricePlans, ) @@ -163,7 +158,8 @@ class PricingEdgeCasesTestCase(TestCase): ) # Should return None when price doesn't exist - price = addon.get_price(Currency.CHF) + # For BASE_FEE addons, service_level is required + price = addon.get_price(Currency.CHF, service_level="standard") self.assertIsNone(price) def test_compute_plan_with_validity_dates(self): From 7bbde80913997d610c5c1eede7e2c75ff6f4092a Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Mon, 23 Jun 2025 16:42:28 +0200 Subject: [PATCH 11/60] show order in inline --- hub/services/admin/services.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hub/services/admin/services.py b/hub/services/admin/services.py index c975884..41bc97f 100644 --- a/hub/services/admin/services.py +++ b/hub/services/admin/services.py @@ -49,9 +49,9 @@ class PlanInline(admin.StackedInline): extra = 1 fieldsets = ( (None, {"fields": ("name", "description", "plan_description")}), - ("Display Options", {"fields": ("is_best",)}), + ("Display Options", {"fields": ("is_best", "order")}), ) - show_change_link = True # This allows clicking through to the Plan admin where prices can be managed + show_change_link = True class OfferingInline(admin.StackedInline): From 60de2e547a15cb5498c344f208f57df6388bb3cd Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Mon, 23 Jun 2025 16:47:30 +0200 Subject: [PATCH 12/60] wording and color improvements --- hub/services/static/css/price-calculator.css | 4 ++-- hub/services/templates/services/offering_detail.html | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/hub/services/static/css/price-calculator.css b/hub/services/static/css/price-calculator.css index 5efe5f6..a65d8cc 100644 --- a/hub/services/static/css/price-calculator.css +++ b/hub/services/static/css/price-calculator.css @@ -49,9 +49,9 @@ /* Best choice badge styling */ .badge.bg-success { - background: linear-gradient(135deg, #198754 0%, #20c997 100%) !important; border: 2px solid white; - text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); + text-shadow: 0 1px 2px rgba(0, 0, 0, 0.151); + color: rgb(255, 255, 255); white-space: nowrap; font-size: 0.75rem; padding: 0.5rem 0.75rem; diff --git a/hub/services/templates/services/offering_detail.html b/hub/services/templates/services/offering_detail.html index 7263024..e6682e3 100644 --- a/hub/services/templates/services/offering_detail.html +++ b/hub/services/templates/services/offering_detail.html @@ -473,7 +473,7 @@
From 470887c34ecda51f49d937d9330faf0fd88d8ecb Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Fri, 27 Jun 2025 15:18:03 +0200 Subject: [PATCH 13/60] exoscale marketplace listing tweaks --- hub/services/views/offerings.py | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/hub/services/views/offerings.py b/hub/services/views/offerings.py index e135aec..4016857 100644 --- a/hub/services/views/offerings.py +++ b/hub/services/views/offerings.py @@ -173,15 +173,28 @@ def generate_exoscale_marketplace_yaml(offering): ).strip() # Build YAML structure + service_name = offering.service.name + + # List of service names that should have "Enterprise" appended + # This concerns all services which are already available on Exoscale Marketplace or DBaaS for differentiation + # A workaround because we don't particularly have "Enterprise" services yet + enterprise_services = ["GitLab", "PostgreSQL"] + + if any( + enterprise_service in service_name for enterprise_service in enterprise_services + ): + service_name += " Enterprise" + + title = f"{service_name} by Servala" yaml_structure = { yaml_key: { "page_class": "tmpl-marketplace-product", - "html_title": f"Managed {offering.service.name} by VSHN via Servala", - "meta_desc": "Servala is the Open Cloud Native Service Hub. It connects businesses, developers, and cloud service providers on one unique hub with secure, scalable, and easy-to-use cloud-native services.", - "page_header_title": f"Managed {offering.service.name} by VSHN via Servala", + "html_title": title, + "meta_desc": f"Managed {offering.service.name} by Servala - a product by VSHN. Servala is the Open Cloud Native Service Hub. It connects businesses, developers, and cloud service providers on one unique hub with secure, scalable, and easy-to-use cloud-native services.", + "page_header_title": title, "provider_key": "vshn", - "slug": f"servala-managed-{offering.service.slug}", - "title": f"Managed {offering.service.name} by VSHN via Servala", + "slug": f"{offering.service.slug}-by-servala", + "title": title, "logo": f"img/servala-{offering.service.slug}.svg", "list_display": [], "meta": [ From 6351da70ee3e6d0946d0c28c72a310ef6a0727f0 Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Fri, 4 Jul 2025 15:51:44 +0200 Subject: [PATCH 14/60] add article date field --- hub/services/admin/articles.py | 5 ++-- .../migrations/0039_article_article_date.py | 22 +++++++++++++++++ hub/services/models/articles.py | 4 ++++ .../templates/services/article_detail.html | 4 +--- .../templates/services/article_list.html | 2 +- hub/services/views/articles.py | 24 +++++++++---------- 6 files changed, 42 insertions(+), 19 deletions(-) create mode 100644 hub/services/migrations/0039_article_article_date.py diff --git a/hub/services/admin/articles.py b/hub/services/admin/articles.py index e6dad8c..90298a4 100644 --- a/hub/services/admin/articles.py +++ b/hub/services/admin/articles.py @@ -45,7 +45,7 @@ class ArticleAdmin(admin.ModelAdmin): "image_preview", "is_published", "is_featured", - "created_at", + "article_date", ) list_filter = ( "is_published", @@ -54,11 +54,12 @@ class ArticleAdmin(admin.ModelAdmin): "related_service", "related_consulting_partner", "related_cloud_provider", - "created_at", + "article_date", ) search_fields = ("title", "excerpt", "content", "meta_keywords") prepopulated_fields = {"slug": ("title",)} readonly_fields = ("created_at", "updated_at") + ordering = ("-article_date",) def image_preview(self, obj): """Display image preview in admin list view""" diff --git a/hub/services/migrations/0039_article_article_date.py b/hub/services/migrations/0039_article_article_date.py new file mode 100644 index 0000000..69acc86 --- /dev/null +++ b/hub/services/migrations/0039_article_article_date.py @@ -0,0 +1,22 @@ +# Generated by Django 5.2 on 2025-07-04 13:48 + +import django.utils.timezone +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ("services", "0038_add_plan_ordering_and_best"), + ] + + operations = [ + migrations.AddField( + model_name="article", + name="article_date", + field=models.DateField( + default=django.utils.timezone.now, + help_text="Date of the article publishing", + ), + ), + ] diff --git a/hub/services/models/articles.py b/hub/services/models/articles.py index 781c54c..b1b85e7 100644 --- a/hub/services/models/articles.py +++ b/hub/services/models/articles.py @@ -3,6 +3,7 @@ from django.urls import reverse from django.utils.text import slugify from django.contrib.auth.models import User from django_prose_editor.fields import ProseEditorField +from django.utils import timezone from .base import validate_image_size from .services import Service from .providers import CloudProvider, ConsultingPartner @@ -23,6 +24,9 @@ class Article(models.Model): help_text="Title picture for the article", ) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="articles") + article_date = models.DateField( + default=timezone.now, help_text="Date of the article publishing" + ) # Relations to other models related_service = models.ForeignKey( diff --git a/hub/services/templates/services/article_detail.html b/hub/services/templates/services/article_detail.html index 44af754..9721513 100644 --- a/hub/services/templates/services/article_detail.html +++ b/hub/services/templates/services/article_detail.html @@ -16,9 +16,7 @@
By {{ article.author.get_full_name|default:article.author.username }} • - {{ article.created_at|date:"M d, Y" }} - {% if article.updated_at != article.created_at %} - {% endif %} + {{ article.article_date|date:"M d, Y" }}
diff --git a/hub/services/templates/services/article_list.html b/hub/services/templates/services/article_list.html index edb0989..ac86df4 100644 --- a/hub/services/templates/services/article_list.html +++ b/hub/services/templates/services/article_list.html @@ -169,7 +169,7 @@ By {{ article.author.get_full_name|default:article.author.username }} - {{ article.created_at|date:"M d, Y" }} + {{ article.article_date|date:"M d, Y" }}

diff --git a/hub/services/views/articles.py b/hub/services/views/articles.py index 6589d6f..4b8117f 100644 --- a/hub/services/views/articles.py +++ b/hub/services/views/articles.py @@ -23,7 +23,7 @@ def article_list(request): # Apply filters based on request parameters if search_query: articles = articles.filter( - Q(title__icontains=search_query) + Q(title__icontains=search_query) | Q(excerpt__icontains=search_query) | Q(content__icontains=search_query) | Q(meta_keywords__icontains=search_query) @@ -41,7 +41,7 @@ def article_list(request): # Order articles: featured first, then by creation date (newest first) articles = articles.order_by( "-is_featured", # Featured first (True before False) - "-created_at", # Newest first + "-article_date", # Newest first ) # Create base querysets for each filter type that apply all OTHER current filters @@ -51,7 +51,7 @@ def article_list(request): service_filter_base = all_articles if search_query: service_filter_base = service_filter_base.filter( - Q(title__icontains=search_query) + Q(title__icontains=search_query) | Q(excerpt__icontains=search_query) | Q(content__icontains=search_query) | Q(meta_keywords__icontains=search_query) @@ -69,7 +69,7 @@ def article_list(request): cp_filter_base = all_articles if search_query: cp_filter_base = cp_filter_base.filter( - Q(title__icontains=search_query) + Q(title__icontains=search_query) | Q(excerpt__icontains=search_query) | Q(content__icontains=search_query) | Q(meta_keywords__icontains=search_query) @@ -85,7 +85,7 @@ def article_list(request): cloud_filter_base = all_articles if search_query: cloud_filter_base = cloud_filter_base.filter( - Q(title__icontains=search_query) + Q(title__icontains=search_query) | Q(excerpt__icontains=search_query) | Q(content__icontains=search_query) | Q(meta_keywords__icontains=search_query) @@ -136,16 +136,14 @@ def article_detail(request, slug): Article.objects.select_related( "author", "related_service", - "related_consulting_partner", - "related_cloud_provider" + "related_consulting_partner", + "related_cloud_provider", ).filter(is_published=True), slug=slug, ) # Get related articles (same service, partner, or provider) - related_articles = Article.objects.filter( - is_published=True - ).exclude(id=article.id) + related_articles = Article.objects.filter(is_published=True).exclude(id=article.id) if article.related_service: related_articles = related_articles.filter( @@ -164,13 +162,13 @@ def article_detail(request, slug): related_articles = related_articles.filter( related_service__isnull=True, related_consulting_partner__isnull=True, - related_cloud_provider__isnull=True + related_cloud_provider__isnull=True, ) - related_articles = related_articles.order_by("-created_at")[:3] + related_articles = related_articles.order_by("-article_date")[:3] context = { "article": article, "related_articles": related_articles, } - return render(request, "services/article_detail.html", context) \ No newline at end of file + return render(request, "services/article_detail.html", context) From bdf06863d2fcd39fe57534a4ee36c3849e401690 Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Fri, 4 Jul 2025 15:53:00 +0200 Subject: [PATCH 15/60] do not show header image in article detail view --- hub/services/templates/services/article_detail.html | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/hub/services/templates/services/article_detail.html b/hub/services/templates/services/article_detail.html index 9721513..b3264e5 100644 --- a/hub/services/templates/services/article_detail.html +++ b/hub/services/templates/services/article_detail.html @@ -23,16 +23,6 @@
-{% if article.image %} -
-
-
- {{ article.title }} -
-
-
-{% endif %} -
From 52dbe895825af65ca9d9ff31e1d08c96cfeba400 Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Fri, 4 Jul 2025 16:28:13 +0200 Subject: [PATCH 16/60] image library created using VS Codey Copilot Agent with Claude Sonnet 4 --- hub/services/admin/__init__.py | 1 + hub/services/admin/images.py | 115 +++++++ hub/services/forms/image_library.py | 149 +++++++++ hub/services/management/__init__.py | 0 hub/services/management/commands/__init__.py | 0 .../management/commands/migrate_images.py | 293 ++++++++++++++++++ .../migrations/0040_add_image_library.py | 144 +++++++++ hub/services/models/__init__.py | 1 + hub/services/models/base.py | 6 +- hub/services/models/images.py | 224 +++++++++++++ .../static/admin/css/image_library.css | 79 +++++ hub/services/templatetags/image_library.py | 112 +++++++ hub/services/utils/image_library.py | 243 +++++++++++++++ hub/settings.py | 2 + 14 files changed, 1366 insertions(+), 3 deletions(-) create mode 100644 hub/services/admin/images.py create mode 100644 hub/services/forms/image_library.py create mode 100644 hub/services/management/__init__.py create mode 100644 hub/services/management/commands/__init__.py create mode 100644 hub/services/management/commands/migrate_images.py create mode 100644 hub/services/migrations/0040_add_image_library.py create mode 100644 hub/services/models/images.py create mode 100644 hub/services/static/admin/css/image_library.css create mode 100644 hub/services/templatetags/image_library.py create mode 100644 hub/services/utils/image_library.py diff --git a/hub/services/admin/__init__.py b/hub/services/admin/__init__.py index 3c79092..fba7be9 100644 --- a/hub/services/admin/__init__.py +++ b/hub/services/admin/__init__.py @@ -4,6 +4,7 @@ from .articles import * from .base import * from .content import * +from .images import * from .leads import * from .pricing import * from .providers import * diff --git a/hub/services/admin/images.py b/hub/services/admin/images.py new file mode 100644 index 0000000..917d0db --- /dev/null +++ b/hub/services/admin/images.py @@ -0,0 +1,115 @@ +from django.contrib import admin +from django.utils.html import format_html +from django.urls import reverse +from django.utils.safestring import mark_safe +from ..models.images import ImageLibrary + + +@admin.register(ImageLibrary) +class ImageLibraryAdmin(admin.ModelAdmin): + """ + Admin interface for the Image Library. + """ + + list_display = [ + "image_thumbnail", + "name", + "category", + "get_dimensions", + "get_file_size_display", + "usage_count", + "uploaded_by", + "uploaded_at", + ] + + list_filter = [ + "category", + "uploaded_at", + "uploaded_by", + ] + + search_fields = [ + "name", + "description", + "alt_text", + "tags", + ] + + readonly_fields = [ + "width", + "height", + "file_size", + "usage_count", + "uploaded_at", + "updated_at", + "image_preview", + ] + + prepopulated_fields = {"slug": ("name",)} + + fieldsets = ( + ("Image Information", {"fields": ("name", "slug", "description", "alt_text")}), + ("Image File", {"fields": ("image", "image_preview")}), + ("Categorization", {"fields": ("category", "tags")}), + ( + "Metadata", + { + "fields": ("width", "height", "file_size", "usage_count"), + "classes": ("collapse",), + }, + ), + ( + "Timestamps", + { + "fields": ("uploaded_by", "uploaded_at", "updated_at"), + "classes": ("collapse",), + }, + ), + ) + + def image_thumbnail(self, obj): + """ + Display small thumbnail in list view. + """ + if obj.image: + return format_html( + '', + obj.image.url, + ) + return "No Image" + + image_thumbnail.short_description = "Thumbnail" + + def image_preview(self, obj): + """ + Display larger preview in detail view. + """ + if obj.image: + return format_html( + '', + obj.image.url, + ) + return "No Image" + + image_preview.short_description = "Preview" + + def get_dimensions(self, obj): + """ + Display image dimensions. + """ + if obj.width and obj.height: + return f"{obj.width} × {obj.height}" + return "Unknown" + + get_dimensions.short_description = "Dimensions" + + def save_model(self, request, obj, form, change): + """ + Set uploaded_by field to current user if not already set. + """ + if not change: # Only set on creation + obj.uploaded_by = request.user + super().save_model(request, obj, form, change) + + class Media: + css = {"all": ("admin/css/image_library.css",)} diff --git a/hub/services/forms/image_library.py b/hub/services/forms/image_library.py new file mode 100644 index 0000000..1770456 --- /dev/null +++ b/hub/services/forms/image_library.py @@ -0,0 +1,149 @@ +from django import forms +from django.utils.safestring import mark_safe +from django.utils.html import format_html +from django.urls import reverse +from ..models.images import ImageLibrary + + +class ImageLibraryWidget(forms.Select): + """ + Custom widget for selecting images from the library with thumbnails. + """ + + def __init__(self, attrs=None, choices=(), show_thumbnails=True): + self.show_thumbnails = show_thumbnails + super().__init__(attrs, choices) + + def format_value(self, value): + """ + Format the selected value for display. + """ + if value is None: + return "" + return str(value) + + def render(self, name, value, attrs=None, renderer=None): + """ + Render the widget with thumbnails. + """ + if attrs is None: + attrs = {} + + # Add CSS class for styling + attrs["class"] = attrs.get("class", "") + " image-library-select" + + # Get all images for the select options + images = ImageLibrary.objects.all().order_by("name") + + # Build choices with thumbnails + choices = [("", "--- Select an image ---")] + for image in images: + thumbnail_html = "" + if self.show_thumbnails and image.image: + thumbnail_html = format_html( + ' ', + image.image.url, + ) + + choice_text = ( + f"{image.name} ({image.get_category_display()}){thumbnail_html}" + ) + choices.append((image.pk, choice_text)) + + # Build the select element + select_html = format_html( + '', + name, + attrs.get("id", ""), + self._build_attrs_string(attrs), + self._build_options(choices, value), + ) + + # Add preview area + preview_html = "" + if value: + try: + image = ImageLibrary.objects.get(pk=value) + preview_html = format_html( + '
' + '' + '

{} - {}x{} - {}

' + "
", + image.image.url, + image.name, + image.width or "?", + image.height or "?", + image.get_file_size_display(), + ) + except ImageLibrary.DoesNotExist: + pass + + # Add JavaScript for preview updates + js_html = format_html( + "", + attrs.get("id", ""), + ) + + return mark_safe(select_html + preview_html + js_html) + + def _build_attrs_string(self, attrs): + """ + Build HTML attributes string. + """ + attr_parts = [] + for key, value in attrs.items(): + if key != "id": # id is handled separately + attr_parts.append(f'{key}="{value}"') + return " " + " ".join(attr_parts) if attr_parts else "" + + def _build_options(self, choices, selected_value): + """ + Build option elements for the select. + """ + options = [] + for value, text in choices: + selected = "selected" if str(value) == str(selected_value) else "" + options.append(f'') + return "".join(options) + + +class ImageLibraryField(forms.ModelChoiceField): + """ + Custom form field for selecting images from the library. + """ + + def __init__(self, queryset=None, widget=None, show_thumbnails=True, **kwargs): + if queryset is None: + queryset = ImageLibrary.objects.all() + + if widget is None: + widget = ImageLibraryWidget(show_thumbnails=show_thumbnails) + + super().__init__(queryset=queryset, widget=widget, **kwargs) + + def label_from_instance(self, obj): + """ + Return the label for an image instance. + """ + return f"{obj.name} ({obj.get_category_display()})" diff --git a/hub/services/management/__init__.py b/hub/services/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/hub/services/management/commands/__init__.py b/hub/services/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/hub/services/management/commands/migrate_images.py b/hub/services/management/commands/migrate_images.py new file mode 100644 index 0000000..ca90dcb --- /dev/null +++ b/hub/services/management/commands/migrate_images.py @@ -0,0 +1,293 @@ +from django.core.management.base import BaseCommand +from django.core.files.base import ContentFile +from django.utils.text import slugify +from hub.services.models import ( + ImageLibrary, + Service, + CloudProvider, + ConsultingPartner, + Article, +) +import os +import shutil + + +class Command(BaseCommand): + help = "Migrate existing images to the Image Library" + + def add_arguments(self, parser): + parser.add_argument( + "--dry-run", + action="store_true", + help="Show what would be migrated without actually doing it", + ) + parser.add_argument( + "--force", + action="store_true", + help="Force migration even if images already exist in library", + ) + + def handle(self, *args, **options): + """ + Main command handler to migrate existing images to the library. + """ + dry_run = options["dry_run"] + force = options["force"] + + self.stdout.write( + self.style.SUCCESS( + f'Starting image migration {"(DRY RUN)" if dry_run else ""}' + ) + ) + + # Migrate different types of images + self.migrate_service_logos(dry_run, force) + self.migrate_cloud_provider_logos(dry_run, force) + self.migrate_partner_logos(dry_run, force) + self.migrate_article_images(dry_run, force) + + self.stdout.write( + self.style.SUCCESS( + f'Image migration completed {"(DRY RUN)" if dry_run else ""}' + ) + ) + + def migrate_service_logos(self, dry_run, force): + """ + Migrate service logos to the image library. + """ + self.stdout.write("Migrating service logos...") + + services = Service.objects.filter(logo__isnull=False).exclude(logo="") + + for service in services: + if not service.logo: + continue + + # Check if image already exists in library + existing_image = ImageLibrary.objects.filter( + name=f"{service.name} Logo" + ).first() + + if existing_image and not force: + self.stdout.write( + self.style.WARNING( + f" - Skipping {service.name} logo (already exists)" + ) + ) + continue + + if dry_run: + self.stdout.write( + self.style.SUCCESS(f" - Would migrate: {service.name} logo") + ) + continue + + # Create image library entry + image_lib = ImageLibrary( + name=f"{service.name} Logo", + slug=slugify(f"{service.name}-logo"), + description=f"Logo for {service.name} service", + alt_text=f"{service.name} logo", + category="logo", + tags=f"service, logo, {service.name.lower()}", + ) + + # Copy the image file + if service.logo and os.path.exists(service.logo.path): + with open(service.logo.path, "rb") as f: + image_lib.image.save( + os.path.basename(service.logo.name), + ContentFile(f.read()), + save=True, + ) + + self.stdout.write( + self.style.SUCCESS(f" - Migrated: {service.name} logo") + ) + else: + self.stdout.write( + self.style.ERROR( + f" - Failed to migrate: {service.name} logo (file not found)" + ) + ) + + def migrate_cloud_provider_logos(self, dry_run, force): + """ + Migrate cloud provider logos to the image library. + """ + self.stdout.write("Migrating cloud provider logos...") + + providers = CloudProvider.objects.filter(logo__isnull=False).exclude(logo="") + + for provider in providers: + if not provider.logo: + continue + + # Check if image already exists in library + existing_image = ImageLibrary.objects.filter( + name=f"{provider.name} Logo" + ).first() + + if existing_image and not force: + self.stdout.write( + self.style.WARNING( + f" - Skipping {provider.name} logo (already exists)" + ) + ) + continue + + if dry_run: + self.stdout.write( + self.style.SUCCESS(f" - Would migrate: {provider.name} logo") + ) + continue + + # Create image library entry + image_lib = ImageLibrary( + name=f"{provider.name} Logo", + slug=slugify(f"{provider.name}-logo"), + description=f"Logo for {provider.name} cloud provider", + alt_text=f"{provider.name} logo", + category="logo", + tags=f"cloud, provider, logo, {provider.name.lower()}", + ) + + # Copy the image file + if provider.logo and os.path.exists(provider.logo.path): + with open(provider.logo.path, "rb") as f: + image_lib.image.save( + os.path.basename(provider.logo.name), + ContentFile(f.read()), + save=True, + ) + + self.stdout.write( + self.style.SUCCESS(f" - Migrated: {provider.name} logo") + ) + else: + self.stdout.write( + self.style.ERROR( + f" - Failed to migrate: {provider.name} logo (file not found)" + ) + ) + + def migrate_partner_logos(self, dry_run, force): + """ + Migrate consulting partner logos to the image library. + """ + self.stdout.write("Migrating consulting partner logos...") + + partners = ConsultingPartner.objects.filter(logo__isnull=False).exclude(logo="") + + for partner in partners: + if not partner.logo: + continue + + # Check if image already exists in library + existing_image = ImageLibrary.objects.filter( + name=f"{partner.name} Logo" + ).first() + + if existing_image and not force: + self.stdout.write( + self.style.WARNING( + f" - Skipping {partner.name} logo (already exists)" + ) + ) + continue + + if dry_run: + self.stdout.write( + self.style.SUCCESS(f" - Would migrate: {partner.name} logo") + ) + continue + + # Create image library entry + image_lib = ImageLibrary( + name=f"{partner.name} Logo", + slug=slugify(f"{partner.name}-logo"), + description=f"Logo for {partner.name} consulting partner", + alt_text=f"{partner.name} logo", + category="logo", + tags=f"consulting, partner, logo, {partner.name.lower()}", + ) + + # Copy the image file + if partner.logo and os.path.exists(partner.logo.path): + with open(partner.logo.path, "rb") as f: + image_lib.image.save( + os.path.basename(partner.logo.name), + ContentFile(f.read()), + save=True, + ) + + self.stdout.write( + self.style.SUCCESS(f" - Migrated: {partner.name} logo") + ) + else: + self.stdout.write( + self.style.ERROR( + f" - Failed to migrate: {partner.name} logo (file not found)" + ) + ) + + def migrate_article_images(self, dry_run, force): + """ + Migrate article images to the image library. + """ + self.stdout.write("Migrating article images...") + + articles = Article.objects.filter(image__isnull=False).exclude(image="") + + for article in articles: + if not article.image: + continue + + # Check if image already exists in library + existing_image = ImageLibrary.objects.filter( + name=f"{article.title} Image" + ).first() + + if existing_image and not force: + self.stdout.write( + self.style.WARNING( + f" - Skipping {article.title} image (already exists)" + ) + ) + continue + + if dry_run: + self.stdout.write( + self.style.SUCCESS(f" - Would migrate: {article.title} image") + ) + continue + + # Create image library entry + image_lib = ImageLibrary( + name=f"{article.title} Image", + slug=slugify(f"{article.title}-image"), + description=f"Feature image for article: {article.title}", + alt_text=f"{article.title} feature image", + category="article", + tags=f"article, {article.title.lower()}", + ) + + # Copy the image file + if article.image and os.path.exists(article.image.path): + with open(article.image.path, "rb") as f: + image_lib.image.save( + os.path.basename(article.image.name), + ContentFile(f.read()), + save=True, + ) + + self.stdout.write( + self.style.SUCCESS(f" - Migrated: {article.title} image") + ) + else: + self.stdout.write( + self.style.ERROR( + f" - Failed to migrate: {article.title} image (file not found)" + ) + ) diff --git a/hub/services/migrations/0040_add_image_library.py b/hub/services/migrations/0040_add_image_library.py new file mode 100644 index 0000000..bc06e33 --- /dev/null +++ b/hub/services/migrations/0040_add_image_library.py @@ -0,0 +1,144 @@ +# Generated by Django 5.2 on 2025-07-04 14:19 + +import django.db.models.deletion +import hub.services.models.base +import hub.services.models.images +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ("services", "0039_article_article_date"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name="ImageLibrary", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "name", + models.CharField( + help_text="Descriptive name for the image", max_length=200 + ), + ), + ( + "slug", + models.SlugField( + help_text="URL-friendly version of the name", + max_length=250, + unique=True, + ), + ), + ( + "description", + models.TextField( + blank=True, help_text="Optional description of the image" + ), + ), + ( + "alt_text", + models.CharField( + help_text="Alternative text for accessibility", max_length=255 + ), + ), + ( + "image", + models.ImageField( + help_text="Upload image file (max 1MB)", + upload_to=hub.services.models.images.get_image_upload_path, + validators=[hub.services.models.base.validate_image_size], + ), + ), + ( + "width", + models.PositiveIntegerField( + blank=True, help_text="Image width in pixels", null=True + ), + ), + ( + "height", + models.PositiveIntegerField( + blank=True, help_text="Image height in pixels", null=True + ), + ), + ( + "file_size", + models.PositiveIntegerField( + blank=True, help_text="File size in bytes", null=True + ), + ), + ( + "category", + models.CharField( + choices=[ + ("logo", "Logo"), + ("article", "Article Image"), + ("banner", "Banner"), + ("icon", "Icon"), + ("screenshot", "Screenshot"), + ("photo", "Photo"), + ("other", "Other"), + ], + default="other", + help_text="Category of the image", + max_length=20, + ), + ), + ( + "tags", + models.CharField( + blank=True, + help_text="Comma-separated tags for searching", + max_length=500, + ), + ), + ( + "uploaded_at", + models.DateTimeField( + auto_now_add=True, + help_text="Date and time when image was uploaded", + ), + ), + ( + "updated_at", + models.DateTimeField( + auto_now=True, + help_text="Date and time when image was last updated", + ), + ), + ( + "usage_count", + models.PositiveIntegerField( + default=0, help_text="Number of times this image is referenced" + ), + ), + ( + "uploaded_by", + models.ForeignKey( + blank=True, + help_text="User who uploaded the image", + null=True, + on_delete=django.db.models.deletion.SET_NULL, + to=settings.AUTH_USER_MODEL, + ), + ), + ], + options={ + "verbose_name": "Image", + "verbose_name_plural": "Image Library", + "ordering": ["-uploaded_at"], + }, + ), + ] diff --git a/hub/services/models/__init__.py b/hub/services/models/__init__.py index b29a71e..68159a4 100644 --- a/hub/services/models/__init__.py +++ b/hub/services/models/__init__.py @@ -1,6 +1,7 @@ from .articles import * from .base import * from .content import * +from .images import * from .leads import * from .pricing import * from .providers import * diff --git a/hub/services/models/base.py b/hub/services/models/base.py index 9a7abce..a047330 100644 --- a/hub/services/models/base.py +++ b/hub/services/models/base.py @@ -4,10 +4,10 @@ from django.utils.text import slugify from django_prose_editor.fields import ProseEditorField -def validate_image_size(value): +def validate_image_size(value, mb=1): filesize = value.size - if filesize > 1 * 1024 * 1024: # 1MB - raise ValidationError("Maximum file size is 1MB") + if filesize > mb * 1024 * 1024: + raise ValidationError(f"Maximum file size is {mb} MB") class Currency(models.TextChoices): diff --git a/hub/services/models/images.py b/hub/services/models/images.py new file mode 100644 index 0000000..90052ab --- /dev/null +++ b/hub/services/models/images.py @@ -0,0 +1,224 @@ +import os + +from django.db import models +from django.utils import timezone +from django.contrib.auth.models import User +from django.core.exceptions import ValidationError +from django.utils.text import slugify +from PIL import Image as PILImage +from .base import validate_image_size + + +def get_image_upload_path(instance, filename): + """ + Generate upload path for images based on the image library structure. + """ + return f"image_library/{filename}" + + +class ImageLibrary(models.Model): + """ + Generic image library model that can be referenced by other models + to avoid duplicate uploads and provide centralized image management. + """ + + # Image metadata + name = models.CharField(max_length=200, help_text="Descriptive name for the image") + slug = models.SlugField( + max_length=250, unique=True, help_text="URL-friendly version of the name" + ) + description = models.TextField( + blank=True, help_text="Optional description of the image" + ) + alt_text = models.CharField( + max_length=255, help_text="Alternative text for accessibility" + ) + + # Image file + image = models.ImageField( + upload_to=get_image_upload_path, + validators=[validate_image_size], + help_text="Upload image file (max 1MB)", + ) + + # Image properties (automatically populated) + width = models.PositiveIntegerField( + null=True, blank=True, help_text="Image width in pixels" + ) + height = models.PositiveIntegerField( + null=True, blank=True, help_text="Image height in pixels" + ) + file_size = models.PositiveIntegerField( + null=True, blank=True, help_text="File size in bytes" + ) + + # Categorization + CATEGORY_CHOICES = [ + ("logo", "Logo"), + ("article", "Article Image"), + ("banner", "Banner"), + ("icon", "Icon"), + ("screenshot", "Screenshot"), + ("photo", "Photo"), + ("other", "Other"), + ] + category = models.CharField( + max_length=20, + choices=CATEGORY_CHOICES, + default="other", + help_text="Category of the image", + ) + + # Tags for easier searching + tags = models.CharField( + max_length=500, blank=True, help_text="Comma-separated tags for searching" + ) + + # Metadata + uploaded_by = models.ForeignKey( + User, + on_delete=models.SET_NULL, + null=True, + blank=True, + help_text="User who uploaded the image", + ) + uploaded_at = models.DateTimeField( + auto_now_add=True, help_text="Date and time when image was uploaded" + ) + updated_at = models.DateTimeField( + auto_now=True, help_text="Date and time when image was last updated" + ) + + # Usage tracking + usage_count = models.PositiveIntegerField( + default=0, help_text="Number of times this image is referenced" + ) + + class Meta: + ordering = ["-uploaded_at"] + verbose_name = "Image" + verbose_name_plural = "Image Library" + + def __str__(self): + return self.name + + def save(self, *args, **kwargs): + """ + Override save to automatically populate image properties and slug. + """ + # Generate slug if not provided + if not self.slug: + self.slug = slugify(self.name) + + # Save the model first to get the image file + super().save(*args, **kwargs) + + # Update image properties if image exists + if self.image: + self._update_image_properties() + + def _update_image_properties(self): + """ + Update image properties like width, height, and file size. + """ + try: + # Get image dimensions + with PILImage.open(self.image.path) as img: + self.width = img.width + self.height = img.height + + # Get file size + self.file_size = self.image.size + + # Save without calling the full save method to avoid recursion + ImageLibrary.objects.filter(pk=self.pk).update( + width=self.width, height=self.height, file_size=self.file_size + ) + except Exception as e: + # Log error but don't fail the save + print(f"Error updating image properties: {e}") + + def get_file_size_display(self): + """ + Return human-readable file size. + """ + if not self.file_size: + return "Unknown" + + size = self.file_size + for unit in ["B", "KB", "MB", "GB"]: + if size < 1024.0: + return f"{size:.1f} {unit}" + size /= 1024.0 + return f"{size:.1f} TB" + + def get_tags_list(self): + """ + Return tags as a list. + """ + if not self.tags: + return [] + return [tag.strip() for tag in self.tags.split(",") if tag.strip()] + + def increment_usage(self): + """ + Increment usage count when image is referenced. + """ + self.usage_count += 1 + self.save(update_fields=["usage_count"]) + + def decrement_usage(self): + """ + Decrement usage count when reference is removed. + """ + if self.usage_count > 0: + self.usage_count -= 1 + self.save(update_fields=["usage_count"]) + + +class ImageReference(models.Model): + """ + Abstract base class for models that want to reference images from the library. + This helps track usage and provides a consistent interface. + """ + + image = models.ForeignKey( + ImageLibrary, + on_delete=models.SET_NULL, + null=True, + blank=True, + help_text="Select an image from the library", + ) + + class Meta: + abstract = True + + def save(self, *args, **kwargs): + """ + Override save to update usage count. + """ + # Track if image changed + old_image = None + if self.pk: + try: + old_instance = self.__class__.objects.get(pk=self.pk) + old_image = old_instance.image + except self.__class__.DoesNotExist: + pass + + super().save(*args, **kwargs) + + # Update usage counts + if old_image and old_image != self.image: + old_image.decrement_usage() + + if self.image and self.image != old_image: + self.image.increment_usage() + + def delete(self, *args, **kwargs): + """ + Override delete to update usage count. + """ + if self.image: + self.image.decrement_usage() + super().delete(*args, **kwargs) diff --git a/hub/services/static/admin/css/image_library.css b/hub/services/static/admin/css/image_library.css new file mode 100644 index 0000000..6d589bb --- /dev/null +++ b/hub/services/static/admin/css/image_library.css @@ -0,0 +1,79 @@ +/* CSS for Image Library Admin */ + +/* Thumbnail styling in list view */ +.image-thumbnail { + border-radius: 4px; + object-fit: cover; +} + +/* Preview styling in detail view */ +.image-preview { + border-radius: 4px; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); +} + +/* Form styling */ +.image-library-form .form-row { + margin-bottom: 15px; +} + +.image-library-form .help { + font-size: 11px; + color: #666; + margin-top: 5px; +} + +/* Usage count styling */ +.usage-count { + font-weight: bold; + color: #0066cc; +} + +.usage-count.high { + color: #cc0000; +} + +/* Category badges */ +.category-badge { + display: inline-block; + padding: 2px 6px; + border-radius: 3px; + font-size: 10px; + font-weight: bold; + text-transform: uppercase; +} + +.category-badge.logo { + background-color: #e8f4f8; + color: #2c6e92; +} + +.category-badge.article { + background-color: #f0f8e8; + color: #5a7c3a; +} + +.category-badge.banner { + background-color: #fef4e8; + color: #d2691e; +} + +.category-badge.icon { + background-color: #f8e8f8; + color: #8b4c8b; +} + +.category-badge.screenshot { + background-color: #e8f8f4; + color: #3a7c5a; +} + +.category-badge.photo { + background-color: #f4e8f8; + color: #923c92; +} + +.category-badge.other { + background-color: #f0f0f0; + color: #666; +} \ No newline at end of file diff --git a/hub/services/templatetags/image_library.py b/hub/services/templatetags/image_library.py new file mode 100644 index 0000000..99339b7 --- /dev/null +++ b/hub/services/templatetags/image_library.py @@ -0,0 +1,112 @@ +from django import template +from django.utils.safestring import mark_safe +from django.utils.html import format_html +from ..models.images import ImageLibrary + +register = template.Library() + + +@register.simple_tag +def image_library_img(slug_or_id, css_class="", alt_text="", width=None, height=None): + """ + Render an image from the image library by slug or ID. + + Usage: + {% image_library_img "my-image-slug" css_class="img-fluid" %} + {% image_library_img image_id css_class="logo" width="100" height="100" %} + """ + try: + # Try to get by slug first, then by ID + if isinstance(slug_or_id, str): + image = ImageLibrary.objects.get(slug=slug_or_id) + else: + image = ImageLibrary.objects.get(pk=slug_or_id) + + # Use provided alt_text or fall back to image's alt_text + final_alt_text = alt_text or image.alt_text + + # Build HTML attributes + attrs = { + "src": image.image.url, + "alt": final_alt_text, + } + + if css_class: + attrs["class"] = css_class + + if width: + attrs["width"] = width + + if height: + attrs["height"] = height + + # Build the HTML + attr_string = " ".join(f'{k}="{v}"' for k, v in attrs.items()) + return format_html("", attr_string) + + except ImageLibrary.DoesNotExist: + # Return empty string or placeholder if image not found + return format_html( + 'Image not found', + css_class, + ) + + +@register.simple_tag +def image_library_url(slug_or_id): + """ + Get the URL of an image from the image library. + + Usage: + {% image_library_url "my-image-slug" %} + {% image_library_url image_id %} + """ + try: + if isinstance(slug_or_id, str): + image = ImageLibrary.objects.get(slug=slug_or_id) + else: + image = ImageLibrary.objects.get(pk=slug_or_id) + + return image.image.url + + except ImageLibrary.DoesNotExist: + return "/static/images/placeholder.png" + + +@register.simple_tag +def image_library_info(slug_or_id): + """ + Get information about an image from the image library. + + Usage: + {% image_library_info "my-image-slug" as img_info %} + {{ img_info.name }} - {{ img_info.width }}x{{ img_info.height }} + """ + try: + if isinstance(slug_or_id, str): + image = ImageLibrary.objects.get(slug=slug_or_id) + else: + image = ImageLibrary.objects.get(pk=slug_or_id) + + return { + "name": image.name, + "alt_text": image.alt_text, + "width": image.width, + "height": image.height, + "file_size": image.get_file_size_display(), + "category": image.get_category_display(), + "tags": image.get_tags_list(), + "url": image.image.url, + } + + except ImageLibrary.DoesNotExist: + return { + "name": "Image not found", + "alt_text": "Image not found", + "width": None, + "height": None, + "file_size": "Unknown", + "category": "Unknown", + "tags": [], + "url": "/static/images/placeholder.png", + } diff --git a/hub/services/utils/image_library.py b/hub/services/utils/image_library.py new file mode 100644 index 0000000..c0b72b2 --- /dev/null +++ b/hub/services/utils/image_library.py @@ -0,0 +1,243 @@ +from django.core.files.base import ContentFile +from django.utils.text import slugify +from ..models.images import ImageLibrary +import os + +try: + import requests +except ImportError: + requests = None +from PIL import Image as PILImage + + +def create_image_from_file( + file_path, name, description="", alt_text="", category="other", tags="" +): + """ + Create an ImageLibrary entry from a local file. + + Args: + file_path: Path to the image file + name: Name for the image + description: Optional description + alt_text: Alternative text for accessibility + category: Image category + tags: Comma-separated tags + + Returns: + ImageLibrary instance or None if failed + """ + try: + if not os.path.exists(file_path): + print(f"File not found: {file_path}") + return None + + # Generate slug + slug = slugify(name) + + # Check if image already exists + if ImageLibrary.objects.filter(slug=slug).exists(): + print(f"Image with slug '{slug}' already exists") + return ImageLibrary.objects.get(slug=slug) + + # Create image library entry + image_lib = ImageLibrary( + name=name, + slug=slug, + description=description, + alt_text=alt_text or name, + category=category, + tags=tags, + ) + + # Read and save the image file + with open(file_path, "rb") as f: + image_lib.image.save( + os.path.basename(file_path), ContentFile(f.read()), save=True + ) + + print(f"Created image library entry: {name}") + return image_lib + + except Exception as e: + print(f"Error creating image library entry: {e}") + return None + + +def create_image_from_url( + url, name, description="", alt_text="", category="other", tags="" +): + """ + Create an ImageLibrary entry from a URL. + + Args: + url: URL to the image + name: Name for the image + description: Optional description + alt_text: Alternative text for accessibility + category: Image category + tags: Comma-separated tags + + Returns: + ImageLibrary instance or None if failed + """ + if requests is None: + print("requests library is not installed. Cannot download from URL.") + return None + + try: + # Generate slug + slug = slugify(name) + + # Check if image already exists + if ImageLibrary.objects.filter(slug=slug).exists(): + print(f"Image with slug '{slug}' already exists") + return ImageLibrary.objects.get(slug=slug) + + # Download the image + response = requests.get(url) + response.raise_for_status() + + # Create image library entry + image_lib = ImageLibrary( + name=name, + slug=slug, + description=description, + alt_text=alt_text or name, + category=category, + tags=tags, + ) + + # Save the image + filename = url.split("/")[-1] + if "?" in filename: + filename = filename.split("?")[0] + + image_lib.image.save(filename, ContentFile(response.content), save=True) + + print(f"Created image library entry from URL: {name}") + return image_lib + + except Exception as e: + print(f"Error creating image library entry from URL: {e}") + return None + + +def get_image_by_slug(slug): + """ + Get an image from the library by slug. + + Args: + slug: Slug of the image + + Returns: + ImageLibrary instance or None if not found + """ + try: + return ImageLibrary.objects.get(slug=slug) + except ImageLibrary.DoesNotExist: + return None + + +def get_images_by_category(category): + """ + Get all images from a specific category. + + Args: + category: Category name + + Returns: + QuerySet of ImageLibrary instances + """ + return ImageLibrary.objects.filter(category=category) + + +def get_images_by_tags(tags): + """ + Get images that contain any of the specified tags. + + Args: + tags: List of tags or comma-separated string + + Returns: + QuerySet of ImageLibrary instances + """ + if isinstance(tags, str): + tags = [tag.strip() for tag in tags.split(",")] + + from django.db.models import Q + + query = Q() + for tag in tags: + query |= Q(tags__icontains=tag) + + return ImageLibrary.objects.filter(query).distinct() + + +def cleanup_unused_images(): + """ + Find and optionally clean up unused images from the library. + + Returns: + List of ImageLibrary instances with usage_count = 0 + """ + unused_images = ImageLibrary.objects.filter(usage_count=0) + + print(f"Found {unused_images.count()} unused images:") + for image in unused_images: + print(f" - {image.name} ({image.slug})") + + return unused_images + + +def optimize_image(image_library_instance, max_width=1920, max_height=1080, quality=85): + """ + Optimize an image in the library by resizing and compressing. + + Args: + image_library_instance: ImageLibrary instance + max_width: Maximum width in pixels + max_height: Maximum height in pixels + quality: JPEG quality (1-100) + + Returns: + bool: True if optimization was successful + """ + try: + if not image_library_instance.image: + return False + + # Open the image + with PILImage.open(image_library_instance.image.path) as img: + # Calculate new dimensions while maintaining aspect ratio + ratio = min(max_width / img.width, max_height / img.height) + + if ratio < 1: # Only resize if image is larger than max dimensions + new_width = int(img.width * ratio) + new_height = int(img.height * ratio) + + # Resize the image + img_resized = img.resize( + (new_width, new_height), PILImage.Resampling.LANCZOS + ) + + # Save the optimized image + img_resized.save( + image_library_instance.image.path, + format="JPEG", + quality=quality, + optimize=True, + ) + + # Update the image properties + image_library_instance._update_image_properties() + + print(f"Optimized image: {image_library_instance.name}") + return True + else: + print(f"Image already optimal: {image_library_instance.name}") + return True + + except Exception as e: + print(f"Error optimizing image {image_library_instance.name}: {e}") + return False diff --git a/hub/settings.py b/hub/settings.py index 8e6f3e6..120d9cb 100644 --- a/hub/settings.py +++ b/hub/settings.py @@ -245,6 +245,7 @@ JAZZMIN_SETTINGS = { "new_window": True, }, {"name": "Articles", "url": "/admin/services/article/"}, + {"name": "Image Library", "url": "/admin/services/imagelibrary/"}, {"name": "FAQs", "url": "/admin/services/websitefaq/"}, ], "show_sidebar": True, @@ -257,6 +258,7 @@ JAZZMIN_SETTINGS = { "services.VSHNAppCatAddon": "single", "services.ServiceOffering": "single", "services.Plan": "single", + "services.ImageLibrary": "single", }, "related_modal_active": True, } From 07bea333bc95d8859b58d3dc1d0ebef952b92561 Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Fri, 4 Jul 2025 16:49:29 +0200 Subject: [PATCH 17/60] move form to folder --- hub/services/forms/__init__.py | 2 ++ hub/services/{forms.py => forms/lead.py} | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 hub/services/forms/__init__.py rename hub/services/{forms.py => forms/lead.py} (94%) diff --git a/hub/services/forms/__init__.py b/hub/services/forms/__init__.py new file mode 100644 index 0000000..920f500 --- /dev/null +++ b/hub/services/forms/__init__.py @@ -0,0 +1,2 @@ +from .lead import LeadForm +from .image_library import ImageLibraryField, ImageLibraryWidget diff --git a/hub/services/forms.py b/hub/services/forms/lead.py similarity index 94% rename from hub/services/forms.py rename to hub/services/forms/lead.py index a608d44..d02c876 100644 --- a/hub/services/forms.py +++ b/hub/services/forms/lead.py @@ -1,5 +1,5 @@ from django import forms -from .models import Lead, Plan +from ..models import Lead class LeadForm(forms.ModelForm): From 1a2bbb1c3522a08edfc55c2ab37204abfba17aee Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Fri, 4 Jul 2025 17:26:09 +0200 Subject: [PATCH 18/60] image library migration step 1 --- IMAGE_LIBRARY_MIGRATION_STATUS.md | 81 +++++++++++++++++++ hub/services/admin/articles.py | 43 +++++++++- hub/services/admin/providers.py | 56 +++++++++++-- hub/services/admin/services.py | 33 +++++++- .../0041_add_image_library_references.py | 57 +++++++++++++ .../0042_fix_image_library_field_name.py | 74 +++++++++++++++++ hub/services/models/articles.py | 13 ++- hub/services/models/images.py | 15 ++-- hub/services/models/providers.py | 21 ++++- hub/services/models/services.py | 11 ++- hub/services/templates/pages/homepage.html | 12 ++- .../templates/services/article_detail.html | 8 +- .../templates/services/article_list.html | 2 +- .../templates/services/lead_form.html | 2 +- .../templates/services/offering_detail.html | 4 +- .../templates/services/offering_list.html | 4 +- .../templates/services/partner_detail.html | 4 +- .../templates/services/partner_list.html | 2 +- .../templates/services/provider_detail.html | 4 +- .../templates/services/provider_list.html | 2 +- .../templates/services/service_detail.html | 4 +- .../templates/services/service_list.html | 2 +- hub/services/templatetags/json_ld_tags.py | 16 ++-- 23 files changed, 413 insertions(+), 57 deletions(-) create mode 100644 IMAGE_LIBRARY_MIGRATION_STATUS.md create mode 100644 hub/services/migrations/0041_add_image_library_references.py create mode 100644 hub/services/migrations/0042_fix_image_library_field_name.py diff --git a/IMAGE_LIBRARY_MIGRATION_STATUS.md b/IMAGE_LIBRARY_MIGRATION_STATUS.md new file mode 100644 index 0000000..d2e27de --- /dev/null +++ b/IMAGE_LIBRARY_MIGRATION_STATUS.md @@ -0,0 +1,81 @@ +# Image Library Migration Status + +## ✅ COMPLETED (First Production Rollout) - UPDATED + +### Models Updated +- **Article**: Now inherits from `ImageReference`, with `image_library` field for new images and original `image` field temporarily +- **CloudProvider**: Now inherits from `ImageReference`, with `image_library` field for new images and original `logo` field temporarily +- **ConsultingPartner**: Now inherits from `ImageReference`, with `image_library` field for new images and original `logo` field temporarily +- **Service**: Now inherits from `ImageReference`, with `image_library` field for new images and original `logo` field temporarily + +### New Properties Added +- `Article.get_image()` - Returns image from library or falls back to original field +- `CloudProvider.get_logo()` - Returns logo from library or falls back to original field +- `ConsultingPartner.get_logo()` - Returns logo from library or falls back to original field +- `Service.get_logo()` - Returns logo from library or falls back to original field + +### Templates Updated +- ✅ `pages/homepage.html` - Updated service, provider, and partner image references +- ✅ `services/article_list.html` - Updated article image references +- ✅ `services/article_detail.html` - Updated related service/provider/partner logos +- ✅ `services/offering_list.html` - Updated service and provider logos +- ✅ `services/offering_detail.html` - Updated service and provider logos +- ✅ `services/lead_form.html` - Updated service logo +- ✅ `services/partner_detail.html` - Updated partner and service logos +- ✅ `services/partner_list.html` - Updated partner logos +- ✅ `services/provider_list.html` - Updated provider logos +- ✅ `services/provider_detail.html` - Updated provider and service logos +- ✅ `services/service_detail.html` - Updated service and provider logos + +### Admin Interface Updated +- ✅ `ArticleAdmin` - Updated image_preview to use get_image property +- ✅ `ServiceAdmin` - Updated logo_preview to use get_logo property +- ✅ `CloudProviderAdmin` - Updated logo_preview to use get_logo property +- ✅ `ConsultingPartnerAdmin` - Updated logo_preview to use get_logo property + +### JSON-LD Template Tags Updated +- ✅ Updated structured data generation to use new image properties +- ✅ Updated logo references for services, providers, and partners + +### Database Migration +- ✅ Migration `0041_add_image_library_references` successfully applied +- ✅ Migration `0042_fix_image_library_field_name` successfully applied +- ✅ All models now have `image_library` foreign key fields to ImageLibrary +- ✅ Original image fields preserved for backward compatibility +- ✅ Fixed field name conflicts using `%(class)s_references` related_name pattern + +### Admin Interface Enhanced +- ✅ **ArticleAdmin**: Added fieldsets with `image_library` field visible in "Images" section +- ✅ **ServiceAdmin**: Added fieldsets with `image_library` field visible in "Images" section +- ✅ **CloudProviderAdmin**: Added fieldsets with `image_library` field visible in "Images" section +- ✅ **ConsultingPartnerAdmin**: Added fieldsets with `image_library` field visible in "Images" section +- ✅ All admin interfaces show both new and legacy fields during transition +- ✅ Clear descriptions guide users to use Image Library for new images + +## Current Status +The system is now ready for production with dual image support: +- **New images**: Can be added through the Image Library +- **Legacy images**: Still work through the original fields +- **Templates**: Use the new `get_image/get_logo` properties that automatically fall back + +## Next Steps (Future Cleanup) +1. **Data Migration**: Create script to migrate existing images to ImageLibrary +2. **Admin Updates**: Update admin interfaces to use ImageLibrary selection +3. **Template Validation**: Add null checks to remaining templates +4. **Field Removal**: Remove legacy image fields after migration is complete +5. **Storage Cleanup**: Remove old image files from media directories + +## Benefits Achieved +- ✅ Centralized image management through ImageLibrary +- ✅ Usage tracking for images +- ✅ Backward compatibility maintained +- ✅ Enhanced admin experience ready +- ✅ Consistent image handling across all models +- ✅ Proper fallback mechanisms in place + +## Safety Measures +- ✅ Original image fields preserved +- ✅ Gradual migration approach +- ✅ Fallback properties ensure no broken images +- ✅ Database migration tested and applied +- ✅ Admin interface maintains functionality diff --git a/hub/services/admin/articles.py b/hub/services/admin/articles.py index 90298a4..387ec30 100644 --- a/hub/services/admin/articles.py +++ b/hub/services/admin/articles.py @@ -61,12 +61,47 @@ class ArticleAdmin(admin.ModelAdmin): readonly_fields = ("created_at", "updated_at") ordering = ("-article_date",) + fieldsets = ( + (None, {"fields": ("title", "slug", "excerpt", "content", "meta_keywords")}), + ( + "Images", + { + "fields": ( + "image_library", + "image", + ), # New image library field and legacy field + "description": "Use the Image Library field for new images. Legacy field will be removed after migration.", + }, + ), + ( + "Publishing", + {"fields": ("author", "article_date", "is_published", "is_featured")}, + ), + ( + "Relations", + { + "fields": ( + "related_service", + "related_consulting_partner", + "related_cloud_provider", + ), + "classes": ("collapse",), + }, + ), + ( + "Metadata", + { + "fields": ("created_at", "updated_at"), + "classes": ("collapse",), + }, + ), + ) + def image_preview(self, obj): """Display image preview in admin list view""" - if obj.image: - return format_html( - '', obj.image.url - ) + image = obj.get_image + if image: + return format_html('', image.url) return "No image" image_preview.short_description = "Image" diff --git a/hub/services/admin/providers.py b/hub/services/admin/providers.py index 8ef3ad3..d33e291 100644 --- a/hub/services/admin/providers.py +++ b/hub/services/admin/providers.py @@ -47,12 +47,30 @@ class CloudProviderAdmin(SortableAdminMixin, admin.ModelAdmin): inlines = [OfferingInline] ordering = ("order",) + fieldsets = ( + (None, {"fields": ("name", "slug", "description", "order")}), + ( + "Images", + { + "fields": ( + "image_library", + "logo", + ), # New image library field and legacy field + "description": "Use the Image Library field for new images. Legacy field will be removed after migration.", + }, + ), + ( + "Contact Information", + {"fields": ("website", "linkedin", "phone", "email", "address")}, + ), + ("Settings", {"fields": ("is_featured", "disable_listing")}), + ) + def logo_preview(self, obj): """Display logo preview in admin list view""" - if obj.logo: - return format_html( - '', obj.logo.url - ) + logo = obj.get_logo + if logo: + return format_html('', logo.url) return "No logo" logo_preview.short_description = "Logo" @@ -75,12 +93,34 @@ class ConsultingPartnerAdmin(SortableAdminMixin, admin.ModelAdmin): filter_horizontal = ("services", "cloud_providers") ordering = ("order",) + fieldsets = ( + (None, {"fields": ("name", "slug", "description", "order")}), + ( + "Images", + { + "fields": ( + "image_library", + "logo", + ), # New image library field and legacy field + "description": "Use the Image Library field for new images. Legacy field will be removed after migration.", + }, + ), + ( + "Contact Information", + {"fields": ("website", "linkedin", "phone", "email", "address")}, + ), + ( + "Relations", + {"fields": ("services", "cloud_providers"), "classes": ("collapse",)}, + ), + ("Settings", {"fields": ("is_featured", "disable_listing")}), + ) + def logo_preview(self, obj): """Display logo preview in admin list view""" - if obj.logo: - return format_html( - '', obj.logo.url - ) + logo = obj.get_logo + if logo: + return format_html('', logo.url) return "No logo" logo_preview.short_description = "Logo" diff --git a/hub/services/admin/services.py b/hub/services/admin/services.py index 41bc97f..b34cf97 100644 --- a/hub/services/admin/services.py +++ b/hub/services/admin/services.py @@ -93,12 +93,37 @@ class ServiceAdmin(admin.ModelAdmin): filter_horizontal = ("categories",) inlines = [ExternalLinkInline, OfferingInline] + fieldsets = ( + (None, {"fields": ("name", "slug", "description", "tagline")}), + ( + "Images", + { + "fields": ( + "image_library", + "logo", + ), # New image library field and legacy field + "description": "Use the Image Library field for new images. Legacy field will be removed after migration.", + }, + ), + ( + "Configuration", + { + "fields": ( + "categories", + "features", + "is_featured", + "is_coming_soon", + "disable_listing", + ) + }, + ), + ) + def logo_preview(self, obj): """Display logo preview in admin list view""" - if obj.logo: - return format_html( - '', obj.logo.url - ) + logo = obj.get_logo + if logo: + return format_html('', logo.url) return "No logo" logo_preview.short_description = "Logo" diff --git a/hub/services/migrations/0041_add_image_library_references.py b/hub/services/migrations/0041_add_image_library_references.py new file mode 100644 index 0000000..231520b --- /dev/null +++ b/hub/services/migrations/0041_add_image_library_references.py @@ -0,0 +1,57 @@ +# Generated by Django 5.2 on 2025-07-04 15:04 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ("services", "0040_add_image_library"), + ] + + operations = [ + migrations.AddField( + model_name="cloudprovider", + name="image", + field=models.ForeignKey( + blank=True, + help_text="Select an image from the library", + null=True, + on_delete=django.db.models.deletion.SET_NULL, + to="services.imagelibrary", + ), + ), + migrations.AddField( + model_name="consultingpartner", + name="image", + field=models.ForeignKey( + blank=True, + help_text="Select an image from the library", + null=True, + on_delete=django.db.models.deletion.SET_NULL, + to="services.imagelibrary", + ), + ), + migrations.AddField( + model_name="service", + name="image", + field=models.ForeignKey( + blank=True, + help_text="Select an image from the library", + null=True, + on_delete=django.db.models.deletion.SET_NULL, + to="services.imagelibrary", + ), + ), + migrations.AlterField( + model_name="article", + name="image", + field=models.ImageField( + blank=True, + help_text="Title picture for the article", + null=True, + upload_to="article_images/", + ), + ), + ] diff --git a/hub/services/migrations/0042_fix_image_library_field_name.py b/hub/services/migrations/0042_fix_image_library_field_name.py new file mode 100644 index 0000000..0996f8b --- /dev/null +++ b/hub/services/migrations/0042_fix_image_library_field_name.py @@ -0,0 +1,74 @@ +# Generated by Django 5.2 on 2025-07-04 15:22 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ("services", "0041_add_image_library_references"), + ] + + operations = [ + migrations.RemoveField( + model_name="cloudprovider", + name="image", + ), + migrations.RemoveField( + model_name="consultingpartner", + name="image", + ), + migrations.RemoveField( + model_name="service", + name="image", + ), + migrations.AddField( + model_name="article", + name="image_library", + field=models.ForeignKey( + blank=True, + help_text="Select an image from the library", + null=True, + on_delete=django.db.models.deletion.SET_NULL, + related_name="%(class)s_references", + to="services.imagelibrary", + ), + ), + migrations.AddField( + model_name="cloudprovider", + name="image_library", + field=models.ForeignKey( + blank=True, + help_text="Select an image from the library", + null=True, + on_delete=django.db.models.deletion.SET_NULL, + related_name="%(class)s_references", + to="services.imagelibrary", + ), + ), + migrations.AddField( + model_name="consultingpartner", + name="image_library", + field=models.ForeignKey( + blank=True, + help_text="Select an image from the library", + null=True, + on_delete=django.db.models.deletion.SET_NULL, + related_name="%(class)s_references", + to="services.imagelibrary", + ), + ), + migrations.AddField( + model_name="service", + name="image_library", + field=models.ForeignKey( + blank=True, + help_text="Select an image from the library", + null=True, + on_delete=django.db.models.deletion.SET_NULL, + related_name="%(class)s_references", + to="services.imagelibrary", + ), + ), + ] diff --git a/hub/services/models/articles.py b/hub/services/models/articles.py index b1b85e7..8ea50c0 100644 --- a/hub/services/models/articles.py +++ b/hub/services/models/articles.py @@ -7,9 +7,10 @@ from django.utils import timezone from .base import validate_image_size from .services import Service from .providers import CloudProvider, ConsultingPartner +from .images import ImageReference -class Article(models.Model): +class Article(ImageReference): title = models.CharField(max_length=200) slug = models.SlugField(max_length=250, unique=True) excerpt = models.TextField( @@ -19,9 +20,12 @@ class Article(models.Model): meta_keywords = models.CharField( max_length=255, blank=True, help_text="SEO keywords separated by commas" ) + # Original image field - keep temporarily for migration image = models.ImageField( upload_to="article_images/", help_text="Title picture for the article", + null=True, + blank=True, ) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="articles") article_date = models.DateField( @@ -86,6 +90,13 @@ class Article(models.Model): def get_absolute_url(self): return reverse("services:article_detail", kwargs={"slug": self.slug}) + @property + def get_image(self): + """Returns the image from library or falls back to legacy image""" + if self.image_library and self.image_library.image: + return self.image_library.image + return self.image + @property def related_to(self): """Returns a string describing what this article is related to""" diff --git a/hub/services/models/images.py b/hub/services/models/images.py index 90052ab..3bf72f7 100644 --- a/hub/services/models/images.py +++ b/hub/services/models/images.py @@ -182,12 +182,13 @@ class ImageReference(models.Model): This helps track usage and provides a consistent interface. """ - image = models.ForeignKey( + image_library = models.ForeignKey( ImageLibrary, on_delete=models.SET_NULL, null=True, blank=True, help_text="Select an image from the library", + related_name="%(class)s_references", ) class Meta: @@ -202,23 +203,23 @@ class ImageReference(models.Model): if self.pk: try: old_instance = self.__class__.objects.get(pk=self.pk) - old_image = old_instance.image + old_image = old_instance.image_library except self.__class__.DoesNotExist: pass super().save(*args, **kwargs) # Update usage counts - if old_image and old_image != self.image: + if old_image and old_image != self.image_library: old_image.decrement_usage() - if self.image and self.image != old_image: - self.image.increment_usage() + if self.image_library and self.image_library != old_image: + self.image_library.increment_usage() def delete(self, *args, **kwargs): """ Override delete to update usage count. """ - if self.image: - self.image.decrement_usage() + if self.image_library: + self.image_library.decrement_usage() super().delete(*args, **kwargs) diff --git a/hub/services/models/providers.py b/hub/services/models/providers.py index e3257ea..5567cb9 100644 --- a/hub/services/models/providers.py +++ b/hub/services/models/providers.py @@ -4,9 +4,10 @@ from django.utils.text import slugify from django_prose_editor.fields import ProseEditorField from .base import validate_image_size +from .images import ImageReference -class CloudProvider(models.Model): +class CloudProvider(ImageReference): name = models.CharField(max_length=100) slug = models.SlugField(unique=True) description = ProseEditorField() @@ -15,6 +16,7 @@ class CloudProvider(models.Model): phone = models.CharField(max_length=25, blank=True, null=True) email = models.EmailField(max_length=254, blank=True, null=True) address = models.TextField(max_length=250, blank=True, null=True) + # Original logo field - keep temporarily for migration logo = models.ImageField( upload_to="cloud_provider_logos/", validators=[validate_image_size], @@ -39,11 +41,19 @@ class CloudProvider(models.Model): def get_absolute_url(self): return reverse("services:provider_detail", kwargs={"slug": self.slug}) + @property + def get_logo(self): + """Returns the logo from library or falls back to legacy logo""" + if self.image_library and self.image_library.image: + return self.image_library.image + return self.logo -class ConsultingPartner(models.Model): + +class ConsultingPartner(ImageReference): name = models.CharField(max_length=200) slug = models.SlugField(unique=True) description = ProseEditorField() + # Original logo field - keep temporarily for migration logo = models.ImageField( upload_to="partner_logos/", validators=[validate_image_size], @@ -83,3 +93,10 @@ class ConsultingPartner(models.Model): def get_absolute_url(self): return reverse("services:partner_detail", kwargs={"slug": self.slug}) + + @property + def get_logo(self): + """Returns the logo from library or falls back to legacy logo""" + if self.image_library and self.image_library.image: + return self.image_library.image + return self.logo diff --git a/hub/services/models/services.py b/hub/services/models/services.py index 8b6984d..af4c2e0 100644 --- a/hub/services/models/services.py +++ b/hub/services/models/services.py @@ -13,13 +13,15 @@ from .base import ( Currency, ) from .providers import CloudProvider +from .images import ImageReference -class Service(models.Model): +class Service(ImageReference): name = models.CharField(max_length=200) slug = models.SlugField(max_length=250, unique=True) description = ProseEditorField() tagline = models.TextField(max_length=500, blank=True, null=True) + # Original logo field - keep temporarily for migration logo = models.ImageField( upload_to="service_logos/", validators=[validate_image_size], @@ -58,6 +60,13 @@ class Service(models.Model): def get_absolute_url(self): return reverse("services:service_detail", kwargs={"slug": self.slug}) + @property + def get_logo(self): + """Returns the logo from library or falls back to legacy logo""" + if self.image_library and self.image_library.image: + return self.image_library.image + return self.logo + class ServiceOffering(models.Model): service = models.ForeignKey( diff --git a/hub/services/templates/pages/homepage.html b/hub/services/templates/pages/homepage.html index f16da44..a7507c6 100644 --- a/hub/services/templates/pages/homepage.html +++ b/hub/services/templates/pages/homepage.html @@ -48,9 +48,15 @@ @@ -105,7 +111,7 @@
- {{ provider.name }} @@ -159,7 +165,7 @@
- {{ partner.name }} diff --git a/hub/services/templates/services/article_detail.html b/hub/services/templates/services/article_detail.html index b3264e5..2f67b43 100644 --- a/hub/services/templates/services/article_detail.html +++ b/hub/services/templates/services/article_detail.html @@ -43,7 +43,7 @@
Service
{% if article.related_service.logo %}
- {{ article.related_service.name }} logo
{% endif %} @@ -60,7 +60,7 @@
Partner
{% if article.related_consulting_partner.logo %}
- {{ article.related_consulting_partner.name }} logo
{% endif %} @@ -77,7 +77,7 @@
Provider
{% if article.related_cloud_provider.logo %}
- {{ article.related_cloud_provider.name }} logo
{% endif %} @@ -100,7 +100,7 @@
{% if related_article.image %} - {{ related_article.title }} + {{ related_article.title }} {% endif %}
{{ related_article.title }}
diff --git a/hub/services/templates/services/article_list.html b/hub/services/templates/services/article_list.html index ac86df4..47ae5ae 100644 --- a/hub/services/templates/services/article_list.html +++ b/hub/services/templates/services/article_list.html @@ -149,7 +149,7 @@
{% if article.image %}
- {{ article.title }} + {{ article.title }}
{% endif %} {% if article.is_featured %} diff --git a/hub/services/templates/services/lead_form.html b/hub/services/templates/services/lead_form.html index 73e0585..bcc26d6 100644 --- a/hub/services/templates/services/lead_form.html +++ b/hub/services/templates/services/lead_form.html @@ -78,7 +78,7 @@
{% if selected_offering.service.logo %} - Service Logo + Service Logo {% endif %}
diff --git a/hub/services/templates/services/offering_detail.html b/hub/services/templates/services/offering_detail.html index e6682e3..2fe0eba 100644 --- a/hub/services/templates/services/offering_detail.html +++ b/hub/services/templates/services/offering_detail.html @@ -34,7 +34,7 @@
{% if offering.service.logo %} - {{ offering.service.name }} logo {% endif %} @@ -50,7 +50,7 @@

Runs on

- {{ offering.cloud_provider.name }} logo + {{ offering.cloud_provider.name }} logo
diff --git a/hub/services/templates/services/offering_list.html b/hub/services/templates/services/offering_list.html index 0f138e3..741352b 100644 --- a/hub/services/templates/services/offering_list.html +++ b/hub/services/templates/services/offering_list.html @@ -151,7 +151,7 @@
{% if offering.service.logo %} - {{ offering.service.name }} {% endif %} @@ -165,7 +165,7 @@
{% if offering.cloud_provider.logo %} - {{ offering.cloud_provider.name }} diff --git a/hub/services/templates/services/partner_detail.html b/hub/services/templates/services/partner_detail.html index 7e90b82..1e78144 100644 --- a/hub/services/templates/services/partner_detail.html +++ b/hub/services/templates/services/partner_detail.html @@ -24,7 +24,7 @@
{% if partner.logo %} - {{ partner.name }} logo + {{ partner.name }} logo {% endif %}
@@ -178,7 +178,7 @@ {% if service.logo %} {% endif %} diff --git a/hub/services/templates/services/partner_list.html b/hub/services/templates/services/partner_list.html index fb196dc..5f554ac 100644 --- a/hub/services/templates/services/partner_list.html +++ b/hub/services/templates/services/partner_list.html @@ -115,7 +115,7 @@
- {{ partner.name }} diff --git a/hub/services/templates/services/provider_detail.html b/hub/services/templates/services/provider_detail.html index 151c986..aa9c360 100644 --- a/hub/services/templates/services/provider_detail.html +++ b/hub/services/templates/services/provider_detail.html @@ -24,7 +24,7 @@
{% if provider.logo %} - {{ provider.name }} logo + {{ provider.name }} logo {% endif %}
@@ -178,7 +178,7 @@ {% if offering.service.logo %} {% endif %} diff --git a/hub/services/templates/services/provider_list.html b/hub/services/templates/services/provider_list.html index 5484b7e..ca27bab 100644 --- a/hub/services/templates/services/provider_list.html +++ b/hub/services/templates/services/provider_list.html @@ -99,7 +99,7 @@
{% if provider.logo %} - {{ provider.name }} diff --git a/hub/services/templates/services/service_detail.html b/hub/services/templates/services/service_detail.html index 5054d61..bdb3748 100644 --- a/hub/services/templates/services/service_detail.html +++ b/hub/services/templates/services/service_detail.html @@ -23,7 +23,7 @@
{% if service.logo %} - {{ service.name }} logo + {{ service.name }} logo {% endif %}
@@ -184,7 +184,7 @@
{% if offering.cloud_provider.logo %}
- {{ offering.cloud_provider.name }} logo
{% else %} diff --git a/hub/services/templates/services/service_list.html b/hub/services/templates/services/service_list.html index da16d3e..0420a74 100644 --- a/hub/services/templates/services/service_list.html +++ b/hub/services/templates/services/service_list.html @@ -156,7 +156,7 @@
{% if service.logo %}
- {{ service.name }} logo + {{ service.name }} logo
{% endif %} {% if service.is_featured %} diff --git a/hub/services/templatetags/json_ld_tags.py b/hub/services/templatetags/json_ld_tags.py index eb18007..c9225d5 100644 --- a/hub/services/templatetags/json_ld_tags.py +++ b/hub/services/templatetags/json_ld_tags.py @@ -119,8 +119,8 @@ def json_ld_structured_data(context): } # Add image if available - if hasattr(service, "logo") and service.logo: - data["image"] = request.build_absolute_uri(service.logo.url) + if hasattr(service, "get_logo") and service.get_logo: + data["image"] = request.build_absolute_uri(service.get_logo.url) # Add offerings if available if hasattr(service, "offerings") and service.offerings.exists(): @@ -143,8 +143,8 @@ def json_ld_structured_data(context): } # Add image if available - if hasattr(provider, "logo") and provider.logo: - data["logo"] = request.build_absolute_uri(provider.logo.url) + if hasattr(provider, "get_logo") and provider.get_logo: + data["logo"] = request.build_absolute_uri(provider.get_logo.url) # Add contact information if available contact_point = {"@type": "ContactPoint", "contactType": "Customer Support"} @@ -179,8 +179,8 @@ def json_ld_structured_data(context): } # Add image if available - if hasattr(partner, "logo") and partner.logo: - data["logo"] = request.build_absolute_uri(partner.logo.url) + if hasattr(partner, "get_logo") and partner.get_logo: + data["logo"] = request.build_absolute_uri(partner.get_logo.url) # Add contact information if available contact_point = {"@type": "ContactPoint", "contactType": "Customer Support"} @@ -219,8 +219,8 @@ def json_ld_structured_data(context): data["brand"] = {"@type": "Brand", "name": offering.service.name} # Add image if available - if hasattr(offering.service, "logo") and offering.service.logo: - data["image"] = request.build_absolute_uri(offering.service.logo.url) + if hasattr(offering.service, "get_logo") and offering.service.get_logo: + data["image"] = request.build_absolute_uri(offering.service.get_logo.url) # Add offers if available if hasattr(offering, "plans") and offering.plans.exists(): From 89149198cc7547aa6302b9c381708e716a90474e Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Mon, 7 Jul 2025 13:18:07 +0200 Subject: [PATCH 19/60] move articles menu item to before about --- hub/services/templates/base.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hub/services/templates/base.html b/hub/services/templates/base.html index 9cef2f2..1e451a9 100644 --- a/hub/services/templates/base.html +++ b/hub/services/templates/base.html @@ -55,9 +55,9 @@
diff --git a/hub/services/templates/services/partner_detail.html b/hub/services/templates/services/partner_detail.html index 477af4a..1f3968e 100644 --- a/hub/services/templates/services/partner_detail.html +++ b/hub/services/templates/services/partner_detail.html @@ -153,7 +153,7 @@

{{ partner.name }}

- +
diff --git a/hub/services/templates/services/partner_list.html b/hub/services/templates/services/partner_list.html index f05ca5b..59765b0 100644 --- a/hub/services/templates/services/partner_list.html +++ b/hub/services/templates/services/partner_list.html @@ -94,6 +94,23 @@
+ +
+
+ +
+
+ +
+
+
Clear @@ -126,6 +143,9 @@

{{ partner.name }}

+
+ {{ partner.get_category_display_badge }} +
diff --git a/hub/services/views/partners.py b/hub/services/views/partners.py index ac3668e..4651a14 100644 --- a/hub/services/views/partners.py +++ b/hub/services/views/partners.py @@ -1,6 +1,7 @@ from django.shortcuts import render, get_object_or_404 from django.db.models import Q from hub.services.models import ConsultingPartner, CloudProvider, Service +from hub.services.models.base import PartnerCategory def partner_list(request): @@ -8,6 +9,7 @@ def partner_list(request): search_query = request.GET.get("search", "") service_id = request.GET.get("service", "") cloud_provider_id = request.GET.get("cloud_provider", "") + category = request.GET.get("category", "") # Start with all active partners partners = ConsultingPartner.objects.filter(disable_listing=False).order_by("order") @@ -24,6 +26,9 @@ def partner_list(request): if cloud_provider_id: partners = partners.filter(cloud_providers__id=cloud_provider_id) + if category: + partners = partners.filter(category=category) + # Get available services from filtered partners available_service_ids = partners.values_list("services__id", flat=True).distinct() available_services = Service.objects.filter( @@ -68,6 +73,7 @@ def partner_list(request): ), "available_services": available_services, "available_cloud_providers": available_cloud_providers, + "partner_categories": PartnerCategory.choices, } return render(request, "services/partner_list.html", context) From dd25ea9d10c7bbde3b8984fd30d8ae3c334c754d Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Fri, 11 Jul 2025 11:02:14 +0200 Subject: [PATCH 48/60] better category badge on list view --- .../templates/services/partner_detail.html | 22 ++++++------- .../templates/services/partner_list.html | 31 +++++++++---------- 2 files changed, 25 insertions(+), 28 deletions(-) diff --git a/hub/services/templates/services/partner_detail.html b/hub/services/templates/services/partner_detail.html index 1f3968e..98c81a4 100644 --- a/hub/services/templates/services/partner_detail.html +++ b/hub/services/templates/services/partner_detail.html @@ -171,19 +171,17 @@

Consulting for Services

{% for service in services %} -
-
- {% if service.get_logo %} -
- {% if service.get_logo %} -
- - {{ service.name }} logo - -
- {% endif %} +
+ {% if service.get_logo %} +
+ - {% endif %} +
+ {% endif %}

{{ service.name }}

diff --git a/hub/services/templates/services/partner_list.html b/hub/services/templates/services/partner_list.html index 59765b0..1a3edf6 100644 --- a/hub/services/templates/services/partner_list.html +++ b/hub/services/templates/services/partner_list.html @@ -127,25 +127,24 @@
+ {% if partner.category %} +
+ {{ partner.get_category_display_badge }} +
+ {% endif %} + {% if partner.get_logo %} +
+
+ {{ partner.name }} logo +
+
+ {% endif %}
-
- {% if partner.get_logo %} -
- - {{ partner.name }} - -
- {% endif %} -

{{ partner.name }}

-
- {{ partner.get_category_display_badge }} -
@@ -155,9 +154,9 @@
From c123e74c1f9c669ecbc434f27fefbcc5744fcb08 Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Fri, 11 Jul 2025 11:14:43 +0200 Subject: [PATCH 49/60] several adjustments to support different partner categories --- hub/services/models/providers.py | 3 +- hub/services/templates/base.html | 4 +- .../templates/services/partner_detail.html | 29 ++------ .../templates/services/partner_list.html | 4 +- .../templates/services/service_detail.html | 73 ++++++++++++++----- 5 files changed, 66 insertions(+), 47 deletions(-) diff --git a/hub/services/models/providers.py b/hub/services/models/providers.py index 3589d66..0877111 100644 --- a/hub/services/models/providers.py +++ b/hub/services/models/providers.py @@ -80,8 +80,7 @@ class ConsultingPartner(ImageReference): return f"{self.name} ({self.get_category_display()})" def get_category_display_badge(self): - """Returns category display suitable for badges/UI""" - return self.get_category_display() + return f"Servala {self.get_category_display()} Partner" def save(self, *args, **kwargs): if not self.slug: diff --git a/hub/services/templates/base.html b/hub/services/templates/base.html index 1e451a9..57d59ff 100644 --- a/hub/services/templates/base.html +++ b/hub/services/templates/base.html @@ -55,8 +55,8 @@ diff --git a/hub/services/templates/services/partner_detail.html b/hub/services/templates/services/partner_detail.html index 98c81a4..159533f 100644 --- a/hub/services/templates/services/partner_detail.html +++ b/hub/services/templates/services/partner_detail.html @@ -99,27 +99,6 @@
- - {% if partner.cloud_providers.exists %} -
-

Cloud Providers

- -
- {% endif %} - {% if related_articles %}
@@ -168,7 +147,13 @@ {% if services %}
-

Consulting for Services

+

+ {% if partner.category == 'TRAINING' %} + Training for Services + {% else %} + Consulting for Services + {% endif %} +

{% for service in services %}
diff --git a/hub/services/templates/services/partner_list.html b/hub/services/templates/services/partner_list.html index 1a3edf6..942f748 100644 --- a/hub/services/templates/services/partner_list.html +++ b/hub/services/templates/services/partner_list.html @@ -156,7 +156,9 @@ {% if partner.website %} Visit Website {% endif %} - Available Services + + {% if partner.category == 'TRAINING' %}Available Trainings{% else %}Available Services{% endif %} +
diff --git a/hub/services/templates/services/service_detail.html b/hub/services/templates/services/service_detail.html index 9628846..e45e1a4 100644 --- a/hub/services/templates/services/service_detail.html +++ b/hub/services/templates/services/service_detail.html @@ -51,26 +51,59 @@ {% endif %} - {% if service.consulting_partners.exists %} -
-

Consulting Partners

-

If you want to get the most out of your {{ service.name }}, our consulting partners can help you optimize your setup and application:

- -
- {% endif %} + {% with consulting_partners=service.consulting_partners.all|dictsort:"order" %} + {% regroup consulting_partners by category as partners_by_category %} + {% for category_group in partners_by_category %} + {% if category_group.grouper == "CONSULTING" and category_group.list %} +
+

Consulting Partners

+

If you want to get the most out of your {{ service.name }} service, our consulting partners can help you optimize your setup and application:

+ +
+ {% endif %} + {% endfor %} + {% endwith %} + + + {% with training_partners=service.consulting_partners.all|dictsort:"order" %} + {% regroup training_partners by category as partners_by_category %} + {% for category_group in partners_by_category %} + {% if category_group.grouper == "TRAINING" and category_group.list %} +
+

Training Partners

+

Looking to upskill your team on {{ service.name }}? Our training partners offer comprehensive courses and workshops:

+ +
+ {% endif %} + {% endfor %} + {% endwith %} {% if service.external_links.exists %} From 4bc6e7d3541034f70bd24a226e7a436ece9b3272 Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Fri, 11 Jul 2025 11:19:02 +0200 Subject: [PATCH 50/60] add time to datePublished --- hub/services/templatetags/json_ld_tags.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/hub/services/templatetags/json_ld_tags.py b/hub/services/templatetags/json_ld_tags.py index 3741bfe..6efa78c 100644 --- a/hub/services/templatetags/json_ld_tags.py +++ b/hub/services/templatetags/json_ld_tags.py @@ -1,7 +1,9 @@ -# hub/services/templatetags/json_ld_tags.py +from datetime import datetime, time from django import template from django.urls import resolve, Resolver404 from django.utils.safestring import mark_safe +from django.utils import timezone as django_timezone + import json register = template.Library() @@ -332,8 +334,10 @@ def json_ld_structured_data(context): } # Add publication date using article_date field - if article.article_date: - data["datePublished"] = article.article_date.isoformat() + article_datetime = django_timezone.make_aware( + datetime.combine(article.article_date, time.min) + ) + data["datePublished"] = article_datetime.isoformat() # Add modification date if article.updated_at: From 53e87ae1a2dfc3d9b12647caa8ba35118acb80c4 Mon Sep 17 00:00:00 2001 From: Tobias Brunner Date: Fri, 11 Jul 2025 11:27:57 +0200 Subject: [PATCH 51/60] small adjustments to partner listing --- .../templates/services/partner_list.html | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/hub/services/templates/services/partner_list.html b/hub/services/templates/services/partner_list.html index 942f748..600cc6c 100644 --- a/hub/services/templates/services/partner_list.html +++ b/hub/services/templates/services/partner_list.html @@ -129,19 +129,21 @@ onclick="cardClicked(event, '{{ partner.get_absolute_url }}')"> {% if partner.category %}
- {{ partner.get_category_display_badge }} -
- {% endif %} - {% if partner.get_logo %} -
-
- {{ partner.name }} logo -
+ {{ partner.get_category_display_badge }}
{% endif %}
+ {% if partner.get_logo %} +
+
+ + {{ partner.name }} logo + +
+
+ {% endif %}

{{ partner.name }}

@@ -154,9 +156,9 @@