/** * EDC Assets Management Component * * Handles all asset-related operations including: * - Listing assets with search and sort * - Creating new assets * - Editing existing assets * - Deleting assets * * @customElement edc-assets-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 { Asset, AssetInput, EdcStoreInterface } from '../../../types/edc-types'; // Import styles import { managementStyles } from '../../../styles/management-styles'; import { buttonStyles, formStyles } from '../../../styles/shared-styles'; @customElement("edc-assets-management") export class EdcAssetsManagement extends LitElement { // ============================================================================ // Properties // ============================================================================ @property({ type: Object }) store!: EdcStoreInterface; // ============================================================================ // State // ============================================================================ @state() private assets: Asset[] = []; @state() private isLoading: boolean = false; @state() private showCreateForm: boolean = false; @state() private editingAsset: Asset | null = null; @state() private searchTerm: string = ''; @state() private sortBy: 'id' | 'title' | 'created' = 'id'; @state() private sortDirection: 'asc' | 'desc' = 'asc'; @state() private errorMessage: string = ''; @state() private successMessage: string = ''; // ============================================================================ // Lifecycle Methods // ============================================================================ connectedCallback() { super.connectedCallback(); this.loadAssets(); } // ============================================================================ // Data Loading // ============================================================================ async loadAssets() { if (!this.store) { this.showError('Store not initialized.'); return; } this.isLoading = true; this.clearMessages(); try { console.log('🔍 Loading assets...'); const assets = await this.store.getAllAssets(); this.assets = Array.isArray(assets) ? assets : []; console.log(`✅ Loaded ${this.assets.length} assets`); } catch (error: any) { console.error('❌ Failed to load assets:', error); this.showError(`Failed to load assets: ${error.message}`); } finally { this.isLoading = false; } } // ============================================================================ // CRUD Operations // ============================================================================ private async createAsset(assetData: AssetInput) { if (!this.store) return false; try { console.log('🔨 Creating asset:', assetData); await this.store.createAsset(assetData); this.showSuccess(msg('Asset created successfully!', { id: 'sassetcreatedsuccessfully' })); this.showCreateForm = false; await this.loadAssets(); // Dispatch event to notify parent this.dispatchEvent(new CustomEvent('asset-created', { detail: { asset: assetData }, bubbles: true, composed: true })); return true; } catch (error: any) { this.showError(`Failed to create asset: ${error.message}`); return false; } } private async updateAsset(assetId: string, assetData: AssetInput) { if (!this.store) return false; try { console.log('✏️ Updating asset:', assetId, assetData); await this.store.updateAsset(assetId, assetData); this.showSuccess(msg('Asset updated successfully!', { id: 'sassetupdatedsuccessfully' })); this.editingAsset = null; await this.loadAssets(); // Dispatch event to notify parent this.dispatchEvent(new CustomEvent('asset-updated', { detail: { assetId, asset: assetData }, bubbles: true, composed: true })); return true; } catch (error: any) { this.showError(`Failed to update asset: ${error.message}`); return false; } } private async deleteAsset(assetId: string) { if (!this.store) return; if (!confirm(`Are you sure you want to delete asset '${assetId}'?`)) { return; } try { console.log('🗑️ Deleting asset:', assetId); await this.store.deleteAsset(assetId); this.showSuccess(msg('Asset deleted successfully!', { id: 'sassetdeletedsuccessfully' })); await this.loadAssets(); // Dispatch event to notify parent this.dispatchEvent(new CustomEvent('asset-deleted', { detail: { assetId }, bubbles: true, composed: true })); } catch (error: any) { this.showError(`Failed to delete asset: ${error.message}`); } } // ============================================================================ // Event Handlers // ============================================================================ private handleCreateAsset = async (e: Event) => { e.preventDefault(); const form = e.target as HTMLFormElement; const formData = new FormData(form); const assetData: AssetInput = { '@id': formData.get('assetId') as string, properties: { 'dcterms:title': formData.get('title') as string, 'dcterms:description': formData.get('description') as string } }; const dataAddressType = formData.get('dataAddressType') as string; const baseUrl = formData.get('baseUrl') as string; if (dataAddressType) { assetData.dataAddress = { '@type': 'DataAddress', type: dataAddressType }; if (baseUrl) { assetData.dataAddress.baseUrl = baseUrl; } } await this.createAsset(assetData); }; private handleEditAsset = async (e: Event) => { e.preventDefault(); if (!this.editingAsset) return; const form = e.target as HTMLFormElement; const formData = new FormData(form); const assetData: AssetInput = { '@id': this.editingAsset['@id'], properties: { 'dcterms:title': formData.get('title') as string, 'dcterms:description': formData.get('description') as string } }; const dataAddressType = formData.get('dataAddressType') as string; const baseUrl = formData.get('baseUrl') as string; if (dataAddressType) { assetData.dataAddress = { '@type': 'DataAddress', type: dataAddressType }; if (baseUrl) { assetData.dataAddress.baseUrl = baseUrl; } } await this.updateAsset(this.editingAsset['@id'], assetData); }; // ============================================================================ // 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 filteredAssets() { let filtered = [...this.assets]; if (this.searchTerm) { const term = this.searchTerm.toLowerCase(); filtered = filtered.filter(asset => { const id = asset['@id']?.toLowerCase() || ''; const title = asset.properties?.['dcterms:title']?.toLowerCase() || ''; const description = asset.properties?.['dcterms:description']?.toLowerCase() || ''; return id.includes(term) || title.includes(term) || description.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 'title': aVal = a.properties?.['dcterms:title'] || a['@id'] || ''; bVal = b.properties?.['dcterms:title'] || b['@id'] || ''; 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 asset to get started.', { id: 'screateyourfirstasset' })}