/** * EDC Policies Management Component * * Handles all policy-related operations including: * - Listing ODRL policies with search and sort * - Creating new policies * - Editing existing policies * - Deleting policies * * @customElement edc-policies-management */ import { html, LitElement, nothing } from "lit"; import { customElement, property, state } from "lit/decorators.js"; import { repeat } from "lit/directives/repeat.js"; import { msg } from '@lit/localize'; import type { PolicyDefinition, EdcStoreInterface } from '../../../types/edc-types'; // Import styles import { managementStyles } from '../../../styles/management-styles'; import { buttonStyles, formStyles } from '../../../styles/shared-styles'; @customElement("edc-policies-management") export class EdcPoliciesManagement extends LitElement { // ============================================================================ // Properties // ============================================================================ @property({ type: Object }) store!: EdcStoreInterface; // ============================================================================ // State // ============================================================================ @state() private policies: PolicyDefinition[] = []; @state() private isLoading: boolean = false; @state() private showCreateForm: boolean = false; @state() private editingPolicy: PolicyDefinition | null = null; @state() private searchTerm: string = ''; @state() private sortBy: 'id' | 'type' | 'created' = 'id'; @state() private sortDirection: 'asc' | 'desc' = 'asc'; @state() private errorMessage: string = ''; @state() private successMessage: string = ''; // ============================================================================ // Lifecycle Methods // ============================================================================ connectedCallback() { super.connectedCallback(); this.loadPolicies(); } // ============================================================================ // Data Loading // ============================================================================ async loadPolicies() { if (!this.store) { this.showError('Store not initialized.'); return; } this.isLoading = true; this.clearMessages(); try { console.log('🔍 Loading policies...'); const policies = await this.store.getAllPolicies(); this.policies = Array.isArray(policies) ? policies : []; console.log(`✅ Loaded ${this.policies.length} policies`); } catch (error: any) { console.error('❌ Failed to load policies:', error); this.showError(`Failed to load policies: ${error.message}`); } finally { this.isLoading = false; } } // ============================================================================ // CRUD Operations // ============================================================================ private async createPolicy(policyData: PolicyDefinition) { if (!this.store) return false; try { console.log('🔨 Creating policy:', policyData); await this.store.createPolicy(policyData); this.showSuccess(msg('Policy created successfully!', { id: 'spolicycreatedsuccessfully' })); this.showCreateForm = false; await this.loadPolicies(); // Dispatch event to notify parent this.dispatchEvent(new CustomEvent('policy-created', { detail: { policy: policyData }, bubbles: true, composed: true })); return true; } catch (error: any) { this.showError(`Failed to create policy: ${error.message}`); return false; } } private async updatePolicy(policyId: string, policyData: PolicyDefinition) { if (!this.store) return false; try { console.log(`✏️ Updating policy ${policyId}:`, policyData); await this.store.updatePolicy(policyId, policyData); this.showSuccess(msg('Policy updated successfully!', { id: 'spolicyupdatedsuccessfully' })); this.editingPolicy = null; await this.loadPolicies(); // Dispatch event to notify parent this.dispatchEvent(new CustomEvent('policy-updated', { detail: { policyId, policy: policyData }, bubbles: true, composed: true })); return true; } catch (error: any) { this.showError(`Failed to update policy: ${error.message}`); return false; } } private async deletePolicy(policyId: string) { if (!this.store) return; if (!confirm(`Are you sure you want to delete policy '${policyId}'? This action cannot be undone.`)) { return; } try { console.log(`🗑️ Deleting policy: ${policyId}`); await this.store.deletePolicy(policyId); this.showSuccess(msg('Policy deleted successfully!', { id: 'spolicydeletedsuccessfully' })); await this.loadPolicies(); // Dispatch event to notify parent this.dispatchEvent(new CustomEvent('policy-deleted', { detail: { policyId }, bubbles: true, composed: true })); } catch (error: any) { this.showError(`Failed to delete policy: ${error.message}`); } } // ============================================================================ // Event Handlers // ============================================================================ private handleCreatePolicy = async (e: Event) => { e.preventDefault(); const form = e.target as HTMLFormElement; const formData = new FormData(form); const policyData: PolicyDefinition = { '@type': 'PolicyDefinition', '@id': formData.get('policyId') as string, policy: { '@type': formData.get('policyType') as any, '@id': formData.get('innerPolicyId') as string || undefined, target: formData.get('target') as string || undefined, permission: [{ '@type': 'Permission', action: formData.get('permissionAction') as string, constraint: [] }] } }; await this.createPolicy(policyData); }; private handleEditPolicy = async (e: Event) => { e.preventDefault(); if (!this.editingPolicy) return; const form = e.target as HTMLFormElement; const formData = new FormData(form); const policyData: PolicyDefinition = { '@type': 'PolicyDefinition', '@id': this.editingPolicy['@id'], policy: { '@type': formData.get('policyType') as any, '@id': formData.get('innerPolicyId') as string || undefined, target: formData.get('target') as string || undefined, permission: [{ '@type': 'Permission', action: formData.get('permissionAction') as string, constraint: [] }] } }; await this.updatePolicy(this.editingPolicy['@id'], policyData); }; // ============================================================================ // Utility Methods // ============================================================================ private showError(message: string) { this.errorMessage = message; this.successMessage = ''; setTimeout(() => { this.errorMessage = ''; }, 5000); } private showSuccess(message: string) { this.successMessage = message; this.errorMessage = ''; setTimeout(() => { this.successMessage = ''; }, 3000); } private clearMessages() { this.errorMessage = ''; this.successMessage = ''; } private get filteredPolicies() { let filtered = [...this.policies]; if (this.searchTerm) { const term = this.searchTerm.toLowerCase(); filtered = filtered.filter(policy => { const id = policy['@id']?.toLowerCase() || ''; const type = policy.policy['@type']?.toLowerCase() || ''; const policyId = policy.policy['@id']?.toLowerCase() || ''; return id.includes(term) || type.includes(term) || policyId.includes(term); }); } // Sort filtered.sort((a, b) => { let aVal: string | number; let bVal: string | number; switch (this.sortBy) { case 'id': aVal = a['@id'] || ''; bVal = b['@id'] || ''; break; case 'type': aVal = a.policy['@type'] || ''; bVal = b.policy['@type'] || ''; break; case 'created': aVal = a.createdAt || 0; bVal = b.createdAt || 0; break; default: aVal = a['@id'] || ''; bVal = b['@id'] || ''; } if (typeof aVal === 'string' && typeof bVal === 'string') { aVal = aVal.toLowerCase(); bVal = bVal.toLowerCase(); } let result = 0; if (aVal < bVal) result = -1; else if (aVal > bVal) result = 1; return this.sortDirection === 'desc' ? -result : result; }); return filtered; } // ============================================================================ // Render Methods // ============================================================================ render() { return html`
${msg('Create your first ODRL policy to get started.', { id: 'screateyourfirstodrlpolicy' })}