Skip to main content

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.

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:

    FieldValue
    TitleMachine 1 - Coolant low
    DescriptionMachine 1 reported low coolant. Check the level and top up. Look for leaks.
    AssetCoreForge\Philadelphia\Machining\Machine 1
    Maintenance typeCorrective
    PriorityHigh
    Requested byYour own user
    Schedule typeOne Time
  3. Save it. Leave its version status as Draft for now.

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:

    SettingValue
    NameMachine1CoolantLow
    Tag typeMemory Tag
    Data typeBoolean
    Valuefalse

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.
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:

    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.

Reference Materials: getWorkOrderEvents

Retrieves work order events matching the optional filter criteria supplied in paramsDict. Each row in the returned dataset represents a single work order event � a specific scheduled or requested occurrence of a work order being executed on an asset, rather than the work order definition itself. All keys within paramsDict are optional; any key that is omitted is simply not applied as a filter, so calling the function with an empty dictionary returns all work order events.


Parameters​

paramsDict Dictionary

- assetIdIntegerThe asset the work order event is on, exactly
- assetPathStringEvery asset whose path starts with this (the asset and those under it, and a sibling whose name starts the same, such as Machine 10 for Machine 1). Use assetId for one asset
- assignedToInteger
- endDateDateTimeWith startDate
- isActiveBoolean
- requestedByInteger
- scheduleTypeIdInteger
- scheduleTypeNameString
- startDateDateTimeWith endDate: closed work order events due in the window. Active ones are returned whatever their due date (with isActive False, only closed ones due in the window)
- titleString
- workOrderEventNameString
- workOrderIdInteger
- workOrderNameTitleStringfilter on both the workOrderName and the title field
- workOrderPriorityIdInteger
- workOrderPriorityNameString
- workOrderEventStatusCategoryIdInteger
- workOrderEventStatusCategoryNameString
- workOrderEventStatusIdInteger
- workOrderEventStatusNameString

Returns​

workOrderEventData pyDataset


Example​

# An asset's work order events due in the last week, and any still open
paramsDict = {'assetId': 6121, 'startDate': system.date.addDays(system.date.now(), -7), 'endDate': system.date.now()}
events = system.kanoa.cmms.getWorkOrderEvents(paramsDict)

# Get all work order events currently 'In Progress'
paramsDict = {"workOrderStatusName": "In Progress"}
data = system.kanoa.utilities.convertDatasetToJSON(system.kanoa.cmms.getWorkOrderEvents(paramsDict))

for i, row in enumerate(data):
print 'Row %i'%i
for k,v in row.items():
print k,v

break #Just limiting to returning the columns from the first record for display purposes
>>>
Row 0
workOrderEventStatusName Completed
workOrderEventStatusId 6
workOrderEventName MWO00047
workOrderPriorityName Low
scheduleTypeName One Time
workOrderPriorityIconPath None
dueDate Sat Mar 14 14:00:01 UTC 2026
description
conditionName None
isActive False
title jjj
workOrderEventStatusCategoryId 4
enabled True
assignedTo None
changedDate Tue Mar 17 01:53:29 UTC 2026
workOrderEventStatusColor #CCFFCC
workOrderPriorityColor --kcGray-10
maintenanceSubTypeId None
conditionId None
assetId None
assetPath None
changedBy 5
procedureName None
maintenanceSubTypeName None
workOrderEventId 4
assignedUser None
scheduleTypeId 1
maintenanceTypeId 1
conditionInfo None
lastGeneratedDate None
workOrderEventStatusCategoryName Closed
procedureId None
requestedBy 5
createdDate Sat Mar 14 14:01:55 UTC 2026
workOrderPriorityId 1
createdBy 5
lastGeneratedValue None
maintenanceTypeColor --kcBlue-20
assetName None
workOrderId 67
occurrenceKey None
requestedByUser jason
maintenanceTypeName Corrective
workOrderConditionId None
>>>
Reference Materials: addWorkOrderScheduleEvent

Adds the maintenance work order (MWO) that a work order schedule or condition generates. Use it from a custom generation job instead of waiting for the automatic generation to run. The MWO is named by the next serial number of the work order's maintenance type. If an MWO of the same work order is still open, this one is still added, but as Missed, with a note on its status change naming the open one. Then the schedule or condition that generated it is stamped with the due date. To add an MWO with a name and status of your own, use addWorkOrderEvent instead.


Parameters​

workOrderEventInfo Dictionary

- workOrderIdIntegerRequired. Id of the work order template
- workOrderPriorityIdIntegerRequired. Id of the priority, from getWorkOrderPriorities
- requestedByIntegerRequired. Id of the user who requested the work
- dueDateDateTimeRequired. When the work is due
- assetIdIntegerOptional. Id of the asset the work is done on
- assignedToIntegerOptional. Id of the user the MWO is assigned to
- maintenanceSubTypeIdIntegerOptional. Id of the maintenance sub type, from getMaintenanceSubTypes
- workOrderEventStatusIdIntegerOptional. Defaults to Assigned when assignedTo is set, else Open. Missed when an MWO of this work order is still open
- workOrderScheduleIdIntegerOptional. Id of the work order schedule that generated the MWO. It's stamped with the dueDate
- workOrderConditionIdIntegerOptional. Id of the work order condition that generated the MWO. It's stamped with the dueDate and currentValue
- conditionIdIntegerOptional. The older name for workOrderConditionId, read when that isn't given
- currentValueFloatOptional. The condition value that generated the MWO

userId Integer:Id of the user executing the function


Returns​

workOrderEventId Integer None if the MWO wasn't added
message String None if success. When the MWO was added but the schedule or condition couldn't be stamped, both are set


Example​

# Add the next seal inspection MWO for Machine 1 from its schedule, due in a week
userId = system.kanoa.security.getIDPUserId({'userName': 'SYSTEM'})
workOrders = system.kanoa.cmms.getWorkOrders({'workOrderName': 'Seal Inspection'})
workOrderId = system.kanoa.utilities.getFieldValue('workOrderId', workOrders)
workOrderPriorityId = system.kanoa.utilities.getFieldValue('workOrderPriorityId', workOrders)
workOrderScheduleId = system.kanoa.utilities.getFieldValue('workOrderScheduleId', system.kanoa.cmms.getWorkOrderSchedule({'workOrderId': workOrderId}))
assetId = system.kanoa.utilities.getFieldValue('assetId', system.kanoa.asset.getAssets({'assetPath': 'CoreForge/Philadelphia/Machining/Machine 1'}))

workOrderEventInfo = {
'workOrderId': workOrderId,
'workOrderPriorityId': workOrderPriorityId,
'requestedBy': userId,
'dueDate': system.date.addDays(system.date.now(), 7),
'assetId': assetId,
'workOrderScheduleId': workOrderScheduleId
}
workOrderEventId, message = system.kanoa.cmms.addWorkOrderScheduleEvent(workOrderEventInfo, userId)
print workOrderEventId, message

Test It from the Script Console​

Test the function before you wire it to a tag.

Run the function twice
  1. Open the Script Console in the Designer (Tools → Script Console).

  2. Run this:

    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​

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:

    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.

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

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.
  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.