6 Commits

Author SHA1 Message Date
Gaurav Kumar
c5d730ae22 Update editnewdash.component.ts 2025-11-05 10:49:53 +05:30
Gaurav Kumar
40438fcc1b unified 2025-11-04 19:11:00 +05:30
Gaurav Kumar
71be18b21f unified 2025-11-04 18:47:53 +05:30
Gaurav Kumar
1263805d61 chart 2025-11-04 18:37:45 +05:30
Gaurav Kumar
0e6e4899e5 unifield 2025-11-04 17:41:18 +05:30
Gaurav Kumar
29e50253af edit new dash 2025-11-04 13:02:23 +05:30
5 changed files with 1005 additions and 331 deletions

View File

@@ -0,0 +1,125 @@
import { Injectable } from '@angular/core';
import { Observable, forkJoin } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiRequestService } from 'src/app/services/api/api-request.service';
import { ChartType, UiComponent, ComponentProperty, ChartTemplate, DynamicField } from './chart-config-manager.component';
@Injectable({
providedIn: 'root'
})
export class DynamicChartLoaderService {
private chartTypesUrl = 'api/chart-types';
private uiComponentsUrl = 'api/ui-components';
private componentPropertiesUrl = 'api/component-properties';
private chartTemplatesUrl = 'api/chart-templates';
private dynamicFieldsUrl = 'api/dynamic-fields';
constructor(private apiRequest: ApiRequestService) { }
/**
* Load all chart configurations dynamically
* This method fetches all chart types and their associated components, templates, and fields
*/
loadAllChartConfigurations(): Observable<any> {
console.log('Loading all chart configurations dynamically');
// Load all chart types first
return this.apiRequest.get(this.chartTypesUrl).pipe(
map(chartTypes => {
console.log('Loaded chart types:', chartTypes);
return chartTypes;
})
);
}
/**
* Load complete configuration for a specific chart type
* This includes UI components, templates, and dynamic fields
*/
loadChartConfiguration(chartTypeId: number): Observable<{
chartType: ChartType,
uiComponents: UiComponent[],
templates: ChartTemplate[],
dynamicFields: DynamicField[]
}> {
console.log(`Loading complete configuration for chart type ${chartTypeId}`);
// Load all related data in parallel
return forkJoin({
chartType: this.apiRequest.get(`${this.chartTypesUrl}/${chartTypeId}`),
uiComponents: this.apiRequest.get(`${this.uiComponentsUrl}/chart-type/${chartTypeId}`),
templates: this.apiRequest.get(`${this.chartTemplatesUrl}/chart-type/${chartTypeId}`),
dynamicFields: this.apiRequest.get(`${this.dynamicFieldsUrl}/chart-type/${chartTypeId}`)
}).pipe(
map(result => {
console.log(`Loaded complete configuration for chart type ${chartTypeId}:`, result);
return result;
})
);
}
/**
* Load chart template for a specific chart type
* This is used to render the chart UI dynamically
*/
loadChartTemplate(chartTypeId: number): Observable<ChartTemplate[]> {
console.log(`Loading chart templates for chart type ${chartTypeId}`);
return this.apiRequest.get(`${this.chartTemplatesUrl}/chart-type/${chartTypeId}`);
}
/**
* Load UI components for a specific chart type
* These define what configuration fields are needed for the chart
*/
loadUiComponents(chartTypeId: number): Observable<UiComponent[]> {
console.log(`Loading UI components for chart type ${chartTypeId}`);
return this.apiRequest.get(`${this.uiComponentsUrl}/chart-type/${chartTypeId}`);
}
/**
* Load dynamic fields for a specific chart type
* These define additional dynamic fields that can be used in the chart
*/
loadDynamicFields(chartTypeId: number): Observable<DynamicField[]> {
console.log(`Loading dynamic fields for chart type ${chartTypeId}`);
return this.apiRequest.get(`${this.dynamicFieldsUrl}/chart-type/${chartTypeId}`);
}
/**
* Get chart type by name
* This is useful for finding a chart type by its name rather than ID
*/
// getChartTypeByName(name: string): Observable<ChartType | null> {
// console.log(`Finding chart type by name: ${name}`);
// return this.apiRequest.get(`${this.chartTypesUrl}/byname?chartName=${name}`).pipe(
// map((chartTypes: ChartType[]) => {
// console.log('Available chart types:', chartTypes);
// const chartType = chartTypes.find(ct => ct.name === name);
// console.log(`Found chart type for name ${name}:`, chartType);
// return chartType || null;
// })
// );
// }
getChartTypeByName(name: string): Observable<any> {
console.log(`Finding chart type by name: ${name}`);
return this.apiRequest.get(`${this.chartTypesUrl}/byname?chartName=${name}`);
}
/**
* Load all active chart types
* This is used to populate the chart selection in the dashboard editor
*/
loadActiveChartTypes(): Observable<ChartType[]> {
console.log('Loading active chart types');
return this.apiRequest.get(`${this.chartTypesUrl}`).pipe(
map((chartTypes: ChartType[]) => {
const activeChartTypes = chartTypes.filter(ct => ct.isActive);
console.log('Loaded active chart types:', activeChartTypes);
return activeChartTypes;
})
);
}
}

View File

@@ -17,6 +17,9 @@
<div style="display: inline; float: right;"> <div style="display: inline; float: right;">
<!-- <button class="btn btn-primary">Build</button> <!-- <button class="btn btn-primary">Build</button>
<button class="btn btn-primary" (click)="onSchedule()">Schedule</button> --> <button class="btn btn-primary" (click)="onSchedule()">Schedule</button> -->
<button class="btn btn-success" (click)="testDynamicChartCreation()" style="margin-left: 10px;" *ngIf="!fromRunner">
<clr-icon shape="test"></clr-icon> Test Dynamic Chart
</button>
</div> </div>
</div> </div>

View File

@@ -30,6 +30,8 @@ import { CompactFilterComponent } from '../common-filter';
import { FilterService } from '../common-filter/filter.service'; import { FilterService } from '../common-filter/filter.service';
// Add the UnifiedChartComponent import // Add the UnifiedChartComponent import
import { UnifiedChartComponent } from '../gadgets/unified-chart'; import { UnifiedChartComponent } from '../gadgets/unified-chart';
// Add the DynamicChartLoaderService import
import { DynamicChartLoaderService } from '../chart-config/dynamic-chart-loader.service';
function isNullArray(arr) { function isNullArray(arr) {
return !Array.isArray(arr) || arr.length === 0; return !Array.isArray(arr) || arr.length === 0;
@@ -58,6 +60,7 @@ export class EditnewdashComponent implements OnInit {
// Add availableKeys property for compact filter // Add availableKeys property for compact filter
availableKeys: string[] = []; availableKeys: string[] = [];
// Initialize with default widgets and update dynamically
WidgetsMock: WidgetModel[] = [ WidgetsMock: WidgetModel[] = [
{ {
name: 'Common Filter', name: 'Common Filter',
@@ -75,26 +78,26 @@ export class EditnewdashComponent implements OnInit {
name: 'Line Chart', name: 'Line Chart',
identifier: 'line_chart' identifier: 'line_chart'
}, },
{ // {
name: 'Bar Chart', // name: 'Bar Chart',
identifier: 'bar_chart' // identifier: 'bar_chart'
}, // },
{ // {
name: 'Pie Chart', // name: 'Pie Chart',
identifier: 'pie_chart' // identifier: 'pie_chart'
}, // },
{ // {
name: 'Polar Area Chart', // name: 'Polar Area Chart',
identifier: 'polar_area_chart' // identifier: 'polar_area_chart'
}, // },
{ // {
name: 'Bubble Chart', // name: 'Bubble Chart',
identifier: 'bubble_chart' // identifier: 'bubble_chart'
}, // },
{ // {
name: 'Scatter Chart', // name: 'Scatter Chart',
identifier: 'scatter_chart' // identifier: 'scatter_chart'
}, // },
{ {
name: 'Dynamic Chart', name: 'Dynamic Chart',
identifier: 'dynamic_chart' identifier: 'dynamic_chart'
@@ -206,6 +209,9 @@ export class EditnewdashComponent implements OnInit {
// Add drilldown column data property // Add drilldown column data property
drilldownColumnData = []; // Add drilldown column data property drilldownColumnData = []; // Add drilldown column data property
// Add chart types property for dynamic chart selection
chartTypes: any[] = [];
constructor(private route: ActivatedRoute, constructor(private route: ActivatedRoute,
private router: Router, private router: Router,
private dashboardService: Dashboard3Service, private dashboardService: Dashboard3Service,
@@ -214,7 +220,8 @@ export class EditnewdashComponent implements OnInit {
private datastoreService: DatastoreService, private datastoreService: DatastoreService,
private alertService: AlertsService, private alertService: AlertsService,
private sureconnectService: SureconnectService, private sureconnectService: SureconnectService,
private filterService: FilterService) { } // Add SureconnectService and FilterService to constructor private filterService: FilterService,
private dynamicChartLoader: DynamicChartLoaderService) { } // Add SureconnectService, FilterService, and DynamicChartLoaderService to constructor
// Add property to track if coming from dashboard runner // Add property to track if coming from dashboard runner
fromRunner: boolean = false; fromRunner: boolean = false;
@@ -299,12 +306,46 @@ export class EditnewdashComponent implements OnInit {
apiUrl: [''] apiUrl: ['']
}); });
// Load chart types for dynamic chart selection
this.loadChartTypesForSelection();
// Load sureconnect data first, then load dashboard data // Load sureconnect data first, then load dashboard data
this.loadSureconnectData(); this.loadSureconnectData();
// Load common filter data if it exists // Load common filter data if it exists
this.loadCommonFilterData(); this.loadCommonFilterData();
} }
// Add method to load all chart types for dynamic selection
loadChartTypesForSelection() {
console.log('Loading chart types for selection');
this.dynamicChartLoader.loadActiveChartTypes().subscribe({
next: (chartTypes) => {
console.log('Loaded chart types for selection:', chartTypes);
this.chartTypes = chartTypes;
// Convert each chart type to a WidgetModel
const newWidgets = chartTypes.map(ct => ({
name: ct.displayName || ct.name,
// identifier: ct.name.toLowerCase().replace(/\s+/g, '_')
identifier: `${ct.name.toLowerCase().replace(/\s+/g, '_')}_chart`
}));
// Filter out duplicates by identifier
const existingIds = new Set(this.WidgetsMock.map(w => w.identifier));
const uniqueNewWidgets = newWidgets.filter(w => !existingIds.has(w.identifier));
// Append unique new widgets to WidgetsMock
this.WidgetsMock = [...this.WidgetsMock, ...uniqueNewWidgets];
console.log('Updated WidgetsMock:', this.WidgetsMock);
},
error: (error) => {
console.error('Error loading chart types for selection:', error);
}
});
}
// Add method to load sureconnect data // Add method to load sureconnect data
loadSureconnectData() { loadSureconnectData() {
@@ -565,20 +606,8 @@ export class EditnewdashComponent implements OnInit {
connection: undefined connection: undefined
}); });
case "bar_chart": case "bar_chart":
return this.dashboardArray.push({ // Use dynamic chart creation for bar charts
cols: 5, return this.createDynamicChart('bar', maxChartId);
rows: 6,
x: 0,
y: 0,
chartid: maxChartId + 1,
component: UnifiedChartComponent,
name: "Bar Chart",
chartType: 'bar',
xAxis: '',
yAxis: '',
table: '',
connection: undefined
});
case "pie_chart": case "pie_chart":
return this.dashboardArray.push({ return this.dashboardArray.push({
cols: 5, cols: 5,
@@ -730,6 +759,27 @@ export class EditnewdashComponent implements OnInit {
table: '', table: '',
connection: undefined connection: undefined
}); });
default:
// Handle any other chart types dynamically
// Extract chart type name from identifier (e.g., "heatmap_chart" -> "heatmap")
const chartTypeName = componentType.replace('_chart', '');
const displayName = chartTypeName.charAt(0).toUpperCase() + chartTypeName.slice(1) + ' Chart';
// Create a unified chart with the dynamic chart type
return this.dashboardArray.push({
cols: 5,
rows: 6,
x: 0,
y: 0,
chartid: maxChartId + 1,
component: UnifiedChartComponent,
name: displayName,
chartType: chartTypeName,
xAxis: '',
yAxis: '',
table: '',
connection: undefined
});
} }
} }
removeItem(item) { removeItem(item) {
@@ -2045,4 +2095,257 @@ export class EditnewdashComponent implements OnInit {
} }
} }
// Add method to apply dynamic template to a chart
applyDynamicTemplate(chartItem: any, template: any) {
console.log('Applying dynamic template to chart:', chartItem, template);
// Apply HTML template
if (template.templateHtml) {
// In a real implementation, you would dynamically render the HTML template
// For now, we'll just log it
console.log('HTML Template:', template.templateHtml);
}
// Apply CSS styles
if (template.templateCss) {
// In a real implementation, you would dynamically apply the CSS styles
// For now, we'll just log it
console.log('CSS Template:', template.templateCss);
}
// Return the chart item with template applied
return {
...chartItem,
template: template
};
}
// Add method to test dynamic chart creation
testDynamicChartCreation() {
console.log('Testing dynamic chart creation');
// Show a success message to the user
alert('Dynamic chart test started. Check the browser console for detailed output.');
// Load all chart types
this.dynamicChartLoader.loadAllChartConfigurations().subscribe({
next: (chartTypes) => {
console.log('Loaded chart types:', chartTypes);
// Find bar chart type
const barChartType = chartTypes.find((ct: any) => ct.name === 'bar');
if (barChartType) {
console.log('Found bar chart type:', barChartType);
// Load configuration for bar chart
this.dynamicChartLoader.loadChartConfiguration(barChartType.id).subscribe({
next: (config) => {
console.log('Loaded bar chart configuration:', config);
// Create a test chart item
const chartItem = {
cols: 5,
rows: 6,
x: 0,
y: 0,
chartid: 100,
component: UnifiedChartComponent,
name: 'Test Dynamic Bar Chart',
chartType: 'bar',
xAxis: '',
yAxis: '',
table: '',
connection: undefined,
// Add dynamic fields from configuration
dynamicFields: config.dynamicFields || []
};
console.log('Created test chart item:', chartItem);
// If we have templates, apply the default one
if (config.templates && config.templates.length > 0) {
const defaultTemplate = config.templates.find((t: any) => t.isDefault) || config.templates[0];
if (defaultTemplate) {
console.log('Applying default template:', defaultTemplate);
const chartWithTemplate = this.applyDynamicTemplate(chartItem, defaultTemplate);
console.log('Chart with template:', chartWithTemplate);
// Show success message
alert('Dynamic chart test completed successfully! Check console for details.');
}
} else {
// Show success message even without templates
alert('Dynamic chart test completed successfully! No templates found. Check console for details.');
}
},
error: (error) => {
console.error('Error loading bar chart configuration:', error);
alert('Error loading bar chart configuration. Check console for details.');
}
});
} else {
console.warn('Bar chart type not found');
alert('Bar chart type not found in the database.');
}
},
error: (error) => {
console.error('Error loading chart types:', error);
alert('Error loading chart types. Check console for details.');
}
});
}
// Add method to load dynamic chart configuration
loadDynamicChartConfiguration(chartTypeId: number) {
console.log(`Loading dynamic chart configuration for chart type ${chartTypeId}`);
this.dynamicChartLoader.loadChartConfiguration(chartTypeId).subscribe({
next: (config) => {
console.log('Loaded dynamic chart configuration:', config);
// Here you would apply the configuration to the UI
// For example, populate form fields, set up templates, etc.
},
error: (error) => {
console.error('Error loading dynamic chart configuration:', error);
}
});
}
// Add method to create a dynamic chart with configuration from database
createDynamicChart(chartTypeName: string, maxChartId: number) {
console.log(`Creating dynamic chart of type: ${chartTypeName}`);
// First, get the chart type by name
this.dynamicChartLoader.getChartTypeByName(chartTypeName).subscribe({
next: (chartType) => {
if (chartType) {
console.log(`Found chart type:`, chartType);
// Load the complete configuration for this chart type
this.dynamicChartLoader.loadChartConfiguration(chartType.id).subscribe({
next: (config) => {
console.log(`Loaded configuration for ${chartTypeName}:`, config);
// Create the chart item with dynamic configuration
const chartItem = {
cols: 5,
rows: 6,
x: 0,
y: 0,
chartid: maxChartId + 1,
component: UnifiedChartComponent,
name: chartType.displayName || chartTypeName,
chartType: chartType.name,
xAxis: '',
yAxis: '',
table: '',
connection: undefined,
// Add any dynamic fields from the configuration
dynamicFields: config.dynamicFields || []
};
// Add UI components as configuration properties
if (config.uiComponents && config.uiComponents.length > 0) {
config.uiComponents.forEach(component => {
chartItem[component.componentName] = '';
});
}
this.dashboardArray.push(chartItem);
console.log(`Created dynamic chart:`, chartItem);
},
error: (error) => {
console.error(`Error loading configuration for ${chartTypeName}:`, error);
// Fallback to default configuration
// this.createDefaultChart(chartTypeName, maxChartId);
}
});
} else {
console.warn(`Chart type ${chartTypeName} not found, using default configuration`);
// this.createDefaultChart(chartTypeName, maxChartId);
}
},
error: (error) => {
console.error('Error loading configuration for chart type:', error);
// Fallback to default configuration
// this.createDefaultChart(chartType.name, chartType.displayName || chartType.name);
}
});
}
// Fallback method to create default chart configuration
createDefaultChart(chartTypeName: string, chartDisplayName: string) {
console.log(`Creating default chart for ${chartTypeName}`);
// Map chart type names to chart types
const chartTypeMap = {
'bar': 'bar',
'line': 'line',
'pie': 'pie',
'doughnut': 'doughnut',
'radar': 'radar',
'polar': 'polar',
'bubble': 'bubble',
'scatter': 'scatter'
};
// Get the chart type from the name
const chartType = chartTypeMap[chartTypeName.toLowerCase()] || 'bar';
// Safely calculate maxChartId, handling cases where chartid might be NaN or missing
let maxChartId = 0;
if (this.dashboardArray && this.dashboardArray.length > 0) {
const validChartIds = this.dashboardArray
.map(item => item.chartid)
.filter(chartid => typeof chartid === 'number' && !isNaN(chartid));
if (validChartIds.length > 0) {
maxChartId = Math.max(...validChartIds);
}
}
const chartItem = {
cols: 5,
rows: 6,
x: 0,
y: 0,
chartid: maxChartId + 1,
component: UnifiedChartComponent,
name: chartDisplayName,
chartType: chartType,
xAxis: '',
yAxis: '',
table: '',
connection: undefined
};
this.dashboardArray.push(chartItem);
console.log('Created default chart:', chartItem);
// Update the dashboard collection
this.dashboardCollection.dashboard = this.dashboardArray.slice();
// Force gridster to refresh
if (this.options && this.options.api) {
this.options.api.optionsChanged();
}
}
// Helper method to get display name for chart type
getChartDisplayName(chartTypeName: string): string {
const displayNameMap = {
'bar': 'Bar Chart',
'line': 'Line Chart',
'pie': 'Pie Chart',
'doughnut': 'Doughnut Chart',
'radar': 'Radar Chart',
'polar': 'Polar Area Chart',
'bubble': 'Bubble Chart',
'scatter': 'Scatter Chart'
};
return displayNameMap[chartTypeName.toLowerCase()] || chartTypeName;
}
} }

View File

@@ -26,110 +26,21 @@
<!-- Render different chart types based on chartType input --> <!-- Render different chart types based on chartType input -->
<div class="chart-wrapper"> <div class="chart-wrapper">
<!-- Bar Chart --> <!-- Dynamic Chart Container - uses extracted dynamic options and styles but static template -->
<div *ngIf="chartType === 'bar'" class="chart-canvas-container"> <div *ngIf="dynamicTemplate || chartType" class="chart-canvas-container">
<canvas baseChart <canvas baseChart
[datasets]="chartData" [datasets]="chartData"
[labels]="chartLabels" [labels]="chartLabels"
[options]="chartOptions" [options]="chartOptions"
[legend]="chartLegend" [legend]="chartLegend"
[chartType]="'bar'" [chartType]="chartType || 'bar'"
(chartClick)="chartClicked($event)" (chartClick)="chartClicked($event)"
(chartHover)="chartHovered($event)"> (chartHover)="chartHovered($event)">
</canvas> </canvas>
</div> </div>
<!-- Line Chart --> <!-- Fallback for when no chart type is specified -->
<div *ngIf="chartType === 'line'" class="chart-canvas-container"> <div *ngIf="!dynamicTemplate && !chartType" class="chart-canvas-container">
<canvas baseChart
[datasets]="chartData"
[labels]="chartLabels"
[options]="chartOptions"
[legend]="chartLegend"
[chartType]="'line'"
(chartClick)="chartClicked($event)"
(chartHover)="chartHovered($event)">
</canvas>
</div>
<!-- Pie Chart -->
<div *ngIf="chartType === 'pie'" class="chart-canvas-container">
<canvas baseChart
[datasets]="chartData"
[labels]="chartLabels"
[options]="chartOptions"
[legend]="chartLegend"
[chartType]="'pie'"
(chartClick)="chartClicked($event)"
(chartHover)="chartHovered($event)">
</canvas>
</div>
<!-- Doughnut Chart -->
<div *ngIf="chartType === 'doughnut'" class="chart-canvas-container">
<canvas baseChart
[datasets]="chartData"
[labels]="chartLabels"
[options]="chartOptions"
[legend]="chartLegend"
[chartType]="'doughnut'"
(chartClick)="chartClicked($event)"
(chartHover)="chartHovered($event)">
</canvas>
</div>
<!-- Bubble Chart -->
<div *ngIf="chartType === 'bubble'" class="chart-canvas-container">
<canvas baseChart
[datasets]="bubbleChartData"
[options]="chartOptions"
[legend]="chartLegend"
[chartType]="'bubble'"
(chartClick)="chartClicked($event)"
(chartHover)="chartHovered($event)">
</canvas>
</div>
<!-- Radar Chart -->
<div *ngIf="chartType === 'radar'" class="chart-canvas-container">
<canvas baseChart
[datasets]="chartData"
[labels]="chartLabels"
[options]="chartOptions"
[legend]="chartLegend"
[chartType]="'radar'"
(chartClick)="chartClicked($event)"
(chartHover)="chartHovered($event)">
</canvas>
</div>
<!-- Polar Area Chart -->
<div *ngIf="chartType === 'polar'" class="chart-canvas-container">
<canvas baseChart
[datasets]="chartData"
[labels]="chartLabels"
[options]="chartOptions"
[legend]="chartLegend"
[chartType]="'polarArea'"
(chartClick)="chartClicked($event)"
(chartHover)="chartHovered($event)">
</canvas>
</div>
<!-- Scatter Chart -->
<div *ngIf="chartType === 'scatter'" class="chart-canvas-container">
<canvas baseChart
[datasets]="chartData"
[options]="chartOptions"
[legend]="chartLegend"
[chartType]="'scatter'"
(chartClick)="chartClicked($event)"
(chartHover)="chartHovered($event)">
</canvas>
</div>
<!-- Default/Unknown Chart Type -->
<div *ngIf="!['bar', 'line', 'pie', 'doughnut', 'bubble', 'radar', 'polar', 'scatter'].includes(chartType)" class="chart-canvas-container">
<canvas baseChart <canvas baseChart
[datasets]="chartData" [datasets]="chartData"
[labels]="chartLabels" [labels]="chartLabels"