Service Management
Live Preview

Overview
The Services Management screen serves as a primary interface within the Admin Center for authorized client administrators and key decision-makers to manage recurring service subscriptions applied across their organization's assets (specifically Devices and Users).
Core Functionality:
- Visibility: Provides a clear view of which specific service plans (e.g., Antivirus tiers, Backup plans, Endpoint Security levels) are currently assigned to individual Devices or Users.
- Assignment Control: Allows users with appropriate permissions to change the assigned service plan for an entity within a given service category, selecting from options available under the client's active agreements.
- Staging & Review: Changes made by the user are staged locally in the UI, not saved immediately. A summary bar calculates and displays the aggregated impact of these staged changes (quantity changes, monthly cost difference) across the entire filtered set of entities. Users can review these proposed changes before committing.
- Apply/Discard: Users can either apply the batch of staged changes (triggering backend updates and potentially billing adjustments) or discard all staged changes to revert to the original state.
- Contextual Information:
- Displays service plan recommendations (based on predefined rules) using visual cues (background colors) to guide users towards optimal configurations.
- Indicates when a service assignment is controlled by a policy (disabling manual changes for that specific assignment) and provides details about the policy on hover.
- Shows pricing information for each available service option, calculated according to the relevant pricing rules and overrides.
- Offers a comparison modal for users to view detailed feature differences between available service plans within a category.
- Scoping: Users can filter the view by entity type (Devices/Users), location, device type, user group, and search terms to manage assignments efficiently across different segments of their organization.
Essentially, this screen acts as a centralized control panel for managing the assignment and configuration of recurring, per-entity services defined within the product catalog and made available through client agreements. It bridges the gap between contracted services and their application to specific assets, providing cost transparency and guided recommendations.
Code
HTML
Javascript
/**
* Services Management Page Script v2
*
* Handles dynamic rendering of the service assignment matrix for Devices/Users,
* staging changes, calculating summary costs, handling policy/recommendations,
* and user interactions like applying changes or viewing details.
* Supports tab switching between Devices and Users.
*/
// --- Global State & Configuration ---
let originalState = {}; // Stores initial assignments { entityId: { categoryId: planId } }
let stagedChanges = {}; // Stores changes { entityId: { categoryId: { newPlanId, originalPlanId, ... } } }
let currentEntityType = 'Device'; // Track active tab ('Device' or 'User')
// --- Mock Data (Replace with actual data loading mechanism) ---
const pageData = {
organizationDefaults: {
currency: "CAD" // Default currency for summary calculations
},
entities: [ // Example entities - load dynamically based on filters in real app
// --- Devices ---
{
id: "dev-001",
type: "Device", // Entity type
name: "LAPTOP-001",
link: "#",
details: "Laptop | John Doe | Main Office",
deviceType: "Laptop", // Specific device type
locationId: "main",
assignments: { "cat-antivirus": "plan-av-std", "cat-endpoint": "plan-ep-mdr", "cat-backup": "plan-bkp-wks" },
policyAssignments: { "cat-endpoint": "policy-laptop-default" },
recommendations: { "cat-antivirus": "plan-av-std", "cat-endpoint": "plan-ep-mdr", "cat-backup": "plan-bkp-wks" }
},
{
id: "dev-004",
type: "Device",
name: "LAPTOP-002",
link: "#",
details: "Laptop | Jane Doe | Remote",
deviceType: "Laptop",
locationId: "remote-a",
assignments: { "cat-antivirus": "none", "cat-endpoint": "plan-ep-mdr", "cat-backup": "plan-bkp-wks" },
policyAssignments: { "cat-endpoint": "policy-laptop-default" },
recommendations: { "cat-antivirus": "plan-av-std", "cat-endpoint": "plan-ep-mdr", "cat-backup": "plan-bkp-wks" }
},
{
id: "dev-003",
type: "Device",
name: "SERVER-MAIN",
link: "#",
details: "Server | N/A | Branch Office",
deviceType: "Server",
locationId: "branch-a",
assignments: { "cat-antivirus": "plan-av-pro", "cat-endpoint": "N/A", "cat-backup": "plan-bkp-srv" },
policyAssignments": {},
recommendations": { "cat-antivirus": "plan-av-pro", "cat-endpoint": null, "cat-backup": "plan-bkp-srv" }
},
// --- Users ---
{
id: "usr-001",
type: "User", // Entity type
name: "Jane Smith",
link: "#", // Link to user profile
details: "Sales Manager | Main Office",
deviceType: null, // Not applicable to users
locationId: "main",
assignments: { "cat-email": "plan-email-std" }, // Only email applies
policyAssignments: {},
recommendations: { "cat-email": "plan-email-adv" } // Recommend advanced
},
{
id: "usr-002",
type: "User",
name: "Bob Johnson",
link: "#",
details: "Engineer | Engineering",
deviceType: null,
locationId: "main",
assignments: { "cat-email": "plan-email-std" }, // Also has standard
policyAssignments: {},
recommendations: { "cat-email": "plan-email-std" } // Recommend standard
}
],
visibleCategories: { // Categories to show per entity type
Device: ["cat-antivirus", "cat-endpoint", "cat-backup"],
User: ["cat-email"] // Only show Email Protection for Users
},
serviceCategories: { // Category details
"cat-antivirus": { "name": "Antivirus" },
"cat-endpoint": { "name": "Endpoint Security" },
"cat-backup": { "name": "Backup" },
"cat-email": { "name": "Email Protection" }
},
servicePlans: { // Plan details
"none": { categoryId: null, name: "None", description: "No service assigned.", price: 0, currency: "CAD", applicableEntityTypes: ["Device", "User"], applicableDeviceTypes: null },
"plan-av-std": { categoryId: "cat-antivirus", name: "Standard AV", description: "Core protection.", price: 6.00, currency: "CAD", applicableEntityTypes: ["Device"], applicableDeviceTypes: ["Laptop", "Workstation"], comparison_attributes: {"Real-time Protection": true, "Scheduled Scans": true, "Ransomware Rollback": false}, is_service_management_enabled: true },
"plan-av-adv": { categoryId: "cat-antivirus", name: "Advanced AV", description: "Adds rollback.", price: 12.00, currency: "CAD", applicableEntityTypes: ["Device"], applicableDeviceTypes: ["Laptop", "Workstation"], comparison_attributes: {"Real-time Protection": true, "Scheduled Scans": true, "Ransomware Rollback": true}, is_service_management_enabled: true },
"plan-av-pro": { categoryId: "cat-antivirus", name: "Server AV Pro", description: "For servers.", price: 25.00, currency: "CAD", applicableEntityTypes: ["Device"], applicableDeviceTypes: ["Server"], comparison_attributes: {"Real-time Protection": true, "Scheduled Scans": true, "Ransomware Rollback": true}, is_service_management_enabled: true },
"plan-ep-mdr": { categoryId: "cat-endpoint", name: "Standard MDR", description: "Managed Detection & Response.", price: 15.00, currency: "CAD", applicableEntityTypes: ["Device"], applicableDeviceTypes: ["Laptop", "Workstation"], comparison_attributes: {"Threat Hunting": true, "Incident Response": true}, is_service_management_enabled: true },
"plan-bkp-wks": { categoryId: "cat-backup", name: "Workstation Backup", description: "For workstations/laptops.", price: 10.00, currency: "CAD", mandatory: true, applicableEntityTypes: ["Device"], applicableDeviceTypes: ["Laptop", "Workstation"], comparison_attributes: {"File Backup": true, "System Image": false, "Cloud Storage": "100 GB"}, is_service_management_enabled: true },
"plan-bkp-srv": { categoryId: "cat-backup", name: "Server Backup", description: "For servers.", price: 50.00, currency: "CAD", mandatory: false, applicableEntityTypes: ["Device"], applicableDeviceTypes: ["Server"], comparison_attributes: {"File Backup": true, "System Image": true, "Cloud Storage": "1 TB"}, is_service_management_enabled: true },
// Email Plans Added
"plan-email-std": { categoryId: "cat-email", name: "Standard Email Security", description: "Basic email filtering.", price: 4.00, currency: "CAD", applicableEntityTypes: ["User"], applicableDeviceTypes: null, comparison_attributes: {"Anti-Spam": true, "Anti-Phishing": "Basic", "Archiving": false}, is_service_management_enabled: true },
"plan-email-adv": { categoryId: "cat-email", name: "Advanced Email Security", description: "Enhanced filtering and archiving.", price: 7.00, currency: "CAD", applicableEntityTypes: ["User"], applicableDeviceTypes: null, comparison_attributes: {"Anti-Spam": true, "Anti-Phishing": "Advanced", "Archiving": true}, is_service_management_enabled: true }
},
policies: { // Policy details
"policy-laptop-default": { name: "Default Laptop Policy", description: "Standard security policy for all company laptops." }
},
modalDetails: { // Data for comparison modals
"cat-antivirus": {
categoryDescription: "Protects against viruses, malware, and other threats.",
features: ["Unit Price", "Description", "Real-time Protection", "Scheduled Scans", "Ransomware Rollback"],
plans: { // Example - dynamically generate based on applicable plans
"none": { name: "None", price: 0, currency: "CAD", description: "No protection.", values: ["$0.00/mo CAD", "No protection applied.", false, false, false] },
"plan-av-std": { name: "Standard AV", price: 6.00, currency: "CAD", description: "Core protection.", recommended: true, values: ["$6.00/mo CAD", "Core antivirus...", true, true, false] },
"plan-av-adv": { name: "Advanced AV", price: 12.00, currency: "CAD", description: "Adds rollback.", values: ["$12.00/mo CAD", "Includes Standard...", true, true, true] }
}
},
"cat-endpoint": {
categoryDescription: "Advanced endpoint threat detection and response.",
features: ["Unit Price", "Description", "Threat Hunting", "Incident Response"],
plans: {
"none": { name: "None", price: 0, currency: "CAD", description: "No protection.", values: ["$0.00/mo CAD", "No protection.", false, false] },
"plan-ep-mdr": { name: "Standard MDR", price: 15.00, currency: "CAD", description: "Managed Detection & Response.", recommended: true, values: ["$15.00/mo CAD", "Managed Detection...", true, true] }
}
},
"cat-backup": {
categoryDescription: "Secure cloud backup solutions.",
features: ["Unit Price", "Description", "File Backup", "System Image", "Cloud Storage"],
plans: {
"none": { name: "None", price: 0, currency: "CAD", description: "No backup.", values: ["$0.00/mo CAD", "No backup.", false, false, "0 GB"] },
"plan-bkp-wks": { name: "Workstation Backup", price: 10.00, currency: "CAD", description: "For laptops/desktops.", recommended: true, values: ["$10.00/mo CAD", "Cloud backup...", true, false, "100 GB"] },
"plan-bkp-srv": { name: "Server Backup", price: 50.00, currency: "CAD", description: "For servers.", recommended: true, values: ["$50.00/mo CAD", "Cloud backup...", true, true, "1 TB"] }
}
},
"cat-email": { // Added Email Modal Details
categoryDescription: "Email security and filtering services.",
features: ["Unit Price", "Description", "Anti-Spam", "Anti-Phishing", "Archiving"],
plans: {
"none": { name: "None", price: 0, currency: "CAD", description: "No protection.", values: ["$0.00/mo CAD", "No protection.", false, "None", false] },
"plan-email-std": { name: "Standard Email Security", price: 4.00, currency: "CAD", description: "Basic filtering.", recommended: false, values: ["$4.00/mo CAD", "Basic filtering.", true, "Basic", false] },
"plan-email-adv": { name: "Advanced Email Security", price: 7.00, currency: "CAD", description: "Enhanced filtering and archiving.", recommended: true, values: ["$7.00/mo CAD", "Enhanced filtering...", true, "Advanced", true] }
}
}
}
};
const ORG_DEFAULT_CURRENCY = pageData.organizationDefaults.currency;
const CONVERSION_RATES = { 'CAD': 1.0, 'USD': 1.35 }; // Example conversion rates
// --- Initialization ---
document.addEventListener('DOMContentLoaded', () => {
initializeState();
setupEventListeners();
renderMatrix(currentEntityType); // Initial render based on default tab
updateUIFromState();
// Initialize Tippy tooltips if library is loaded
if (window.tippy && typeof tippy === 'function') {
tippy('[data-tippy-content]', { theme: 'custom', animation: 'fade', allowHTML: true });
} else if (window.tippy) { // Fallback for different Tippy loading
tippy.default('[data-tippy-content]', { theme: 'custom', animation: 'fade', allowHTML: true });
}
});
function initializeState() {
console.log("Initializing state...");
originalState = {};
stagedChanges = {};
const rows = document.querySelectorAll('#matrixTableBody tr[data-entity-id]');
rows.forEach(row => {
const entityId = row.dataset.entityId;
originalState[entityId] = {};
row.querySelectorAll('td[data-category]').forEach(cell => {
const categoryId = cell.dataset.category;
const select = cell.querySelector('select');
const readOnlyAssigned = cell.dataset.assigned;
if (select) {
originalState[entityId][categoryId] = select.value;
} else if (readOnlyAssigned) {
originalState[entityId][categoryId] = readOnlyAssigned;
} else if (cell.classList.contains('cell-disabled') || cell.textContent.trim() === 'N/A') {
originalState[entityId][categoryId] = 'N/A';
} else {
originalState[entityId][categoryId] = 'none';
}
});
});
console.log("Original State Initialized:", JSON.parse(JSON.stringify(originalState)));
}
function setupEventListeners() {
console.log("Setting up event listeners...");
// Tabs - Use IDs assigned in HTML
document.getElementById('tab-devices')?.addEventListener('click', () => switchEntityType('Device'));
document.getElementById('tab-users')?.addEventListener('click', () => switchEntityType('User'));
// Add listener for Overview tab if it needs interaction
// document.querySelector('a[data-w-tab="Overview"]')?.addEventListener('click', () => { /* Handle Overview click */ });
// Filters (Add listeners if these elements exist and have IDs)
document.getElementById('locationFilter')?.addEventListener('change', handleFilterChange);
document.getElementById('deviceTypeFilter')?.addEventListener('change', handleFilterChange);
document.getElementById('groupFilter')?.addEventListener('change', handleFilterChange); // For Users
document.getElementById('searchFilter')?.addEventListener('input', handleFilterChange); // Assuming search input has this ID
// Summary Area Buttons - Use IDs assigned in HTML
document.getElementById('show-service-change-details')?.addEventListener('click', toggleSummaryDetails);
document.getElementById('discardChangesBtn')?.addEventListener('click', confirmDiscardChanges);
document.getElementById('applyChangesBtn')?.addEventListener('click', confirmApplyChanges);
// Event delegation for table body interactions
const tableBody = document.getElementById('matrixTableBody');
if (tableBody) {
// Handle dropdown changes
tableBody.addEventListener('change', (event) => {
if (event.target.tagName === 'SELECT' && !event.target.disabled) {
const cell = event.target.closest('td');
const row = cell?.closest('tr');
if (!cell || !row) return;
const entityId = row.dataset.entityId;
const categoryId = cell.dataset.category;
if(entityId && categoryId) {
stageChange(entityId, categoryId, event.target);
}
}
});
// Handle "Apply to other..." link clicks
tableBody.addEventListener('click', (event) => {
if (event.target.classList.contains('apply-link')) {
event.preventDefault();
stageApplySameClass(event.target);
}
// Handle clicks on info icons (using onclick attribute is simpler for this)
// const infoIcon = event.target.closest('.table-compare-options');
// if (infoIcon && !infoIcon.hasAttribute('onclick')) { ... }
});
}
// Modal Close Buttons
const serviceModal = document.getElementById('serviceComparisonModal');
serviceModal?.querySelector('.modal-close-button')?.addEventListener('click', () => closeModal('serviceComparisonModal'));
serviceModal?.querySelector('.button.w-button')?.addEventListener('click', (e) => { // Assuming 'Close' button
if (e.target.textContent.toLowerCase() === 'close') {
closeModal('serviceComparisonModal');
}
});
const confirmationModal = document.getElementById('confirmationModal');
confirmationModal?.querySelector('#confirmationModalCancelBtn')?.addEventListener('click', () => closeModal('confirmationModal'));
console.log("Event listeners set up.");
}
// --- Core Functions ---
function renderMatrix(entityType) {
console.log(`Rendering matrix for: ${entityType}`);
const tableHead = document.getElementById('matrixTableHead');
const tableBody = document.getElementById('matrixTableBody');
const categories = pageData.visibleCategories[entityType] || []; // Get categories for this view
if (!tableHead || !tableBody) {
console.error("Matrix table head or body not found!");
return;
}
// --- Render Header ---
// Use appropriate header text based on entityType
const entityColumnHeader = entityType === 'Device' ? 'Device' : 'User';
let headerHTML = `<tr class="table-header-row">
<th><div class="table-cell-content"><div class="table-heading">${entityColumnHeader}</div></div></th>`;
categories.forEach(catId => {
const category = pageData.serviceCategories[catId];
if (category) {
headerHTML += `
<th data-category="${catId}"> <div class="table-cell-content">
<div class="table-heading">${category.name}</div>
<a href="#" class="table-compare-options w-inline-block" onclick="openModal('serviceComparisonModal', '${catId}')" title="Compare ${category.name} Options">
<div class="icon _20 w-embed"> <svg fill="currentColor" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 32 32"><path d="M12 6v6H6V6h6m0-2H6a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zM26 6v6h-6V6h6m0-2h-6a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zM12 20v6H6v-6h6m0-2H6a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2v-6a2 2 0 0 0-2-2zM26 20v6h-6v-6h6m0-2h-6a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2v-6a2 2 0 0 0-2-2z"></path></svg>
</div>
</a>
</div>
</th>`;
}
});
headerHTML += `</tr>`;
// Add filter row HTML if it's static in your template, otherwise generate here
tableHead.innerHTML = headerHTML;
// --- Render Body ---
tableBody.innerHTML = ''; // Clear existing rows
const filteredEntities = pageData.entities.filter(e => e.type === entityType); // Filter entities by type
if (filteredEntities.length === 0) {
const row = tableBody.insertRow();
const cell = row.insertCell();
cell.colSpan = categories.length + 1;
cell.innerHTML = `<div class="table-cell-content"><div class="table-data center">No ${entityType}s found matching filters.</div></div>`;
cell.className = 'table-cell'; // Use Webflow class
return;
}
filteredEntities.forEach((entity, index) => {
const row = tableBody.insertRow();
row.className = 'table-row'; // Use Webflow class
if (index === filteredEntities.length - 1) row.classList.add('last-row');
row.dataset.entityId = entity.id;
row.dataset.entityType = entity.deviceType || entity.type;
// Cell 1: Entity Info
const cellInfo = row.insertCell();
cellInfo.className = 'table-cell'; // Use Webflow class
cellInfo.innerHTML = `
<div class="table-cell-content">
<div>
<div><a href="${entity.link || '#'}" class="w-inline-block">${entity.name}</a></div>
<div class="text-small">${entity.details}</div>
</div>
</div>`;
// Subsequent Cells: Service Categories
categories.forEach(catId => {
const cell = row.insertCell();
cell.className = 'table-cell'; // Use Webflow class
cell.dataset.category = catId;
// Add data attributes needed for policy/readonly checks within the helper
const policyId = entity.policyAssignments[catId];
if (policyId) {
cell.dataset.policyAssigned = 'true';
cell.dataset.policyName = pageData.policies[policyId]?.name || 'Unknown Policy';
}
const assignedPlanId = originalState[entity.id]?.[catId]; // Use initial state for render setup
const planDetails = pageData.servicePlans[assignedPlanId];
if (planDetails?.mandatory){
cell.dataset.assigned = assignedPlanId;
cell.dataset.price = planDetails.price;
cell.dataset.currency = planDetails.currency;
}
if (entity.recommendations[catId]){
cell.dataset.recommended = entity.recommendations[catId];
}
cell.innerHTML = createServiceCellHTML(entity, catId); // Generate cell content
});
});
updateUIFromState(); // Update visuals after rendering
}
function createServiceCellHTML(entity, categoryId) {
// --- This function remains the same as the previous version ---
// It determines applicability, checks for mandatory/policy, and generates
// HTML for N/A, read-only, policy-disabled select, or standard select + apply link.
const assignment = originalState[entity.id]?.[categoryId]; // Use original state for initial render setup
const policyId = entity.policyAssignments[categoryId];
const policyDetails = policyId ? pageData.policies[policyId] : null;
const entityDeviceType = entity.deviceType || null;
// Filter applicable plans for this specific entity and category
const applicablePlans = Object.entries(pageData.servicePlans)
.filter(([planId, plan]) =>
plan.is_service_management_enabled && // Check the new flag
planId !== 'none' &&
plan.categoryId === categoryId &&
plan.applicableEntityTypes.includes(entity.type) &&
(!plan.applicableDeviceTypes || !entityDeviceType || plan.applicableDeviceTypes.includes(entityDeviceType))
)
.map(([planId, plan]) => ({ id: planId, ...plan }));
// Is the currently assigned plan mandatory?
const assignedPlan = assignment && assignment !== 'none' && assignment !== 'N/A' ? pageData.servicePlans[assignment] : null;
const isMandatory = assignedPlan?.mandatory === true;
// Is the category generally applicable? (Are there any plans at all?)
// Check if assignment is explicitly N/A from data source (e.g., Server for Endpoint)
const isNotApplicable = assignment === 'N/A';
if (isNotApplicable) {
// Add Webflow classes if needed
return `<div class="table-cell-content cell-disabled"><div class="table-data center wrap-text">N/A</div></div>`;
}
if (isMandatory) {
// Add Webflow classes if needed
return `<div class="table-cell-content cell-readonly">
${assignedPlan.name} - ${formatCurrency(assignedPlan.price, assignedPlan.currency)}/mo
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block w-4 h-4 text-gray-400 ml-1"><rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
</div>`;
}
if (policyDetails) {
const currentPlan = assignedPlan || pageData.servicePlans['none'];
// Add Webflow classes: service-selection-cell, dropdown, dropdown-closed, table-filter etc.
return `<div class="service-selection-cell"> <select class="dropdown-closed table-filter" disabled> <option value="${assignment || 'none'}" data-price="${currentPlan.price}" data-currency="${currentPlan.currency}" selected>${currentPlan.name} - ${formatCurrency(currentPlan.price, currentPlan.currency)}/mo</option>
</select>
<span class="policy-indicator" title="Assigned by: ${policyDetails.name}" data-tippy-content="Assigned by: ${policyDetails.name}">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline-block w-4 h-4"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="m9 12 2 2 4-4"/></svg>
</span>
</div>`;
}
// --- Standard Dropdown ---
const allowNone = !applicablePlans.some(p => p.mandatory);
let optionsHTML = '';
if (allowNone) {
const nonePlan = pageData.servicePlans['none'];
optionsHTML += `<option value="none" data-price="${nonePlan.price}" data-currency="${nonePlan.currency}" ${assignment === 'none' || !assignment ? 'selected' : ''}>${nonePlan.name} - ${formatCurrency(nonePlan.price, nonePlan.currency)}/mo</option>`;
}
applicablePlans.forEach(plan => {
// TODO: Implement dynamic pricing
const displayPrice = plan.price;
const displayCurrency = plan.currency;
optionsHTML += `<option value="${plan.id}" data-price="${displayPrice}" data-currency="${displayCurrency}" ${assignment === plan.id ? 'selected' : ''}>${plan.name} - ${formatCurrency(displayPrice, displayCurrency)}/mo</option>`;
});
if (assignment && assignment !== 'none' && !applicablePlans.some(p => p.id === assignment) && !assignedPlan?.mandatory) {
optionsHTML += `<option value="${assignment}" data-price="${assignedPlan?.price || 0}" data-currency="${assignedPlan?.currency || ORG_DEFAULT_CURRENCY}" selected disabled>${assignedPlan?.name || assignment} (Legacy) - ${formatCurrency(assignedPlan?.price || 0, assignedPlan?.currency || ORG_DEFAULT_CURRENCY)}/mo</option>`;
}
if (!optionsHTML && allowNone) { // If only 'None' was possible but no other plans
const nonePlan = pageData.servicePlans['none'];
optionsHTML += `<option value="none" data-price="${nonePlan.price}" data-currency="${nonePlan.currency}" selected>${nonePlan.name} - ${formatCurrency(nonePlan.price, nonePlan.currency)}/mo</option>`;
} else if (!optionsHTML && !allowNone) { // No applicable plans and None not allowed -> treat as N/A
return `<div class="table-cell-content cell-disabled"><div class="table-data center wrap-text">N/A</div></div>`;
}
// Add Webflow classes: service-selection-cell, dropdown, dropdown-closed, table-filter etc.
return `<div class="service-selection-cell"> <select id="serviceSelect-${entity.id}-${categoryId}" class="dropdown-closed table-filter"> ${optionsHTML}
</select>
<a href="#" class="apply-link hidden" onclick="stageApplySameClass(this)">Apply to other ${entity.deviceType || entity.type}s</a>
</div>`;
}
function updateCellVisuals() {
// --- This function remains the same as the previous version ---
// It adds/removes 'cell-staged' border and 'bg-rec-*' background classes
// to the <td> elements based on stagedChanges and recommendations.
// It also toggles the visibility of the '.apply-link'.
const rows = document.querySelectorAll('#matrixTableBody tr[data-entity-id]');
rows.forEach(row => {
const entityId = row.dataset.entityId;
row.querySelectorAll('td[data-category]').forEach(cell => {
const categoryId = cell.dataset.category;
const isStaged = stagedChanges[entityId]?.[categoryId]?.isStaged;
const currentServiceId = getCurrentServiceId(entityId, categoryId);
const recommendedServiceId = cell.dataset.recommended;
const isPolicyAssigned = cell.dataset.policyAssigned === 'true';
const isReadOnly = cell.classList.contains('cell-readonly');
const isDisabled = cell.classList.contains('cell-disabled');
cell.classList.remove('cell-staged', 'bg-rec-match', 'bg-rec-none', 'bg-rec-differs');
cell.style.backgroundColor = '';
if (isStaged) cell.classList.add('cell-staged');
if (!isDisabled && !isReadOnly) {
if (currentServiceId === 'none') cell.classList.add('bg-rec-none');
else if (recommendedServiceId && currentServiceId === recommendedServiceId) cell.classList.add('bg-rec-match');
else if (currentServiceId !== 'none' && recommendedServiceId && currentServiceId !== recommendedServiceId) cell.classList.add('bg-rec-differs');
} else if (isReadOnly) {
const originalService = originalState[entityId]?.[categoryId];
if (originalService === 'none') cell.classList.add('bg-rec-none');
else if (recommendedServiceId && originalService === recommendedServiceId) cell.classList.add('bg-rec-match');
else if (recommendedServiceId && originalService !== recommendedServiceId) cell.classList.add('bg-rec-differs');
}
const applyLink = cell.querySelector('.apply-link');
if (applyLink) {
const selectElement = cell.querySelector('select');
if (isStaged && selectElement && selectElement.value !== 'none' && !isPolicyAssigned) {
const entityTypeDisplay = row.dataset.entityType || 'Items';
applyLink.textContent = `Apply to other ${entityTypeDisplay}s`;
applyLink.classList.remove('hidden');
} else {
applyLink.classList.add('hidden');
}
}
});
});
}
function updateSummaryArea() {
// --- Updated to filter by currentEntityType ---
const summaryBody = document.getElementById('summaryChangesTableBody');
const prevTotalEl = document.getElementById('summaryPrevTotalCost');
const newTotalEl = document.getElementById('summaryNewTotalCost');
const totalChangeEl = document.getElementById('device_total_cost_changes'); // Use user ID
if (!summaryBody || !prevTotalEl || !newTotalEl || !totalChangeEl) {
console.error("Summary area elements not found! Cannot update.");
return;
}
summaryBody.innerHTML = '';
let overallPrevCost = 0, overallNewCost = 0;
const summaryData = {};
Object.keys(originalState).forEach(entityId => {
// *** ADDED FILTER: Only include entities matching the current view type ***
const entityData = pageData.entities.find(e => e.id === entityId); // Find entity data to check its type
if (!entityData || entityData.type !== currentEntityType) {
return; // Skip entities not matching the current tab view
}
// *** END ADDED FILTER ***
Object.keys(originalState[entityId]).forEach(categoryId => {
// Only consider categories visible for the current entity type
if (!pageData.visibleCategories[currentEntityType]?.includes(categoryId)) return;
const originalPlanId = originalState[entityId][categoryId];
const stagedData = stagedChanges[entityId]?.[categoryId];
const currentPlanId = stagedData?.isStaged ? stagedData.newPlanId : originalPlanId;
// Get price data based on current/original state
const originalPlanData = getServiceDataForState(entityId, categoryId, false); // Get original data
const currentPlanData = getServiceDataForState(entityId, categoryId, true); // Get current/staged data
const originalCostCAD = convertToOrgCurrency(originalPlanData.price, originalPlanData.currency);
const currentCostCAD = convertToOrgCurrency(currentPlanData.price, currentPlanData.currency);
overallPrevCost += originalCostCAD;
overallNewCost += currentCostCAD;
// Aggregate previous state
if (originalPlanId && originalPlanId !== 'none' && originalPlanId !== 'N/A') {
if (!summaryData[originalPlanId]) summaryData[originalPlanId] = { name: getServiceName(originalPlanId, entityId, categoryId), prevQty: 0, newQty: 0, prevCost: 0, newCost: 0, unitPrice: originalPlanData.price, currency: originalPlanData.currency };
summaryData[originalPlanId].prevQty++;
summaryData[originalPlanId].prevCost += originalCostCAD;
}
// Aggregate current state
if (currentPlanId && currentPlanId !== 'none' && currentPlanId !== 'N/A') {
if (!summaryData[currentPlanId]) summaryData[currentPlanId] = { name: getServiceName(currentPlanId, entityId, categoryId), prevQty: 0, newQty: 0, prevCost: 0, newCost: 0, unitPrice: currentPlanData.price, currency: currentPlanData.currency };
summaryData[currentPlanId].newQty++;
summaryData[currentPlanId].newCost += currentCostCAD;
}
});
});
// --- Populate summary table (same as before) ---
let hasChanges = false;
Object.values(summaryData).forEach(data => {
if (data.prevQty !== data.newQty || data.prevCost !== data.newCost) {
hasChanges = true;
const row = summaryBody.insertRow();
row.className = 'table-row';
const monthlyChange = data.newCost - data.prevCost;
// Using user's table structure
row.innerHTML = `
<td class="table-cell"><div class="table-cell-content"><div class="table-data">${data.name}</div></div></td>
<td class="table-cell"><div class="table-cell-content"><div class="table-data center">${data.prevQty}</div></div></td>
<td class="table-cell ${data.prevQty !== data.newQty ? 'highlight-change' : ''}"><div class="table-cell-content"><div class="table-data center">${data.newQty}</div></div></td>
<td class="table-cell"><div class="table-cell-content"><div class="table-data right">${formatCurrency(data.unitPrice, data.currency)}</div></div></td>
<td class="table-cell"><div class="table-cell-content"><div class="table-data right">${formatCurrency(data.prevCost, ORG_DEFAULT_CURRENCY)}</div></div></td>
<td class="table-cell ${data.prevCost !== data.newCost ? 'highlight-change' : ''}"><div class="table-cell-content"><div class="table-data right">${formatCurrency(data.newCost, ORG_DEFAULT_CURRENCY)}</div></div></td>
<td class="table-cell ${monthlyChange !== 0 ? 'highlight-change' : ''}"><div class="table-cell-content"><div class="table-data right ${monthlyChange > 0 ? 'success-text' : monthlyChange < 0 ? 'danger-text' : ''}">${monthlyChange >= 0 ? '+' : ''}${formatCurrency(monthlyChange, ORG_DEFAULT_CURRENCY)}</div></div></td>
`;
}
});
if (!hasChanges && Object.keys(stagedChanges).length === 0) {
summaryBody.innerHTML = '<tr><td colspan="7" class="table-cell"><div class="table-cell-content"><div class="table-data center text-gray-500 py-4">No changes staged yet.</div></div></td></tr>';
}
// --- Update overall totals (same as before) ---
const totalChange = overallNewCost - overallPrevCost;
prevTotalEl.textContent = formatCurrency(overallPrevCost, ORG_DEFAULT_CURRENCY);
newTotalEl.textContent = formatCurrency(overallNewCost, ORG_DEFAULT_CURRENCY);
totalChangeEl.textContent = `${totalChange >= 0 ? '+' : ''}${formatCurrency(totalChange, ORG_DEFAULT_CURRENCY)}`;
totalChangeEl.className = `text-span-3 ${totalChange > 0 ? 'success-text' : totalChange < 0 ? 'danger-text' : ''}`;
updateActionButtons();
}
// --- Helper to get service data for original or current/staged state ---
function getServiceDataForState(entityId, categoryId, useCurrentStaged) {
const planId = useCurrentStaged ? getCurrentServiceId(entityId, categoryId) : originalState[entityId]?.[categoryId];
const stagedData = stagedChanges[entityId]?.[categoryId];
// If using current/staged and it IS staged, use staged price info
if (useCurrentStaged && stagedData?.isStaged) {
return { serviceId: stagedData.newPlanId, price: stagedData.newPrice, currency: stagedData.currency };
}
// Otherwise (using original state, OR using current state but it's NOT staged), get data based on planId
const plan = pageData.servicePlans[planId];
if (plan) {
// TODO: Incorporate override price logic here if needed for original state display?
// Currently assumes original state uses base/calculated price.
return { serviceId: planId, price: plan.price, currency: plan.currency };
}
// Fallback for 'N/A' or 'none' or missing plan
return { serviceId: planId || 'N/A', price: 0, currency: ORG_DEFAULT_CURRENCY };
}
// --- Other functions (updateActionButtons, updatePaginationCounts, stageChange, stageApplySameClass, clearStagedChanges, confirm*, applyChanges, toggleSummaryDetails, openModal, closeModal, populateComparisonModal, showConfirmation, getCurrent*, convert*, format*, getServiceName*)
// --- remain largely the same as the previous version, ensuring they use the correct IDs and handle select elements where needed.
// --- Include FULL implementations of all remaining functions here ---
// (Copy from previous complete JS versions, ensuring correct IDs and logic)
function updateActionButtons() {
const hasStagedChanges = Object.keys(stagedChanges).length > 0;
document.getElementById('applyChangesBtn').disabled = !hasStagedChanges;
document.getElementById('discardChangesBtn').disabled = !hasStagedChanges;
}
function updatePaginationCounts() {
const visibleRows = document.querySelectorAll('#matrixTableBody tr[data-entity-id]:not([style*="display: none"])');
const currentEntityType = document.getElementById('entityColumnHeader')?.textContent || currentEntityType;
let totalFilteredCount = 0;
Object.keys(originalState).forEach(entityId => {
const entity = pageData.entities.find(e => e.id === entityId);
if (entity && entity.type === currentEntityType) {
totalFilteredCount++;
}
});
const paginationEndEl = document.getElementById('pagination-end'); // Assumes this ID exists
const paginationTotalEl = document.getElementById('pagination-total'); // Assumes this ID exists
const paginationTextEl = document.querySelector('.paginaton-total-items div'); // Use selector from user HTML
if(paginationEndEl) paginationEndEl.textContent = visibleRows.length;
if(paginationTotalEl) paginationTotalEl.textContent = totalFilteredCount;
if (paginationTextEl) {
paginationTextEl.textContent = `${totalFilteredCount > 0 ? 1 : 0}–${visibleRows.length} of ${totalFilteredCount} items`;
}
}
function clearStagedChanges(prompt = true) {
if (prompt && Object.keys(stagedChanges).length > 0 && !confirm("Are you sure you want to discard all unsaved changes?")) return;
console.log("Discarding changes...");
stagedChanges = {};
Object.keys(originalState).forEach(entityId => {
const row = document.querySelector(`#matrixTableBody tr[data-entity-id='${entityId}']`);
if (!row) return;
Object.keys(originalState[entityId]).forEach(categoryId => {
const originalPlanId = originalState[entityId][categoryId];
const cell = row.querySelector(`td[data-category='${categoryId}']`);
const selectElement = cell?.querySelector('select');
if (selectElement && !selectElement.disabled) {
selectElement.value = originalPlanId;
}
});
});
document.getElementById('service-change-details')?.classList.add('hidden');
document.getElementById('show-service-change-details')?.textContent = 'Show Details';
document.querySelectorAll('.apply-link').forEach(link => link.classList.add('hidden'));
updateUIFromState();
console.log("Changes discarded.");
}
function confirmDiscardChanges() {
showConfirmation("Discard Changes", "Are you sure you want to discard all unsaved changes?", () => clearStagedChanges(false));
}
function confirmApplyChanges() {
const changeCount = Object.keys(stagedChanges).reduce((count, entityId) => count + Object.keys(stagedChanges[entityId]).length, 0);
const totalChangeSpan = document.getElementById('device_total_cost_changes');
const totalChangeString = totalChangeSpan ? totalChangeSpan.textContent : '$0.00';
showConfirmation("Apply Changes", `Apply ${changeCount} staged change(s) with a total monthly cost impact of ${totalChangeString}?`, applyChanges);
}
function applyChanges() {
console.log("Applying changes (mock)...", JSON.parse(JSON.stringify(stagedChanges)));
const changeCount = Object.keys(stagedChanges).length;
alert(`Mockup: Applied changes for ${changeCount} entities successfully!`);
Object.keys(stagedChanges).forEach(entityId => {
if (originalState[entityId]) {
Object.keys(stagedChanges[entityId]).forEach(categoryId => {
const change = stagedChanges[entityId][categoryId];
if (originalState[entityId][categoryId] !== undefined) {
originalState[entityId][categoryId] = change.newPlanId;
}
});
}
});
stagedChanges = {};
document.getElementById('service-change-details')?.classList.add('hidden');
document.getElementById('show-service-change-details')?.textContent = 'Show Details';
document.querySelectorAll('.apply-link').forEach(link => link.classList.add('hidden'));
updateUIFromState();
console.log("Changes applied and state updated.");
console.log("New Original State:", originalState);
}
function toggleSummaryDetails() {
const detailsDiv = document.getElementById('service-change-details');
const toggleBtn = document.getElementById('show-service-change-details');
if (!detailsDiv || !toggleBtn) return;
detailsDiv.classList.toggle('hidden');
toggleBtn.textContent = detailsDiv.classList.contains('hidden') ? 'Show Details' : 'Hide Details';
}
function openModal(modalId, categoryId = null) {
console.log(`Opening modal: ${modalId}, Category: ${categoryId}`);
const modal = document.getElementById(modalId);
if (!modal) { console.error(`Modal with ID ${modalId} not found.`); return; }
if (modalId === 'serviceComparisonModal' && categoryId) {
populateComparisonModal(categoryId);
}
modal.style.display = 'block'; // Use 'block' or 'flex' depending on modal CSS
}
function closeModal(modalId) {
const modal = document.getElementById(modalId);
if (modal) {
modal.style.display = 'none';
}
}
function showConfirmation(title, text, onConfirmCallback) {
const modal = document.getElementById('confirmationModal');
const titleEl = document.getElementById('confirmationModalTitle');
const textEl = document.getElementById('confirmationModalText');
const confirmBtn = document.getElementById('confirmationModalConfirmBtn');
if (!modal || !titleEl || !textEl || !confirmBtn) {
console.error("Confirmation modal elements not found! Using basic confirm.");
if (confirm(text)) { onConfirmCallback(); }
return;
}
titleEl.textContent = title;
textEl.textContent = text;
const newConfirmBtn = confirmBtn.cloneNode(true);
confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
newConfirmBtn.onclick = () => { onConfirmCallback(); closeModal('confirmationModal'); };
openModal('confirmationModal');
}
window.onclick = (event) => {
// Close modals on background click
const serviceModal = document.getElementById('serviceComparisonModal');
const confirmModal = document.getElementById('confirmationModal');
if (event.target == serviceModal || event.target == confirmModal) {
closeModal(event.target.id);
}
}
function getCurrentServiceId(entityId, categoryId) {
if (stagedChanges[entityId]?.[categoryId]?.isStaged) {
return stagedChanges[entityId][categoryId].newPlanId;
}
const cell = document.querySelector(`tr[data-entity-id='${entityId}'] td[data-category='${categoryId}']`);
const selectElement = cell?.querySelector('select');
if (selectElement) {
return selectElement.value;
}
return originalState[entityId]?.[categoryId] ?? 'N/A';
}
function convertToOrgCurrency(price, currency) {
const rate = CONVERSION_RATES[currency] || 1.0;
return (price * rate);
}
function formatCurrency(value, currencyCode) {
return `${currencyCode === 'USD' ? '$' : '$'}${Number(value || 0).toFixed(2)} ${currencyCode}`;
}
function getServiceName(planId, entityId, categoryId) {
if (!planId || planId === 'none' || planId === 'N/A') return 'None';
const plan = pageData.servicePlans[planId];
if (plan) return plan.name;
const cell = document.querySelector(`tr[data-entity-id='${entityId}'] td[data-category='${categoryId}']`);
const option = cell?.querySelector(`select option[value='${planId}']`);
if (option) { return option.textContent.split('-')[0].trim(); }
const readOnlyCell = document.querySelector(`tr[data-entity-id='${entityId}'] td.cell-readonly[data-category='${categoryId}'][data-assigned='${planId}']`);
if(readOnlyCell) { return readOnlyCell.textContent.split('-')[0].trim(); }
return planId;
}Backend Logic, API, & Required IDs
This document outlines the backend logic, data processing requirements, necessary API endpoints, and required HTML element IDs to support the Services Management user interface.
1. Introduction & Goal
The primary goal of this feature is to allow authorized client administrators to view, manage, and apply contracted service assignments to their organization's Devices and Users efficiently, while understanding recommendations, policy impacts, and cost implications.
2. UI Components & Expected Behavior (Summary)
- Filters: Allow users to scope the view by Entity Type (Devices/Users), Location (hierarchical), Device Type (if Devices selected), Group/Team (if Users selected), and free-text search. Applying filters refreshes the main matrix and resets any pending (staged) changes.
- Tabs: Switch between "Overview", "Devices", and "Users" views. The "Overview" tab provides high-level summaries, while "Devices" and "Users" show the detailed management matrix.
- Management Matrix:
- Displays filtered entities (Devices or Users) as rows.
- Displays applicable service categories (derived from Products.category where is_service_management_enabled=true and available via AgreementAdditions) as columns.
- Cells contain dropdowns (<select>) for selecting service plans (Products).
- Dropdowns list applicable plans for the specific entity/category, including price. A "None" option is available unless a mandatory service applies.
- Cells are visually styled based on the selected plan's alignment with recommendations (Green: Match, Amber: Differs, Red: None).
- Policy-assigned cells show a disabled dropdown and a policy indicator icon with a tooltip showing the policy name.
- Cells representing mandatory services (e.g., Products.is_mandatory=true) show read-only text and a lock icon.
- Cells where a category doesn't apply to the entity type show "N/A".
- Changing a dropdown stages the change (doesn't save immediately) and highlights the cell border (cell-staged).
- An "Apply to other [Type]s" link appears below a dropdown after a change is staged (excluding "None" or policy assignments).
- Collapsible Summary Bar:
- Fixed at the bottom of the viewport.
- Collapsed View: Shows "Review Proposed Changes" title, the calculated Total Monthly Change (cost difference between original and staged states), a "Show/Hide Details" toggle, and "Discard"/"Apply" buttons (disabled initially).
- Expanded View: Reveals a detailed table comparing Previous vs. New Quantities and Costs for each affected service plan across the entire filtered entity set, plus an overall totals box (Previous Total Cost, New Total Cost).
- Modals:
- Service Comparison Modal: Triggered by info icons in matrix headers. Shows a comparison table of features (from Products.comparison_attributes) for applicable plans within that category, highlighting the recommended plan.
- Confirmation Modal: Used for Apply, Discard, and potentially Apply to Same Class actions.
3. Required HTML Element IDs (for JavaScript Functionality)
The accompanying JavaScript (service_management_full_js_v2) relies on specific id attributes being present on certain HTML elements to function correctly. Please ensure the following IDs are added to your HTML structure:
- Tabs:
- tab-devices: On the clickable element (e.g., <a>) for the "Devices" tab.
- tab-users: On the clickable element (e.g., <a>) for the "Users" tab.
- (Optional) entityTypeTabs: On the container holding the tab links (e.g., .tabs-menu) if needed for advanced styling/logic.
- Filters (Example IDs - adjust if necessary):
- locationFilter: On the <select> element for location filtering.
- deviceTypeFilter: On the <select> element for device type filtering.
- groupFilter: On the <select> element for group/team filtering (if applicable for Users).
- searchFilter: On the <input type="text"> element for free-text search.
- Matrix Table:
- matrixTableHead: On the <thead> element of the main matrix table.
- matrixTableBody: On the <tbody> element of the main matrix table.
- entityColumnHeader: On the <span> or <div> inside the first header cell (<th>) whose text should change between "Device" and "User".
- (Note: Individual rows <tr>, cells <td>, and dropdowns <select> do not need unique IDs, but rows require data-entity-id and data-entity-type, and cells require data-category attributes as described in the data model.)
- Summary Area (Bottom Bar):
- device_total_cost_changes: On the <span> element displaying the calculated "Total Change: +/- $X.XX". (Using ID from your HTML snippet).
- show-service-change-details: On the <button> or <a> element used to toggle the details view. (Using ID from your HTML snippet).
- service-change-details: On the <div> container holding the collapsible content (the detailed changes table and the overall totals box). (Using ID from your HTML snippet).
- summaryChangesTableBody: On the <tbody> element of the detailed changes table inside service-change-details.
- summaryOverallTotalsContainer: On the container (e.g., <div> or <table>) holding the Previous/New Total cost display inside service-change-details.
- summaryPrevTotalCost: On the <span> or <td> displaying the "Previous Total Monthly Cost" value inside summaryOverallTotalsContainer.
- summaryNewTotalCost: On the <span> or <td> displaying the "Proposed New Total Monthly Cost" value inside summaryOverallTotalsContainer.
- discardChangesBtn: On the "Discard" <button> or <a>.
- applyChangesBtn: On the "Apply" <button> or <a>.
- Modals:
- serviceComparisonModal: On the main container element for the Service Comparison modal (e.g., .modal-background or .modal-container).
- serviceComparisonModalTitle: On the <h1> or <h2> element displaying the modal's title.
- serviceComparisonModalTableHead: On the <thead> element of the comparison table inside the modal.
- serviceComparisonModalTableBody: On the <tbody> element of the comparison table inside the modal.
- (Ensure modal close buttons have onclick="closeModal('serviceComparisonModal')" or equivalent event listeners)
- confirmationModal: On the main container element for the generic confirmation modal.
- confirmationModalTitle: On the <h1> or <h2> element for the confirmation title.
- confirmationModalText: On the <p> element displaying the confirmation message.
- confirmationModalConfirmBtn: On the "Confirm" button inside the confirmation modal.
- confirmationModalCancelBtn: On the "Cancel" button inside the confirmation modal (should have onclick="closeModal('confirmationModal')").
- Pagination (Optional - JS currently only reads counts):
- pagination-end: On the <span> showing the end number of items displayed (e.g., the '10' in "1-10 of 103").
- pagination-total: On the <span> showing the total number of items (e.g., the '103' in "1-10 of 103").
- (The main pagination text 1-X of Y items can be targeted via its parent container class if needed, e.g., .paginaton-total-items div)
4. Backend Logic - Data Preparation (for Matrix Rendering)
To populate the matrix for a given client org_id and applied filters, the backend must perform these steps:
- Identify Client & Agreement: Determine the active Agreements for the client org_id.
- Filter Entities: Fetch Devices or Users matching the client org_id and the active UI filters (Location, Type/Group, Search). Apply pagination.
- Determine Visible Categories:
- Query Products joined with AgreementAdditions (for the client's active agreements).
- Filter where Products.product_type = 'Service' AND Products.is_service_management_enabled = true.
- Filter where Products.applicable_entity_types contains the selected currentEntityType ('Device' or 'User').
- Get the DISTINCT Products.category values. These form the matrix columns. Store category names/IDs.
- Process Each Entity (for the current page): For each Device/User record:
- Fetch Current Assignments: Query DeviceServiceAssignments or UserServiceAssignments for this entity_id and the visible service_category_ids. Store the assigned_product_id, assignment_method, policy_assignment_source_ref, override_price, override_currency_code.
- Fetch Recommendations: Query ServiceRecommendations based on the entity's context (Org, Location, DeviceType, Tags potentially linked to User Groups) for visible categories. Determine the highest priority recommended_product_id for each category.
- Fetch Applicable Plans & Pricing: For each visible category:
- Query Products again, filtering by category, product_type='Service', is_service_management_enabled=true, applicable_entity_types, and applicable_device_types (matching the specific entity's type).
- Further filter these products based on whether they exist in the client's AgreementAdditions.
- For each resulting applicable plan (Product):
- Calculate Price: Determine the final price using the hierarchy:
- Check Device/UserServiceAssignments.override_price for the current assignment (if any).
- Check AgreementAdditions.unit_price_override for this product/agreement.
- Evaluate PricingRules based on Location -> Agreement -> Org -> MSP hierarchy.
- Use Products.unit_price as the base.
- Determine the correct currency_code.
- Fetch Policy Details: If policy_assignment_source_ref is present, fetch the corresponding policy name (e.g., from Tags or other policy tables) for the tooltip.
- Assemble Frontend Data: Construct the JSON payload (similar to pageData example) containing:
- Filtered entity list with their details, current assignments, recommendations, and policy info.
- List of visible service categories (column headers).
- List of all potentially applicable service plans (for dropdowns) with their calculated price/currency for the context (though price might be better calculated per-cell if highly variable).
- Data for modalDetails.
- organizationDefaults.
- Pagination metadata (total items, total pages).
- Initial summary calculation results (Prev QTY/Cost, New QTY/Cost, Totals) based only on the current DB state (no staged changes yet).
5. Backend Logic - Handling Actions
- Apply Staged Changes:
- Receives a batch of changes from the frontend (e.g., [{ entityId: 'dev-001', categoryId: 'cat-antivirus', newPlanId: 'plan-av-adv' }, ...]).
- For each change item:
- Validate the change (e.g., is the plan applicable? is the entity still valid?).
- Determine the correct assignment_method ('Manual').
- Find the existing record in DeviceServiceAssignments or UserServiceAssignments for the entityId and categoryId.
- If newPlanId is 'none' or null:
- If a record exists, DELETE it or set assigned_product_id = NULL.
- If newPlanId is a valid product ID:
- If a record exists, UPDATE assigned_product_id, assignment_method (to 'Manual'), assigned_by_user_id, updated_at, and clear policy_assignment_source_ref, override_price, override_currency_code.
- If no record exists, INSERT a new record with the details.
- Perform all updates within a transaction.
- Log the changes in AuditLog.
- Trigger any necessary downstream events (e.g., billing updates, agent commands).
- Return success/failure status to the frontend.
- Calculate Summary Data:
- This calculation powers the bottom summary bar and needs to reflect the entire filtered set of entities, not just the current page displayed in the matrix.
- The backend needs to:
- Get the list of all entity IDs matching the current filters (ignoring pagination).
- Fetch the originalState (current assignments) for all these entities from Device/UserServiceAssignments.
- Receive the stagedChanges object from the frontend (or recalculate based on request if staging happens server-side).
- Iterate through all filtered entities:
- Determine the 'previous' assigned plan (from originalState).
- Determine the 'new' assigned plan (from stagedChanges if present, otherwise from originalState).
- Calculate the 'previous' price for the original plan (using the full pricing logic).
- Calculate the 'new' price for the new plan (using the full pricing logic, considering potential override_price from staging data if applicable).
- Convert both prices to the organization's default currency.
- Aggregate these previous/new costs and quantities per product_id across all filtered entities.
- Calculate the overall previous total, new total, and total change.
- Return this aggregated data to the frontend to populate the summary bar (both collapsed and expanded views).
- Performance Note: Calculating this summary across potentially thousands of entities on every staged change can be expensive. Consider:
- Calculating only when the summary details are expanded.
- Performing calculations asynchronously.
- Optimizing database queries heavily.
- Handling "Apply to Same Class":
- The frontend identifies the source entity, selected plan, and entity type.
- The frontend finds other visible entities of the same type.
- The frontend stages the changes locally in its stagedChanges object.
- The backend only gets involved when the main "Apply Changes" button is clicked, processing the bulk changes as described above. (Alternatively, a dedicated backend endpoint could perform the staging if frontend state management is too complex).
6. API Endpoint Requirements (Conceptual)
- GET /api/v1/orgs/{orgId}/services/management
- Purpose: Fetch initial data to render the matrix and summary.
- Query Params: entityType (Device/User), locationFilter, deviceTypeFilter, groupFilter, search, page, pageSize.
- Response Body: JSON object similar to pageData, containing:
- Paginated list of entities matching filters, including their current assignments, recommendations, policy info.
- List of visibleCategories for the columns.
- Details of applicable servicePlans (including calculated price for the context).
- Data for modalDetails.
- organizationDefaults.
- Pagination metadata (total items, total pages).
- Initial summary calculation results (Prev QTY/Cost, New QTY/Cost, Totals) based only on the current DB state (no staged changes yet).
- POST /api/v1/orgs/{orgId}/services/assignments/apply
- Purpose: Apply a batch of staged changes.
- Request Body: Array of change objects: [{ entityId, entityType, categoryId, newPlanId, overridePrice?, overrideCurrency? }, ...].
- Response Body: Success/failure status, potentially updated summary totals, or error details.
- POST /api/v1/orgs/{orgId}/services/summary (Optional/Alternative)
- Purpose: Recalculate the summary bar data based on current filters and provided staged changes (useful if frontend cannot reliably calculate across all filtered entities).
- Request Body: { filters: { ... }, stagedChanges: { ... } }
- Response Body: JSON object with aggregated summary data (Prev/New QTY/Cost per service, Overall Totals).
- GET /api/v1/orgs/{orgId}/services/categories/{categoryId}/comparison (Optional)
- Purpose: Fetch data specifically for the comparison modal.
- Query Params: entityType (Device/User), deviceType (optional).
- Response Body: JSON object for the specific category's modalDetails. (Alternatively, include all modal data in the initial page load).
7. Key Considerations
- Permissions (RBAC): Implement strict checks based on UserRoleAssignments and RolePermissions:
- Who can view the Services Management page?
- Who can stage changes (modify dropdowns)?
- Who can click "Apply Changes"? (This might be a more restricted permission).
- Filtering should also respect user scope (e.g., only show locations/devices the user manages).
- Performance: The summary calculation across all filtered entities is the main performance concern. Optimize database queries, consider caching, and potentially use asynchronous calculation or calculate only on demand (when details expanded or Apply clicked). Indexing relevant database columns is crucial.
- Error Handling: Provide clear feedback for API errors, calculation failures, or partial successes during batch updates.
- Conflict Resolution: Define how conflicting recommendations or policies are resolved (likely based on priority fields). Ensure the backend consistently applies the highest priority rule.
- Auditing: Log all assignment changes (manual or applied batch) in AuditLog, including who made the change, when, and the previous/new state.
Database Schema & Logic
This document details how the database schema supports the Services Management page, including data flow, key table roles, and logic for core features.
1. Purpose of the Feature
The Services Management screen allows authorized client administrators to view, assign, and manage specific contracted services (represented as Products) to Devices and Users within their organization. It highlights recommended configurations, shows policy-driven assignments, and provides a summary of quantity and cost changes before applying them.
2. Core Data Model & Key Tables
The functionality relies on the interplay of several tables:
- Organizations: Defines the client organization and potentially the managing MSP. Holds defaults like currency and links to default pricing/agreements.
- Locations: Defines client sites, which can have specific pricing rules.
- Devices: Represents the physical or virtual devices being managed. Key column: device_type.
- Users: Represents the users being managed.
- Products: The central catalog containing hardware, software, and crucially, service definitions.
- product_type = 'Service' identifies service items.
- is_service_management_enabled = true flags services manageable on this screen.
- category groups services (e.g., 'Antivirus', 'Backup') and defines the matrix columns.
- applicable_entity_types, applicable_device_types define target scope.
- comparison_attributes stores data for the comparison modal.
- is_mandatory flags services that cannot be unassigned ('None' not allowed).
- unit_price, default_currency_code provide base pricing.
- Agreements: Defines the contract between the MSP and the client. Can link to specific Rate Sheets, Pricing Rule Sets, etc.
- AgreementAdditions: Links specific Products (including services) to an Agreement, making them available to the client, potentially with quantity limits or price overrides.
- DeviceServiceAssignments (New): Tracks the current assignment of a specific service Product to a specific Device for a given service category. Stores override prices and assignment method (Manual/Policy).
- UserServiceAssignments (New): Tracks the current assignment of a specific service Product to a specific User for a given service category.
- ServiceRecommendations (New): Stores rules defining the recommended service Product for different scopes (Org, Location, DeviceType, etc.) within a category. Drives UI highlighting.
- PricingRuleSets / PricingRules: Define complex pricing adjustments based on various criteria (Org, Location, Product, etc.). Referenced by Organizations, Locations, Agreements.
- Tags / DeviceTags / UserTags: Used for grouping entities.
- Policy Tables (e.g., TagCompliancePolicyAssignments, TagPatchPolicyAssignments, etc.): These existing tables (or similar ones defining service policies) are referenced via policy_assignment_source_ref in the assignment tables to indicate why an assignment is policy-driven.
3. Defining Services and Categories (Groups)
- Service Definition: A record in the Products table with product_type = 'Service' and is_service_management_enabled = true.
- Category Definition: The value in the Products.category column for these service products defines the category (e.g., 'Antivirus', 'Backup'). Distinct categories applicable to the client (via AgreementAdditions) and the selected entity type become the columns in the UI matrix.
4. Determining Applicability
- Entity Type (Device/User): The Products.applicable_entity_types array (e.g., {'Device', 'User'}) determines if a service product can fundamentally be assigned to a device or a user. The backend filters products based on the selected UI tab (Devices or Users).
- Device Type: For devices, the Products.applicable_device_types array (e.g., {'Laptop', 'Workstation'}) further restricts applicability. If the array is NULL, it applies to all device types matching the applicable_entity_types. The backend filters dropdown options based on the Devices.device_type of the specific row.
- Agreement: A service product must typically be linked to the client's active Agreements via the AgreementAdditions table to be considered available for assignment on this screen.
5. Tracking Assignments (Manual vs. Policy)
- Core Tables: DeviceServiceAssignments and UserServiceAssignments are the source of truth for the current state.
- assigned_product_id: This column holds the product_id of the currently assigned service plan. If it's NULL, it means "None" is assigned for that service_category_id.
- assignment_method: Indicates how the assignment was set:
- 'Manual': Set directly by a user via this screen.
- 'Policy': Set automatically based on a policy (e.g., linked via Tags). The UI dropdown should be disabled.
- 'Default': Assigned automatically as a default (e.g., based on Org settings), potentially overridable.
- policy_assignment_source_ref: If assignment_method = 'Policy', this field should contain a reference identifying the specific policy rule or assignment record that enforced this state (e.g., TagPolicyAssignment:12345, OrgDefault:Antivirus). This allows tracing and potentially displaying the policy name (via tooltip using the title attribute on the policy indicator icon).
- UI Control: The backend determines if an assignment is policy-driven based on these fields. If it is, the frontend should render the dropdown as disabled and show the policy indicator icon.
6. Handling Recommendations
- Source Table: ServiceRecommendations.
- Logic: For a given entity (Device/User) and service_category_id:
- Query ServiceRecommendations matching the entity's context (Org ID, Location ID, Device Type, User Group Tags, etc.) and the service_category_id.
- Filter for is_active = true.
- Order the matching recommendations by priority (ascending, lower number = higher priority).
- Select the recommended_product_id from the top-priority matching rule. If no rule matches, there is no specific recommendation for that cell.
- UI Mapping: The backend passes the recommended_product_id (if found) to the frontend. The JavaScript compares the currently selected/staged assigned_product_id in the cell with the recommended_product_id:
- Match -> Green background (bg-rec-match)
- Mismatch (Assigned != Recommended, and Assigned != None) -> Amber background (bg-rec-differs)
- Assigned is None -> Red background (bg-rec-none)
7. Pricing Logic
- Hierarchy: The price displayed next to each option in the dropdown (and used for summary calculations) is determined by the following hierarchy (highest priority first):
- Assignment Override: DeviceServiceAssignments.override_price / UserServiceAssignments.override_price (if set for the current assignment).
- Agreement Addition Override: AgreementAdditions.unit_price_override (if set for the specific product on the client's agreement).
- Pricing Rules: Evaluate active PricingRules within the applicable PricingRuleSets based on priority. The hierarchy for finding the applicable PricingRuleSet is typically:
- Locations.pricing_rule_set_id
- Agreements.pricing_rule_set_id
- Organizations.pricing_rule_set_id (Client Org)
- Organizations.pricing_rule_set_id (Managing MSP Org, via parent_msp_org_id)
- Base Product Price: Products.unit_price.
- Currency: The final price must be presented in the correct currency. The override_currency_code takes precedence if an override price is set. Otherwise, the currency is determined by the PricingRuleSet or the Products.default_currency_code. All summary calculations (Review Proposed Changes area) should convert individual line costs to the Organizations.default_currency_code for the client org.
8. Staging and Applying Changes
- Frontend State: The JavaScript maintains two key states:
- originalState: Stores the assignments loaded initially from Device/UserServiceAssignments.
- stagedChanges: An object tracking modifications made by the user in the UI before clicking Apply. Keys are entity IDs, values are objects mapping category IDs to { newPlanId, originalPlanId, newPrice, ... }.
- User Interaction: Changing a dropdown value triggers stageChange, which updates stagedChanges and refreshes the UI (cell border/background, summary area).
- Apply Button: Clicking "Apply" triggers applyChanges:
- Confirms with the user.
- Sends the stagedChanges data to the backend (e.g., as an array of updates/inserts).
- Backend Logic: Processes the batch. For each change:
- Finds the corresponding record in DeviceServiceAssignments or UserServiceAssignments (based on entity ID and category ID).
- If a record exists, UPDATE its assigned_product_id, assignment_method (to 'Manual'), assigned_by_user_id, updated_at, and potentially clear override price/policy ref.
- If no record exists (e.g., changing from 'None'), INSERT a new record.
- If changing to 'None', potentially DELETE the existing assignment record or set assigned_product_id to NULL.
- Log the changes in an audit table (e.g., AuditLog).
- Potentially trigger billing recalculations or other workflows.
- Frontend Update: On successful backend response:
- Update originalState to match the newly applied stagedChanges.
- Clear stagedChanges.
- Refresh the UI (updateUIFromState) to remove highlights and update summaries.
- Discard Button: Triggers clearStagedChanges: Clears the stagedChanges object, resets UI dropdowns back to match originalState, and refreshes the UI.
9. Populating the UI (Backend Task)
To generate the pageData JSON for the frontend, the backend needs to:
- Identify the client org_id.
- Determine the active Agreements for the client.
- Fetch the list of Devices or Users based on UI filters (location, type, search).
- For the selected entityType ('Device' or 'User'), determine the applicable serviceCategories by querying Products (where product_type='Service', is_service_management_enabled=true, linked via AgreementAdditions, and matching applicable_entity_types).
- For each entity in the filtered list:
- Fetch its current assignments from DeviceServiceAssignments or UserServiceAssignments for the visible categories.
- Fetch the applicable ServiceRecommendations based on the entity's context (Org, Location, DeviceType, etc.) and visible categories.
- Construct the entity object for the JSON, including ID, name, details, type, current assignments, recommendations, and policy info.
- Fetch details for all potentially applicable Products (service plans) linked via AgreementAdditions for the visible categories. Include pricing, applicability rules, comparison attributes, etc.
- Fetch modalDetails data (likely pre-aggregated or generated on the fly based on applicable products per category).
- Fetch policy details referenced in assignments.
- Assemble the final pageData JSON.
10. Key Queries (Conceptual)
- SELECT assigned_product_id, assignment_method, policy_assignment_source_ref FROM DeviceServiceAssignments WHERE device_id = ? AND service_category_id = ? (Get current assignment)
- SELECT p.* FROM Products p JOIN AgreementAdditions aa ON p.product_id = aa.product_id WHERE aa.agreement_id = ? AND p.product_type = 'Service' AND p.is_service_management_enabled = true AND ? = ANY(p.applicable_entity_types) AND (p.applicable_device_types IS NULL OR ? = ANY(p.applicable_device_types)) AND p.category = ? (Find applicable plans for a cell dropdown)
- SELECT recommended_product_id FROM ServiceRecommendations WHERE org_id = ? AND service_category_id = ? AND scope_type = ? AND scope_value = ? AND is_active = true ORDER BY priority ASC LIMIT 1 (Find best recommendation)
- Logic to check PricingRules based on hierarchy (complex, likely a function).
This detailed breakdown should provide a clear understanding of how the database schema supports the required functionality for the Services Management page.