# Maintenance KPIs in Your Own View

Kanoa has a **Maintenance Analytics** screen, but it has no maintenance widgets for dashboards. The widget categories are Analytics, Downtime, Inputs, Inventory, Lots, Notifications and Selectors.

If a plant manager wants maintenance KPIs on their own dashboard, you build the widget. A widget is just a Perspective view, and the KPIs come from `system.kanoa.cmms` functions.

You will build a view that shows, for Machine 1:

- Preventive maintenance completion and on-time percentages (for the whole plant).
- MTBF in days.
- The open backlog, by age.
- MTBF by asset, in a table.

## Explore the Data

Look at what the functions return before you design the view.

:::action[Print the KPI datasets]

1. Open the Script Console and run this:

   ```python
   asset = system.kanoa.asset.getAssets({'assetPath': 'CoreForge\\Philadelphia\\Machining\\Machine 1'})
   assetId = system.kanoa.utilities.getFieldValue('assetId', asset)

   params = {
       'assetId': assetId,
       'startDate': system.date.addDays(system.date.now(), -90),
       'endDate': system.date.now()
   }

   dates = {'startDate': params['startDate'], 'endDate': params['endDate']}

   summary = system.kanoa.cmms.getMaintenanceKPISummary(params)
   print list(summary.getColumnNames())
   print system.kanoa.utilities.convertDatasetToJSON(summary)

   pm = system.kanoa.cmms.getPreventiveMaintenanceCompliance(dates)
   print system.kanoa.utilities.convertDatasetToJSON(pm)

   mtbf = system.kanoa.cmms.getMaintenanceMTBFSummary(params)
   print system.kanoa.utilities.convertDatasetToJSON(mtbf)
   ```

2. Read the output. `getPreventiveMaintenanceCompliance` filters by date only, not by asset. The summary holds the MTTA, MTTR and related KPIs. The PM compliance row has `PM_CompletionPct`, `PM_OnTimePct` and `PM_OpenCount`. The MTBF summary has `MTBF_Days`.

:::

{/*
TODO: getMaintenanceKPISummary has no sample output in the function reference.
Run it on a gateway and add the column names (for example the MTTA and MTTR columns) here.
Then add them to the tile function in the next section.
*/}

Machine 1 needs completed work orders in the period for these to show anything. Use the ones from [Work Orders](../02-work-orders/index.md). Where there is no data, a dataset may have no rows, so the script below checks for that.

::embed-section{src="../../../systemFunctions/cmms/getMaintenanceKPISummary.md" collapsed="true" summary="Reference Materials: getMaintenanceKPISummary"}

::embed-section{src="../../../systemFunctions/cmms/getPreventiveMaintenanceCompliance.md" collapsed="true" summary="Reference Materials: getPreventiveMaintenanceCompliance"}

## Write the Data Function

A view should make one call and get everything it needs. Add a function to the `trainingMaintenance` library from the last lesson that gathers all the numbers into one dictionary.

Views need plain lists and numbers, so the function converts each dataset with `convertDatasetToJSON`.

:::action[Add getKpiTiles]

1. Open the `trainingMaintenance` script library.
2. Add this function below the one you wrote before:

   ```python
   def getKpiTiles(assetPath, days=90):
       """
       Gather the maintenance KPIs a view needs, for one asset, over the last N days.
       Returns a dictionary with simple values and lists that Perspective can bind to.
       """
       assetId = system.kanoa.utilities.getFieldValue('assetId', system.kanoa.asset.getAssets({'assetPath': assetPath}))
       params = {
           'assetId': assetId,
           'startDate': system.date.addDays(system.date.now(), -days),
           'endDate': system.date.now()
       }

       # Preventive maintenance compliance (one row). It takes dates only, so it covers every asset
       dates = {'startDate': params['startDate'], 'endDate': params['endDate']}
       pmRows = system.kanoa.utilities.convertDatasetToJSON(system.kanoa.cmms.getPreventiveMaintenanceCompliance(dates))
       pm = pmRows[0] if pmRows else {}

       # MTBF for the asset (one row)
       mtbfRows = system.kanoa.utilities.convertDatasetToJSON(system.kanoa.cmms.getMaintenanceMTBFSummary(params))
       mtbf = mtbfRows[0] if mtbfRows else {}

       # MTBF for each asset, trimmed to the columns the table shows
       byAsset = system.kanoa.utilities.convertDatasetToJSON(system.kanoa.cmms.getMaintenanceMTBFByAsset(params))
       mtbfByAsset = []
       for row in byAsset:
           mtbfByAsset.append({
               'assetName': row['assetName'],
               'failureCount': row['failureCount'],
               'MTBF_Days': row['MTBF_Days']
           })

       # Open backlog, counted by age bucket
       backlogParams = {'assetPath': assetPath, 'startDate': system.date.addDays(system.date.now(), -days)}
       backlog = system.kanoa.utilities.convertDatasetToJSON(system.kanoa.cmms.getMaintenanceBacklogAging(backlogParams))
       buckets = {'0-7': 0, '8-30': 0, '31-60': 0, '60+': 0}
       for row in backlog:
           bucket = row['ageBucket']
           buckets[bucket] = buckets.get(bucket, 0) + 1

       return {
           'pmCompletionPct': pm.get('PM_CompletionPct'),
           'pmOnTimePct': pm.get('PM_OnTimePct'),
           'pmOpenCount': pm.get('PM_OpenCount'),
           'mtbfDays': mtbf.get('MTBF_Days'),
           'failureCount': mtbf.get('failureCount'),
           'backlogTotal': len(backlog),
           'backlogBuckets': buckets,
           'mtbfByAsset': mtbfByAsset
       }
   ```

3. In the Script Console, test it:

   ```python
   print trainingMaintenance.getKpiTiles('CoreForge\\Philadelphia\\Machining\\Machine 1')
   ```

:::

{/*
TODO: Confirm the exact age bucket labels returned by getMaintenanceBacklogAging.
The cmmsAnalytics page lists 0-7, 8-30, 31-60 and 60+ days, and the function example shows 31-60.
Check the label for the oldest bucket on a gateway and fix the buckets dictionary if it differs.
Also confirm whether getMaintenanceMTBFByAsset returns only assets with failures, or every asset.
*/}

:::note
`getMaintenanceBacklogAging` filters by `assetPath`, and `assetPath` matches every asset whose path starts with that text. A path ending in `Machine 1` would also match `Machine 10`. That is fine for training, but check it when you reuse the function.
:::

::embed-section{src="../../../systemFunctions/cmms/getMaintenanceBacklogAging.md" collapsed="true" summary="Reference Materials: getMaintenanceBacklogAging"}

::embed-section{src="../../../systemFunctions/cmms/getMaintenanceMTBFByAsset.md" collapsed="true" summary="Reference Materials: getMaintenanceMTBFByAsset"}

## Build the View

The Kanoa dashboard guide says a widget view must have a view parameter called `value`, and that `value` must be a dictionary. Follow that now, so the view works as a widget later.

:::action[Create the view]

1. In the Designer Project Browser, create a new Perspective view named `MaintenanceKpis` in a folder such as `widgets/maintenance`.
2. Set the root container to a **Flex Container** with the direction set to **column**, as the dashboard guide recommends flex containers.
3. On the **Params** tab, add an **Input** parameter called `value`, type Object, with this default:

   ```json
   {
     "assetPath": "CoreForge\\Philadelphia\\Machining\\Machine 1",
     "days": 90
   }
   ```

4. On the **Custom** tab, add a property called `kpis`.
5. Bind `view.custom.kpis` with an **Expression** binding:

   ```text
   runScript("trainingMaintenance.getKpiTiles", 60000, {view.params.value.assetPath}, {view.params.value.days})
   ```

   The `60000` refreshes the numbers every minute.

:::

Now add the display. Everything reads from `view.custom.kpis`.

:::action[Add the tiles and table]

1. Add four **Label** components in a row. Bind each label's `props.text` as shown:

   | Label | Expression binding for `props.text` |
   | --- | --- |
   | PM completion | `"PM completed (plant): " + {view.custom.kpis.pmCompletionPct} + "%"` |
   | PM on time | `"PM on time (plant): " + {view.custom.kpis.pmOnTimePct} + "%"` |
   | MTBF | `"MTBF: " + {view.custom.kpis.mtbfDays} + " days"` |
   | Open backlog | `"Open work orders: " + {view.custom.kpis.backlogTotal}` |

2. Add a **Table** component below them. Bind `props.data` to `view.custom.kpis.mtbfByAsset` with a **Property** binding.
3. Add a second **Table**. Bind its `props.data` with an **Expression** binding:

   ```text
   runScript("trainingMaintenance.getBacklogRows", 60000, {view.custom.kpis})
   ```

   You'll write that function in a moment.

:::

The backlog is a dictionary of counts, and a table wants a list of rows. A small helper turns one into the other.

:::action[Add getBacklogRows]

1. Add this to the `trainingMaintenance` library:

   ```python
   def getBacklogRows(kpis):
       """Turn the backlog bucket counts into table rows, oldest last."""
       rows = []
       for bucket in ['0-7', '8-30', '31-60', '60+']:
           rows.append({'Age (days)': bucket, 'Open work orders': kpis['backlogBuckets'].get(bucket, 0)})
       return rows
   ```

2. Return to the view. It should now show tiles, an MTBF table and a backlog table for Machine 1.

:::

{/*
TODO: The Perspective expression runScript passes view.custom.kpis in as a dictionary-like object.
Confirm on a gateway that kpis['backlogBuckets'].get works on it, or convert it with dict() first.
*/}

Preview the view in the Designer, then open it in a Perspective session. If a tile is empty, the matching dataset has no rows in the period. Complete a few work orders and check again.

## Add the View to a Dashboard

Kanoa dashboards are made of widgets, and any view can become a widget. You register it, then add it to a dashboard.

::embed-section{src="../../../kanoa-ops-analysis/dashboards.md" collapsed="true" summary="Reference Materials: All About Dashboards"}

:::action[Register the view as a widget]

1. Navigate to **Dashboards → Dashboard Editor** and select the widget icon to add a widget.
2. Fill in the **Widget Info** panel:

   | Field | Value |
   | --- | --- |
   | Name | `Maintenance KPIs` |
   | Description | `PM compliance, MTBF and open backlog for one asset.` |
   | Category | Create a new category called `Maintenance` |
   | View Path | The path of your `MaintenanceKpis` view, copied from the Designer |
   | View Params | Copy the `value` parameter from the view |

3. Save the widget.

:::

:::action[Add it to a dashboard]

1. Create a dashboard called `Maintenance Overview`, or open an existing one.
2. Select an area of the canvas. In the add widget popup, choose **Maintenance/Maintenance KPIs**.
3. Click the widget and look at its **View Params**. Change `days` to `30`. The tiles recalculate.

:::

:::warning
This widget does not react to the **Asset Selector** and **Date Range Selector** widgets. Kanoa widgets do that by building filters from the view parameters and the session properties. Your view takes a fixed `assetPath` and `days` instead.
:::

{/*
TODO: Confirm on a gateway whether the Dashboard Editor accepts nested keys in the value parameter
(value.assetPath and value.days) when you edit View Params in the parameter table.
Also confirm how a widget can read the asset selector, using getWidgetFilters from the dashboards guide,
and add a step if it works for these functions.
*/}

## What You Built

You built a maintenance KPI widget. One script function gathers PM compliance, MTBF and backlog aging from the `system.kanoa.cmms` functions. A Perspective view refreshes that data every minute and shows it as tiles and tables. Registered under a new **Maintenance** category, it now sits on a dashboard next to the built-in widgets.
