> ## Documentation Index
> Fetch the complete documentation index at: https://docs.azalt.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Widget

> A single visualization configured for one indicator, with settings and an optional per-widget filter.

### Widget

A widget visualizes a single Indicator inside a Dashboard. Widgets support unified filters (sites, years, statuses), multiple visualization types, aggregation and display options, dataset mappings, and optional targets overlay.

#### Types

* `line_chart`: multi-series time trends
* `bar_chart`: categorical or time-based comparisons (default/stacked/percent)
* `pie_chart`: proportional breakdowns
* `value`: single KPI number
* `periodic_values`: calendar/periodic summaries
* `table`: hierarchical indicator breakdown table

#### Data Shape

```typescript theme={null}
// apps/azalt/src/server/db/types/dashboard.ts (simplified)
type DashboardWidgetType =
  | "line_chart" | "bar_chart" | "pie_chart" | "value" | "table" | "periodic_values";

interface DashboardFilter { siteIds?: string[]; startYear?: number; endYear?: number; statuses?: ("APPROVED"|"COMPLETED"|"REJECTED")[] }

interface DashboardWidgetSettings {
  indicatorDatasetMappings?: Record<string, {
    useDatasetValue: boolean;
    datasetId?: string;
    name?: string;
    field?: string;
  }> | null;
  aggregator?: "sum" | "avg" | "ratio";
  period?: "MONTHLY" | "QUARTERLY" | "YEARLY" | "TIMESTAMP";
  displayMode?: "sites" | "aggregated" | "groups";
  chartSettings?: "default" | "stacked" | "percent"; // bar charts
  showNumbers?: boolean;
  showIndicatorName?: boolean;
  angle?: number;              // pie charts
  siteGroups?: Array<{ id: string; name: string; siteIds: string[] }>;
  decimalPlaces: number;
  selectedTargetEntries?: string[];
  showTargets?: boolean;
}

interface DashboardWidget {
  id: string; dashboardId: string; indicatorId: string; name: string;
  type: DashboardWidgetType; x: number; y: number; w: number; h: number;
  settings: DashboardWidgetSettings; filter: DashboardFilter | null;
}
```

#### Filters & Precedence

* Per-widget `filter` can specify `siteIds`, `startYear`, `endYear`, `statuses`.
* If omitted, the Dashboard `globalFilter` applies.
* Statuses fallback to organization defaults, else `APPROVED`.
* Public dashboards accept per-widget temporary overrides (not saved) when using the public API.

#### Settings

* Aggregation: `sum`, `avg`, or `ratio`
* Period: `MONTHLY`, `QUARTERLY`, `YEARLY` (timestamp normalized to monthly for charts)
* Display mode: `sites` (per-site series), `aggregated` (single series), `groups` (custom site groups)
* Bar chart: `default`, `stacked`, `percent`
* Formatting: `decimalPlaces`, `showNumbers`, `showIndicatorName`, `angle` (pie)
* Dataset mappings: select dataset/field per indicator input; UI surfaces mapping issues (missing field/no data per year)
* Targets: show target lines and select target entries where available
* Contribution shares: enable per-site/group shares on line/bar/pie widgets (when display mode is `sites` or `groups`)

##### Contribution Shares

* Toggle **Show contribution shares** to replace raw KPI values with the contribution payload that includes each site/group’s share. This is available for line/bar/pie widgets whenever the display mode is `sites` or `groups`; the option is disabled in `aggregated` mode because contributions would always read 100%.
* Shares are computed at the same period you pick in the widget (`MONTHLY`, `QUARTERLY`, or `YEARLY`) and honor the selected aggregator (`sum`, `avg`, `ratio`). The backend aggregates contribution basis totals so the shares always sum to \~100% for the bucket.
* Use the **Contribution scope** selector to decide the denominator:
  * **Organization** – ignores the widget’s site filter and reflects the indicator’s true global share (useful for allocating costs across sites even if the widget is filtered).
  * **Visible data** – limits the denominator to the currently visible site set (respecting widget/global filters).
* KPI expressions can still reference `SITE_SHARE`, `GROUP_SHARE`, or `GLOBAL_SHARE` operators directly. The widget-level toggle simply controls how charts render the contribution data returned by `widgets.getData`.

#### Data & API

Internal (app): `dashboardWidgets.getData` returns computed values for the widget’s indicator, respecting merged filters and settings.

Public: `dashboards.getWithData` returns a combined payload for all widgets (dashboard, widgets, datasets, indicators, widgetData). Public view can pass per-widget `viewOptions` (e.g., type) and filter overrides.

#### Security & Permissions

* Read: Viewer or public link (for public dashboards)
* Create/Update/Delete widgets: Manager or higher

#### Typical Operations

* Add a widget: choose indicator, type, and layout (x,y,w,h)
* Adjust settings: period, aggregation, display mode, decimals
* Apply a per-widget filter to override dashboard defaults
* Map datasets for indicator inputs; resolve mapping issues
* Remove or move a widget via drag-and-drop

#### Related Concepts

* Dashboard — container and global filter
* Indicator — the metric a widget visualizes
* Dataset — coefficients and reference values for indicator calculations
* **Average**: Mean values across sites or time periods
* **Ratio**: Calculate ratios and percentages
* **Weighted Average**: Account for site size or other factors

**Filtering and Grouping**:

* **Override Dashboard Filters**: Widget-specific site/year ranges
* **Custom Site Groups**: Organize sites beyond your organizational hierarchy
* **Tag-Based Filtering**: Filter by site tags or characteristics

**Dataset Mappings**: Connect indicators to specific emission factors or benchmarks

* Reference specific dataset versions
* Compare performance against industry standards
* Show methodology and data sources

## Real-World Widget Examples

**Carbon Footprint Line Chart**:

* Data Source: Total Emissions indicator
* Period: Monthly aggregation
* Display: 12-month trend line
* Sites: All manufacturing facilities
* Visual: Line chart with target line overlay

**Energy Source Pie Chart**:

* Data Source: Energy consumption form data
* Breakdown: By energy source type
* Display: Percentage breakdown with values
* Sites: Corporate headquarters only
* Visual: Donut chart with legend

**Facilities Comparison Bar Chart**:

* Data Source: Emissions intensity indicator
* Period: Annual data
* Display: Horizontal bars ranked by performance
* Sites: Top 10 facilities by emissions
* Visual: Color-coded performance bands

**KPI Value Widget**:

* Data Source: Total cost savings indicator
* Period: Year-to-date
* Display: Large number with trend arrow
* Sites: All sites aggregated
* Visual: Green/red color coding based on target

**Monthly Performance Table**:

* Data Source: Multiple indicators (energy, emissions, waste)
* Period: Monthly breakdown
* Display: Tabular format with all metrics
* Sites: Regional breakdown
* Visual: Conditional formatting for target achievement

## Widget Interaction Features

**Drill-Down Capabilities**: Click on data points to see detailed breakdowns

**Export Options**: Download widget data or images

**Real-Time Updates**: Automatic refresh when underlying data changes

**Responsive Design**: Adapt to different screen sizes and orientations

## Site Grouping

Create custom groups beyond your organizational hierarchy:

**Manufacturing Sites**: All production facilities regardless of geographic location

**High Energy Users**: Sites with consumption above certain thresholds

**Pilot Program Participants**: Sites participating in specific initiatives

**Retail Locations**: All customer-facing facilities

**Office Buildings**: All administrative locations

## Performance Optimization

**Data Caching**: Frequently accessed data is cached for faster loading

**Lazy Loading**: Complex visualizations load progressively

**Smart Refresh**: Only update when underlying data actually changes

**Pagination**: Handle large datasets efficiently in table widgets

## Configuration Best Practices

**Choose Appropriate Visualization Types**:

* Use line charts for trends over time
* Use bar charts for comparisons between entities
* Use pie charts for proportional data (limit to 5-7 categories)
* Use value widgets for key performance indicators

**Optimize for Your Audience**:

* Executive dashboards: Focus on high-level KPIs and trends
* Operational dashboards: Show detailed breakdowns and actionable data
* External stakeholder dashboards: Emphasize transparency and compliance

**Maintain Consistency**:

* Use consistent color schemes across related widgets
* Apply similar time periods for meaningful comparisons
* Maintain consistent decimal precision for related metrics

## Operational Benefits

**Focused Analysis**: Each widget addresses a specific question or metric

**Flexible Display**: Choose the best visualization for each type of data

**Interactive Exploration**: Drill down from high-level views to detailed data

**Real-Time Monitoring**: Track performance as data is collected and calculated

**Stakeholder Communication**: Professional visualizations for different audiences
