# Raise a Work Order from a Tag

Machine 1 has a low coolant signal. When it goes true, nobody should have to notice it and fill in a form. A gateway script can raise the work order for you.

The tricky part is not raising the work order. It is raising it **once**. A signal can flicker or stay true for hours, and each change must not add another job to the backlog.

You will build three things:

- A work order template that the raised work orders come from.
- A script function that checks for open work and raises a work order only if there is none.
- A tag change script that calls the function when the signal goes true.

## Create the Template and the Tag

Kanoa raises work orders from **templates**. The script needs a template to point at, so you create it first, the same way you did in [Raise a One-Time Work Order](../02-work-orders/1-one-time-work-order.md).

:::action[Create the work order template]

1. Navigate to **Configuration → Maintenance → Work Orders** and, on the **Work Orders** tab, add a template.
2. Fill it in:

   | Field | Value |
   | --- | --- |
   | Title | `Machine 1 - Coolant low` |
   | Description | `Machine 1 reported low coolant. Check the level and top up. Look for leaks.` |
   | Asset | `CoreForge\Philadelphia\Machining\Machine 1` |
   | Maintenance type | Corrective |
   | Priority | High |
   | Requested by | Your own user |
   | Schedule type | One Time |

3. Save it. Leave its version status as **Draft** for now.

:::

{/*
TODO: Confirm on a gateway whether work order events can be added from a script against a Draft template.
Also confirm whether releasing a One Time template generates a work order of its own,
and which schedule type or status is the right one for a template that only a script raises work from.
Update this step to match.
*/}

:::action[Create the signal tag]

You don't have a real coolant sensor, so you'll use a memory tag as the signal.

1. In the Designer Tag Browser, select the `default` tag provider.
2. Create a new tag with these settings:

   | Setting | Value |
   | --- | --- |
   | Name | `Machine1CoolantLow` |
   | Tag type | Memory Tag |
   | Data type | Boolean |
   | Value | `false` |

:::

## Write the Script Function

Put the logic in a script library, not in the tag script. A library function is easy to test from the Script Console and can be reused by other events.

The function does four things, in order:

1. Finds the template by its title.
2. Asks Kanoa for work orders from that template that are still active.
3. Stops if it finds any.
4. Otherwise raises a new work order.

:::action[Add the script library]

1. In the Designer, open the project that your gateway uses for gateway event scripts. In this training that is `KANOA_SCRIPTS`.
2. Create a script library called `trainingMaintenance`.
3. Paste in this code:

   ```python title="trainingMaintenance"
   ASSET_PATH = 'CoreForge\\Philadelphia\\Machining\\Machine 1'
   TEMPLATE_TITLE = 'Machine 1 - Coolant low'

   def raiseCoolantLowWorkOrder():
       """
       Raise one corrective work order for low coolant on Machine 1,
       unless one from the same template is still open.
       Returns (workOrderEventId, message). workOrderEventId is None if nothing was raised.
       """
       logger = system.util.getLogger('trainingMaintenance')
       userId = system.kanoa.security.getIDPUserId({'userName': 'SYSTEM'})

       # 1. Find the template
       templates = system.kanoa.cmms.getWorkOrders({'title': TEMPLATE_TITLE})
       if templates.getRowCount() != 1:
           return None, 'Expected one template titled %s, found %d' % (TEMPLATE_TITLE, templates.getRowCount())
       workOrderId = system.kanoa.utilities.getFieldValue('workOrderId', templates)
       priorityId = system.kanoa.utilities.getFieldValue('workOrderPriorityId', templates)
       assetId = system.kanoa.utilities.getFieldValue('assetId', templates)

       # 2. Is a work order from this template still active?
       active = system.kanoa.cmms.getWorkOrderEvents({'workOrderId': workOrderId, 'isActive': True})

       # 3. If so, do nothing
       if active.getRowCount() > 0:
           name = active.getValueAt(0, 'workOrderEventName')
           logger.info('Coolant low on Machine 1, but %s is still open. Nothing raised.' % name)
           return None, 'Skipped. %s is still open.' % name

       # 4. Raise a new work order, due now
       workOrderEventInfo = {
           'workOrderId': workOrderId,
           'workOrderPriorityId': priorityId,
           'requestedBy': userId,
           'dueDate': system.date.now(),
           'assetId': assetId
       }
       workOrderEventId, message = system.kanoa.cmms.addWorkOrderScheduleEvent(workOrderEventInfo, userId)
       logger.info('Coolant low on Machine 1. Raised work order event %s. %s' % (workOrderEventId, message))
       return workOrderEventId, message
   ```

:::

A few things to notice:

- `getWorkOrders` returns the **template**. `getWorkOrderEvents` returns the **work orders** raised from it, each with an `isActive` flag.
- `addWorkOrderScheduleEvent` names the new work order from the next serial number, such as `MWO00004`. It is the same function Kanoa uses when a schedule or condition generates work.
- `SYSTEM` is the user recorded as the requester, because no person raised this work order.

::::note
`addWorkOrderScheduleEvent` has its own safety net. If an active work order from the same template exists, it still adds a new one, but with the status **Missed**. Your check stops the extra record from being created at all.
::::

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

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

## Test It from the Script Console

Test the function before you wire it to a tag.

:::action[Run the function twice]

1. Open the Script Console in the Designer (**Tools → Script Console**).
2. Run this:

   ```python
   print trainingMaintenance.raiseCoolantLowWorkOrder()
   print trainingMaintenance.raiseCoolantLowWorkOrder()
   ```

3. The first line prints a new work order event id and `None`. The second prints `None` and a message saying the first work order is still open.
4. Navigate to **Maintenance → Work Orders** and find the new `Machine 1 - Coolant low` work order in the **Open** group.

:::

If the function says it expected one template, check the title in **Configuration → Maintenance → Work Orders**. It must match exactly.

## Call It from a Tag Change Script

:::action[Add the tag change script]

1. In the Tag Browser, double-click `Machine1CoolantLow` to open the tag editor.
2. Select **Tag Event Scripts** and the **Value Changed** event.
3. Paste in this script:

   ```python
   def valueChanged(tag, tagPath, previousValue, currentValue, initialChange, missedEvents):
       # Only act when the signal goes true, and ignore the first value after a gateway start
       if initialChange or not currentValue.value:
           return
       workOrderEventId, message = trainingMaintenance.raiseCoolantLowWorkOrder()
   ```

4. Click **OK** and save the tag.

:::

{/*
TODO: Confirm on a gateway which project a tag event script calls script libraries from.
It should be the project set as the gateway scripting project.
Confirm that is KANOA_SCRIPTS on the training gateway, and give the setting path in the Gateway config.
*/}

The script runs on the gateway. Nobody has to be logged in, and no screen has to be open.

:::action[Trigger the signal]

1. In the Tag Browser, set `Machine1CoolantLow` to `true`.
2. Check **Maintenance → Work Orders**. If you already ran the Script Console test, there is no second work order, because the first is still open.
3. Set the tag to `false`, then `true` again. Still no second work order.
4. Open the work order and take it to **Completed**, as you did in [Work a Work Order](../02-work-orders/2-execute-a-work-order.md).
5. Set the tag to `false`, then `true`. Now a new work order appears, because nothing is open.

:::

You can also check the gateway log. Search for the `trainingMaintenance` logger to see each decision the script made.

## What You Built

You built an automatic corrective work order. A machine signal goes true, a gateway tag script calls `trainingMaintenance.raiseCoolantLowWorkOrder`, and Kanoa raises one work order from the `Machine 1 - Coolant low` template. While that work order is open, the signal can go true as often as it likes and nothing more is raised. You can copy this pattern for any signal, such as a spindle alarm, by changing the template title and the tag.
