Work Order Enterprise Synchronization

Sepasoft MES Module Suite

Work Order Enterprise Synchronization

This guide explains how Sepasoft MES distributes Work Orders across an MES Enterprise network, how to enable operations-based synchronization, and how to create, schedule, and maintain Work Orders through scripting.

Operations-based synchronization sends a Work Order to the gateways responsible for equipment on the linked operations. That equipment includes the Operations Request or Operations Response equipment reference and the equipment on the Request Segments or Response Segments linked to those operations.

This description matches the current MES core implementation. Confirm it against the installed module version before production use.

Choose a synchronization strategy

MES sends objects through the parent and child gateway hierarchy to the gateways that need them. A Work Order uses parent-and-child synchronization. Its destination list comes from the equipment paths associated with the Work Order. The JVM argument below selects how those paths are calculated.

StrategyHow MES determines destinationsAppropriate use
Material based, the defaultOperations Segments that reference the Work Order's Material Definition, including child Material Definitions, plus equipment and material-storage locations on those segmentsEvery capable site should receive the Work Order, or the material is produced at only one site.
Operations based, optionalEquipment on enabled Operations Requests and Operations Responses that reference the Work Order, including equipment on their Request Segments and Response SegmentsWork Orders should reach a site when work is assigned to equipment that site manages.

The gateway that saves a Work Order, or that answers a pull for one, uses its own local JVM value. A gateway that only receives a Work Order does not recalculate the strategy on receipt. Use the same value on every gateway that creates or saves Work Orders. The code does not detect or reject mixed values. Different values produce different destinations depending on which gateway last calculated them.

Material based synchronization

When the JVM argument is absent, blank, MATERIAL, or any value other than OPERATIONS or RESPONSE, MES uses the material path:

  1. Start from the Work Order's Material Definition.
  2. Include Operations Segments that reference that material, and Operations Segments that reference a child Material Definition.
  3. Include the equipment on those segments and the storage equipment referenced by their material properties.
  4. Send the Work Order to every parent and child gateway whose equipment path matches one of those paths.

If many sites can produce the material, those sites receive the Work Order.

Operations based synchronization

When the strategy is OPERATIONS or RESPONSE, MES builds the destination list from linked operations:

  1. Load enabled Operations Requests and Operations Responses whose Work Order reference is this Work Order.
  2. Include an operation when its begin time is inside the default window and its end time is inside that window or is null. The default window runs from DateUtilities.getDate(1970, 1, 1) through DateUtilities.getDate(2200, 1, 1).
  3. For each matching operation, include its equipment reference and the equipment on its Request Segments or Response Segments, including material-storage locations on those segments.
  4. Send the Work Order toward the parent and child gateways that match those paths.

Creating a Work Order with no matching operations leaves the associated equipment set empty. MES does not send that Work Order to other gateways. It remains on the gateway where it was saved, which is typically the enterprise gateway.

If loading the linked operations throws, MES logs the error and leaves the equipment set empty. It does not switch to material-based targeting. If one linked operation fails to load, MES skips that operation and continues with the others.

Requirements and gateway setup

Configure the strategy on every gateway that creates or saves Work Orders. The examples assume that the MES Enterprise network is already configured, the Material Definition exists, and the equipment and operation definitions required for scheduling are available on the gateway running the scripts.

Enable operations based synchronization

  1. Add this JVM argument to each applicable gateway:

    -Dcom.sepasoft.sync.workOrderStrategy=OPERATIONS 
  2. Use the configuration location for your Ignition version:

    Ignition versionConfiguration location
    8.1Gateway Configure > System > Gateway Settings, or a wrapper.java.additional line in ignition.conf
    8.3The platform extra JVM arguments for the gateway, using the same -D flag
  3. Restart each gateway after adding the argument. MES reads the property on each destination calculation. A restart is required because a -D argument is applied when the gateway process starts.

  4. Confirm that every gateway which creates or saves Work Orders uses the same strategy.

Success Set the same value on the enterprise gateway and on all site gateways. MES does not support mixed values in one network

There is no Gateway Config checkbox for this setting. Changing the argument does not remove Work Order copies already stored on other gateways.

Supported argument values

ValueEffective behavior
Not set, blank, MATERIAL, or any other valueMaterial-based synchronization, the default
OPERATIONSOperations-based synchronization. Matching is case-insensitive.
RESPONSESame behavior as OPERATIONS. Matching is case-insensitive.

Leading or trailing spaces are significant. OPERATIONS matches. OPERATIONS does not, and MES treats it as material-based synchronization.

Synchronization behavior and triggers

A Work Order is distributed in two related ways:

  • When the Work Order itself is saved, MES dispatches it to the gateways that match its current equipment paths.

  • When an Operations Request, Operations Response, Request Segment, or Response Segment is saved, MES dispatches that object to the gateways that match its equipment paths. A gateway that receives the object and does not already have the referenced Work Order pulls the Work Order, if the Work Order's current equipment paths match that gateway.

A Work Order created under OPERATIONS before any operation exists has an empty path list, so that first save is not sent. Saving an operation later does not replay the Work Order's earlier changelog. The Work Order arrives with the operation, through the pull described above.

Previously delivered copies stay in place. MES does not delete a Work Order from a gateway when the assignment later points somewhere else.

Where the Work Order is distributed

Work Order or operations conditionDistribution behavior
Work Order saved with no enabled operation inside the default date windowStays on the saving gateway.
Linked Operations Request or Operations Response has equipment on the operation or on its segmentsThe operation is sent to the gateways that manage that equipment. Those gateways pull the Work Order when they do not already have it and the Work Order's paths match them.
Operation or segment equipment changes to a different siteThe changed object is sent to the new site. The new site can pull the Work Order. The previous site keeps the copy it already has.
A linked request or response is disabled or deletedThat operation's removal is synchronized. The Work Order is not sent again because of the deletion. Later path calculations ignore disabled operations. Existing Work Order copies remain.
MES cannot load the operations listThe Work Order is not sent to other gateways from that calculation. MES does not fall back to material-based targeting.

Events that can deliver the Work Order to a site

  • Saving an Operations Request or Operations Response that references the Work Order and has equipment on the operation or on its segments.

  • Changing the equipment reference on a linked Operations Request or Operations Response.

  • Changing the equipment on a Request Segment or Response Segment of a linked operation. The segment is synchronized, the receiving gateway pulls the missing operation, and that pull can pull the Work Order.

  • Changing the Work Order reference on an Operations Request or Operations Response. Gateways that receive the operation can pull the newly referenced Work Order when its paths match them.

Changes that leave the Work Order where it already is

  • Quantity or state updates on an Operations Response, by themselves. Those updates synchronize the response or segment to its current destinations. They do not add new Work Order destinations.

  • Disabling or deleting a linked Operations Request or Operations Response. No additional site receives the Work Order because of that deletion.

Create and distribute a Work Order

Use this sequence when operations-based synchronization is enabled:

  1. Create the Work Order on the enterprise gateway. Use an ERP import, the Work Order Table, or system.mes.workorder.createMESWorkOrder(). With no matching operation, it remains on that gateway.

  2. Create and save the operations assignment. Save an Operations Request or Operations Response that references the Work Order. system.mes.scheduleOperations() sets the Operations Request equipment to the equipment selected for its Request Segments. Segment equipment is also part of the destination calculation.

  3. Allow enterprise synchronization to complete. The operation is sent to the assigned site. That site pulls the Work Order if the Work Order's paths match the site.

  4. Maintain schedule entries separately. Closing or deleting a Work Order does not delete its schedule entries. Review those entries and remove the ones that are no longer needed.

Run the scheduling script on a gateway that already has the Work Order. Before the operation is synchronized, a site gateway does not have a Work Order created on the enterprise gateway.

Example with two sites

The Material Definition Bottle 500ml can run at Site A and Site B.

ActionMaterial basedOperations based
Create WO-1000 for Bottle 500mlSite A and Site B receive it.It remains on the creating gateway.
Save a linked Operations Request whose segments run on Site A Line 1Both sites already have it.Site A receives the request and pulls the Work Order. Site B does not receive a copy from this assignment.
Later link an operations object for Site BBoth sites already have it.Site B becomes a destination as well. Site A keeps the copy it already has.

Scripting reference

These examples use Ignition's system scripting namespace and Jython syntax. Define the functions in a gateway-accessible project script module, and qualify calls with the module path when calling them from other scripts.

FunctionPurposeExecution location
create_work_orderCreate and save a Work Order for an existing materialEnterprise gateway
schedule_work_orderCreate and save schedule objects for a Work Order on a lineThe gateway that already has the Work Order
clean_closed_schedulesFind or delete schedule entries for closed or disabled Work Orders inside a date windowEnterprise gateway, or another gateway that holds the schedule entries. A gateway timer script can call it periodically.

Validate the scripts against the installed MES version and equipment model before production use.

Script 1 Create a Work Order

Create a Work Order for an existing Material Definition, set its quantity and due date, and save it. Under operations-based synchronization, this save stays on the current gateway until a matching operation exists.

ParameterTypeDescription
work_order_nameStringUnique name for the new Work Order
material_nameStringName of an existing Material Definition
quantityNumberTarget production quantity
due_dateDateOptional. Defaults to seven days from the current time.

Returns: The saved MES Work Order object.

system.mes.getMESObjectLinkByName throws when the name is missing. system.mes.workorder.createMESWorkOrder throws when the name already exists or the link is not a Material Definition. The except blocks below treat every lookup failure as "not found." Distinguish a missing object from other failures before using this in an unattended import.

Python
def create_work_order(work_order_name, material_name, quantity, due_date=None):
    # Do not overwrite an existing Work Order.
    try:
        existing = system.mes.getMESObjectLinkByName(
            "WorkOrder", work_order_name)
    except:
        existing = None

    if existing is not None:
        raise Exception("Work order already exists: " + work_order_name)

    try:
        material_link = system.mes.getMESObjectLinkByName(
            "MaterialDef", material_name)
    except:
        material_link = None

    if material_link is None:
        raise Exception("Material definition not found: " + material_name)

    if due_date is None:
        due_date = system.date.addDays(system.date.now(), 7)

    work_order = system.mes.workorder.createMESWorkOrder(
        work_order_name, material_link)
    work_order.setWorkOrderQuantity(float(quantity))
    work_order.setDueDate(due_date)
    system.mes.saveMESObject(work_order)
    return work_order

Example:

Python
wo = create_work_order("WO-0001", "Bottle 500ml", 1000)
print "Created", wo.getName(), "for", wo.getMaterialRefName()

Script 2 Schedule a Work Order on a line

Create schedule objects from an Operations Definition, set the Work Order reference on the Operations Request, and schedule it.

system.mes.createSchedule throws when the Operations Definition is not execute-ready.

system.mes.scheduleOperations selects equipment from the Request Segments and writes that equipment onto the Operations Request and the segments. The default schedule event then sets each segment's end time from the segment material quantity, rate, and rate period, and it moves the window for equipment restrictions and existing schedule entries when overlapping is disabled.

The example uses the OEE naming convention MaterialName-Enterprise:Site:Area:Line.

ParameterTypeDescription
work_order_nameStringName of an existing Work Order
line_pathStringEquipment path, such as Enterprise\Site A\Packaging\Line 1
start_dateDatePreferred start time
quantityNumberOptional. Defaults to the Work Order's remaining quantity, which is target quantity minus actual quantity.
allow_overlappingBooleanOptional. Defaults to False.

Returns: The saved schedule objects, including Operations Schedule, Operations Request, and Request Segment objects.

Python
def schedule_work_order(work_order_name, line_path, start_date,
                        quantity=None, allow_overlapping=False):
    try:
        work_order = system.mes.workorder.getMESWorkOrder(work_order_name)
    except:
        work_order = None

    if work_order is None:
        raise Exception("Work order not found: " + work_order_name)

    if quantity is None:
        quantity = work_order.getRemainingQuantity()

    material_link = work_order.getMaterialRef()
    material_name = material_link.getName()

    # OEE convention: MaterialName-Enterprise:Site:Area:Line
    colon_path = line_path.replace("\\", ":")
    operation_name = material_name + "-" + colon_path

    try:
        operation_link = system.mes.getMESObjectLinkByName(
            "OperationsDefinition", operation_name)
    except:
        operation_link = None

    if operation_link is None:
        raise Exception("Operations Definition not found: " + operation_name)

    operation_definition = operation_link.getMESObject()
    schedule = system.mes.createSchedule(operation_definition)

    for index in range(schedule.size()):
        mes_object = schedule.get(index)
        type_name = mes_object.getMESObjectType().getName()

        if type_name == "OperationsSchedule":
            mes_object.setScheduleProductionCount(float(quantity))

        elif type_name == "OperationsRequest":
            updated = mes_object.setPropertyValue(
                "WorkOrderRefUUID", work_order.getUUID())
            if not updated:
                raise Exception(
                    "WorkOrderRefUUID was not set on " + mes_object.getName())

        elif type_name == "RequestSegment":
            has_material = (
                mes_object.getComplexPropertyCount("ResponseMaterial") > 0)
            if has_material:
                options = mes_object.getAvailableMaterialOptions("Material Out")
                if options.size() > 0:
                    mes_object.setMaterial(
                        "Material Out", material_name, line_path, float(quantity))

    scheduled_list = system.mes.scheduleOperations(
        schedule, start_date, allow_overlapping, "Active")
    system.mes.saveSchedule(scheduled_list)
    return scheduled_list

Example:

Python
line_path = "Enterprise\\Site A\\Packaging\\Line 1"
start_date = system.date.addMinutes(system.date.now(), 30)
result = schedule_work_order("WO-0001", line_path, start_date)

for index in range(result.size()):
    mes_object = result.get(index)
    if mes_object.getMESObjectType().getName() == "OperationsRequest":
        print "Begin:", mes_object.getPropertyValue("BeginDateTime")
        print "End: ", mes_object.getPropertyValue("EndDateTime")
        print "Equipment:", mes_object.getEquipmentRefUUID()

Check before use:

  • The Operations Definition must be execute-ready. createSchedule throws when it is not.

  • After scheduleOperations returns, confirm the Operations Request equipment reference is the intended line. The scheduling call sets it from the Request Segment equipment it selects.

  • setPropertyValue returns false when the property path is missing. The example raises in that case.

  • ResponseMaterial is the complex-property type on a Request Segment. Material Out is the default OEE material resource name. Use the resource name configured on the operation.

  • The OEE operation name is the material name, a hyphen, and the equipment path with backslashes replaced by colons. A project prefix on the path will not match that name.

  • The end time comes from the segment schedule event. The default handler uses the material property's quantity, rate, and rate period, then applies restrictions and existing entries.

Script 3 Clean schedule entries for closed or deleted Work Orders

Closing or deleting a Work Order does not delete its schedule entries. system.mes.workorder.deleteMESWorkOrder disables the Work Order and leaves the row in place. This example searches selected lines inside a date window and finds schedules whose Work Order is disabled or closed.

The default window runs from midnight 30 days before today through midnight 30 days after today. Entries outside that window are not reviewed.

ParameterTypeDescription
line_pathsList of stringsEquipment paths of the lines to inspect
dry_runBooleanOptional. Defaults to True. Reports candidates and does not delete them.
days_backIntegerOptional. Defaults to 30 days before today.
days_aheadIntegerOptional. Defaults to 30 days after today.

Returns: A list of Operations Schedule UUIDs reported in dry-run mode, or disabled in deletion mode.

ConditionAction
Entry has no Work Order linkSkip it.
Work Order load fails or returns no objectReport it and skip it. A load failure is not treated as deletion.
Loaded Work Order has isEnabled() falseClassify it as deleted. deleteMESWorkOrder disables the Work Order.
Loaded Work Order has isClosed() trueClassify it as closed.
Work Order is open and enabledKeep its schedule.
Entry state is 2 or 5Skip it. These are the in-process states. Both display as Active.
Entry state is 7This is Faulted. The script does not protect it. A closed or disabled Work Order with a faulted entry is a deletion candidate.
Entry has no Operations Schedule linkSkip it.
Schedule UUID has already been handled in this passSkip the duplicate.
Candidate meets the rules and dry_run=TruePrint it and return its UUID.
Candidate meets the rules and dry_run=FalseCall system.mes.deleteSchedule and return its UUID.

Deletion caution: Run with dry_run=True first. deleteSchedule disables the schedule and the objects loaded with it. It does not remove rows, and this script does not remove Work Order copies stored at other sites. States 0 through 7 are:

CodeMeaningDisplay string
0Selected / unknownError - Unknown
1Auto incompleteAuto - Incomplete
2Auto in processActive
3Auto completeComplete
4Manual incompleteManual - Incomplete
5Manual in processActive
6Manual completeComplete
7FaultedFaulted

Python
# In-process schedule states. Both display as "Active".
# Faulted (7) is intentionally not included.
ACTIVE_STATES = [2, 5]


def get_date_range(days_back, days_ahead):
    today = system.date.midnight(system.date.now())
    start_date = system.date.addDays(today, -days_back)
    end_date = system.date.addDays(today, days_ahead)
    return start_date, end_date


def get_delete_reason(work_order_link):
    # An unavailable object is not proof that a Work Order was deleted.
    try:
        work_order = work_order_link.getMESObject()
    except Exception as error:
        print "SKIP (cannot load Work Order):", str(error)
        return None

    if work_order is None:
        print "SKIP (Work Order unavailable)"
        return None

    if not work_order.isEnabled():
        return "deleted"

    if work_order.isClosed():
        return "closed"

    return None


def clean_closed_schedules(line_paths, dry_run=True,
                           days_back=30, days_ahead=30):
    start_date, end_date = get_date_range(days_back, days_ahead)
    handled_uuids = []

    for line_path in line_paths:
        entries = system.mes.getEquipmentScheduleEntries(
            line_path, start_date, end_date, "Active", False)

        for entry in entries:
            work_order_link = entry.getWorkOrderLink()
            if work_order_link is None:
                continue

            work_order_name = work_order_link.getName()
            reason = get_delete_reason(work_order_link)
            if reason is None:
                continue

            if entry.getState() in ACTIVE_STATES:
                print "SKIP (running):", work_order_name, "on", line_path
                continue

            if not entry.hasMESOperationsScheduleLink():
                continue

            schedule_uuid = (
                entry.getMESOperationsScheduleLink().getMESObjectUUID())
            if schedule_uuid in handled_uuids:
                continue

            action = "WOULD DELETE" if dry_run else "DELETE"
            print action, "(" + reason + "):", work_order_name, "on", \
                line_path, "starting", entry.getScheduledStartDate()

            if not dry_run:
                system.mes.deleteSchedule(schedule_uuid)
            handled_uuids.append(schedule_uuid)

    outcome = "found" if dry_run else "deleted"
    print "Done.", len(handled_uuids), "schedule(s)", outcome
    return handled_uuids

Example gateway timer call after the functions are available in the relevant script scope:

Python
lines = [
    "Enterprise\\Site A\\Packaging\\Line 1",
    "Enterprise\\Site A\\Packaging\\Line 2",
]

clean_closed_schedules(
    lines, dry_run=True, days_back=30, days_ahead=30)

Run this after reviewing a dry run and choosing a date window that matches the schedules you need to maintain. When the functions live in a project script module, prefix the call with that module's path.

Limitations

Existing copies remain at previously targeted sites

Turning on OPERATIONS leaves Work Order copies that were already sent under material-based synchronization. Those copies remain until a separate retention or cleanup process handles them. Moving an assignment to another site delivers the Work Order to the new site and leaves the previous site's copy in place.

Operations must be enabled and loadable

An operations-based Work Order stays on its saving gateway until an enabled Operations Request or Operations Response in the default date window supplies equipment, either on the operation or on its segments. If MES cannot load the operations list, it does not use the material's capable sites.

Disabled operations are excluded from the destination calculation.

Schedule maintenance is separate from synchronization

clean_closed_schedules disables schedule objects. It does not remove Work Order copies from other sites, and it is not a migration tool for copies sent before OPERATIONS was enabled.

Troubleshooting

SymptomChecks and explanation
Newly created Work Order is absent at all sitesExpected under OPERATIONS until an enabled linked request or response has equipment on the operation or on its segments. Save that assignment and allow synchronization to finish. The site pulls the Work Order with the operation.
Work Order is absent at the assigned site after synchronizationCheck the Work Order reference, equipment on the operation and on its segments, whether the operation is enabled and inside the default date window, the sending gateway's strategy, and enterprise synchronization health.
Every capable site receives a newly created Work OrderThe effective value is material-based. Check for a missing, blank, or unrecognized argument, including surrounding spaces. Confirm the saving gateway was restarted after the argument was added.
Extra sites still show old Work Orders after switching strategiesCopies already delivered stay where they are. Use the normal retention or cleanup process for those copies.
Work Order appears at a site after only a segment equipment changeExpected. Segment equipment is part of the path calculation, and the segment sync can pull the operation and then the Work Order.
Quantity or state updates do not send the Work Order to a new siteExpected. Progress updates synchronize the response or segment to its current destinations.
Scheduling script cannot find the Work Order at a siteRun it on the gateway that already has the Work Order, usually the enterprise gateway, until synchronization has delivered it.
Scheduling script cannot find an Operations DefinitionCheck the material name, the colon-separated equipment path, and the OEE naming convention against the configured operation.
createSchedule throws because the definition is not execute-readyMark the Operations Definition execute-ready, or schedule a definition that already is.
End time is unexpectedReview the segment material quantity, rate, and rate period, plus equipment restrictions and existing schedule entries.
Schedule entries remain after a Work Order closes or is deletedExpected. Review them with the cleanup script. Use a dry run before disabling schedules.
Cleanup skips a Work Order it cannot loadInvestigate the load error. The example does not treat an unavailable object as a deleted object.
Cleanup includes a faulted entryState 7 is Faulted and is a deletion candidate when the Work Order is closed or disabled. Add 7 to ACTIVE_STATES if faulted entries must be kept.
Old schedule entries persist outside the cleanup windowThe default window is midnight 30 days before today through midnight 30 days after today. Widen days_back and days_ahead to review more entries.

Related documentation

Sepasoft MES Module Suite