# Move Templates Between Gateways

You built `Machine 1 - Weekly PM` on a test gateway and it works. Now production needs the same template. You could rebuild it by hand, and get a field wrong. Instead you export it from one gateway and import it into the other.

Two functions do this: `exportWorkOrderTemplates` and `importWorkOrderTemplates`. The export is a JSON file, so you can keep it in source control as well.

## What Moves and What Doesn't

Know this before you start. It decides what you need to prepare on the target gateway.

| Moves with the template | Doesn't move |
| --- | --- |
| The template fields, its schedule, conditions and alert groups | Work orders already raised from the template |
| The procedure it uses, with its steps and checks | Technicians and part plans |
| Maintenance types and sub types, data types, engineering units, pick lists | The last generated date and value, and audit information |
| | Images on procedure checks |
| | Users |

Kanoa matches references by name, not by id, because ids differ between gateways. That has consequences:

- The **asset**, **priority**, **schedule type**, **condition** and **counter** must already exist on the target gateway. A missing one is an error, and nothing is imported.
- A missing maintenance type, sub type, procedure, data type, engineering unit or pick list is created for you.
- A missing alert group is left off the template, with a warning.
- Users are not matched. A new template is requested by the user who runs the import, and it is unassigned.
- Every imported template is saved as **Draft**. Someone must release it.

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

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

## Export from the Test Gateway

:::action[Export the template]

1. Open the Designer on the **test** gateway and open the Script Console.
2. Run this script. It finds `Machine 1 - Weekly PM` by title and saves the export to a file on your computer:

   ```python
   templates = system.kanoa.cmms.getWorkOrders({'title': 'Machine 1 - Weekly PM'})
   workOrderId = system.kanoa.utilities.getFieldValue('workOrderId', templates)

   exportData, message = system.kanoa.cmms.exportWorkOrderTemplates({'workOrderIdList': [workOrderId]})
   if exportData is None:
       print 'Export failed:', message
   else:
       path = system.file.saveFile('workOrderTemplates.json')
       if path:
           system.file.writeFile(path, system.util.jsonEncode(exportData))
           print 'Saved', path
           print 'Exported:', [t['title'] for t in the templates list in the export data]
   ```

3. Choose where to save the file when asked.

:::

{/*
TODO: Confirm on a gateway that each template in the templates list in the export data has a 'title' key.
The reference lists the keys of exportData['data'] but not of a template.
If it differs, change the last print to show the template list another way.
*/}

Leave `workOrderIdList` empty, or leave it out, to export every template.

:::note
In a Perspective view, such as an admin button, save the export with `system.perspective.download('workOrderTemplates.json', system.util.jsonEncode(exportData))`. The browser then downloads it. The Script Console has no browser, so the script above writes a file instead.
:::

## Import into Production

Always run the import as a **dry run** first. A dry run is the default. It reports what would happen and writes nothing. The import is all or nothing, so one template with an error stops all of them.

:::action[Dry run the import]

1. Open the Designer on the **production** gateway and open the Script Console.
2. Make sure `Machine 1`, its priorities and its schedule types exist there. If production has a different asset path, fix that first.
3. Run this script:

   ```python
   path = system.file.openFile('json')
   if path:
       fileText = system.file.readFileAsString(path)
       userId = system.kanoa.security.getIDPUserId({'userName': 'SYSTEM'})
       paramsDict = {'data': fileText, 'onDuplicate': 'rename', 'dryRun': True}
       result = system.kanoa.cmms.importWorkOrderTemplates(paramsDict, userId)

       print 'Passed:', result['passed']
       print result['message']
       for r in result['results']:
           print r['title'], '->', r['action']
           for w in r['warnings']:
               print '  warning:', w
           for e in r['errors']:
               print '  error:', e
   ```

4. Read the output. Each template shows an action of `create`, `rename`, `overwrite` or `skip`. A template with errors shows `None`.

:::

If `passed` is false, fix the errors the script printed. A typical one is an asset path that doesn't exist on production. Then run the dry run again.

When the dry run passes, import for real.

:::action[Import the template]

1. Change `'dryRun': True` to `'dryRun': False` and run the script again.
2. Navigate to **Configuration → Maintenance → Work Orders** and find `Machine 1 - Weekly PM`.
3. Check that its **Procedure** is `Machine 1 Weekly PM` and its schedule is weekly.
4. Assign the technician you want, and set the version status to **Released**.

:::

The template is Draft until you release it, so nothing is scheduled until a person decides it should be.

## Choose What to Do with Duplicates

What if the template is already on production? `onDuplicate` decides. A duplicate is a template with the same maintenance type and title.

| `onDuplicate` | What happens |
| --- | --- |
| `rename` (default) | The import is added as a new template, with a timestamp added to its title |
| `skip` | The existing template is left alone |
| `overwrite` | The existing template's fields, schedule, conditions and alert groups are replaced. It is an error if more than one template matches |

:::tip
If you only have one gateway for training, import the file back into the same gateway with `onDuplicate` set to `rename`. Then try `skip` and `overwrite` in dry runs and compare the actions.
:::

:::warning
An overwritten template keeps its own assigned user, because users are not matched. Procedures that already exist with the same path are reused, not replaced.
:::

## What You Built

You moved a work order template from one gateway to another. You exported `Machine 1 - Weekly PM` with its procedure, previewed the import with a dry run, then imported it as a Draft template on production. You also know what the file does not carry: work orders, technicians, users and check images. Use the same two functions to put your templates in source control or to roll a standard set of maintenance out to every plant.
