Document toolboxDocument toolbox

(v1) .Custom Events Library v2019.2

For details on writing a Custom Event Endpoint, please see our wiki article.

Equipment Details Sync

Sync Service GLA, Owner and Location to Equipment

Equipment Details Sync
<?php
/**
* Event: Custom PHP Event
* Frequency: Hourly
* Time:
* Listener Class: Core_Model_Event
* Listener Method: eventCustom
*/

PCR_Event::attachDb("equipment-bulk-update", ["Application_Model_Equipment_Equipment" => "eventBulkUpdate"]);

$records = $this->query(<<<SQL
        SELECT
          S.RECID AS SERVICES_RECID,
          E.RECID AS EQUIPMENT_RECID,
          S.OWNER_CONTACTS_RECID AS SERVICE_OWNER_CONTACTS_RECID,
          E.OWNER_CONTACTS_RECID AS EQUIPMENT_OWNER_CONTACTS_RECID,
          S.OWNER_DEPT_HIERARCHY_RECID AS SERVICE_OWNER_DEPT_HIERARCHY_RECID,
          E.OWNER_DEPT_HIERARCHY_RECID AS EQUIPMENT_OWNER_DEPT_HIERARCHY_RECID,
        CASE
          WHEN S.OWNER_CONTACTS_RECID IS NULL
            THEN SDH.BILLING_GROUPS_RECID
          WHEN SCON.BILLING_GROUPS_RECID IS NULL 
            THEN SCON_DEPT.BILLING_GROUPS_RECID
          ELSE SCON.BILLING_GROUPS_RECID
          END AS SERVICE_BILLING_GROUP,
        CASE
          WHEN E.OWNER_CONTACTS_RECID IS NULL 
            THEN EDH.BILLING_GROUPS_RECID
          WHEN ECON.BILLING_GROUPS_RECID IS NULL 
            THEN ECON_DEPT.BILLING_GROUPS_RECID
          ELSE ECON.BILLING_GROUPS_RECID
          END AS EQUIPMENT_BILLING_GROUP,
        SEG.GLA_RECID AS SERVICE_GLA,
        EEG.GLA_RECID AS EQUIPMENT_GLA,
        S.LOCATIONS_RECID AS SERVICE_LOCATION,
        E.LOCATIONS_RECID AS EQUIPMENT_LOCATION,
        S.MULTIPLE_LOCATIONS,
        COALESCE(EG.FORMAT,SG.FORMAT) AS GLA_FORMAT,
        E.BILLABLE,
        E.WARRANTY_END_DATE

        FROM SERVICES S
        JOIN SERVICES_EQUIPMENT SE ON S.RECID = SE.SERVICES_RECID
        JOIN EQUIPMENT E ON SE.EQUIPMENT_RECID = E.RECID
        LEFT JOIN DEPT_HIERARCHY EDH ON E.OWNER_DEPT_HIERARCHY_RECID = EDH.RECID
        LEFT JOIN DEPT_HIERARCHY SDH ON S.OWNER_DEPT_HIERARCHY_RECID = SDH.RECID
        LEFT JOIN CONTACTS ECON ON E.OWNER_CONTACTS_RECID = ECON.RECID
        LEFT JOIN DEPT_HIERARCHY ECON_DEPT ON ECON.DEPT_HIERARCHY_RECID = ECON_DEPT.RECID
        LEFT JOIN CONTACTS SCON ON S.OWNER_CONTACTS_RECID = SCON.RECID
        LEFT JOIN DEPT_HIERARCHY SCON_DEPT ON SCON.DEPT_HIERARCHY_RECID = SCON_DEPT.RECID
        LEFT JOIN SERVICES_EXPENSE_GLA SEG ON S.RECID = SEG.SERVICES_RECID
        LEFT JOIN EQUIPMENT_EXPENSE_GLA EEG ON E.RECID = EEG.EQUIPMENT_RECID
        LEFT JOIN LISTS SEGL ON SEG.EXPENSE_TYPE_LISTS_RECID = SEGL.RECID
        LEFT JOIN LISTS EEGL ON EEG.EXPENSE_TYPE_LISTS_RECID = EEGL.RECID
        LEFT JOIN GLA EG ON EEG.GLA_RECID = EG.RECID
        LEFT JOIN GLA SG ON SEG.GLA_RECID = SG.RECID

        WHERE
        -- GLAs are Default and 100% or are not set
        (
          ((SEGL.CODE = 'DEFAULT' AND SEG.PERCENT = 100) OR SEGL.CODE IS NULL)
          AND
          ((EEGL.CODE = 'DEFAULT' AND SEG.PERCENT = 100) OR EEGL.CODE IS NULL)
        )
        -- if the OWNER is different
        AND
        (
            (
              (S.OWNER_CONTACTS_RECID <> E.OWNER_CONTACTS_RECID AND S.OWNER_CONTACTS_RECID IS NOT NULL AND E.OWNER_CONTACTS_RECID IS NOT NULL)
              OR (S.OWNER_DEPT_HIERARCHY_RECID <> E.OWNER_DEPT_HIERARCHY_RECID AND S.OWNER_DEPT_HIERARCHY_RECID IS NOT NULL AND E.OWNER_DEPT_HIERARCHY_RECID IS NOT NULL)
              OR (S.OWNER_CONTACTS_RECID IS NULL AND E.OWNER_CONTACTS_RECID IS NOT NULL)
              OR (S.OWNER_CONTACTS_RECID IS NOT NULL AND E.OWNER_CONTACTS_RECID IS NULL)
              OR (S.OWNER_DEPT_HIERARCHY_RECID IS NULL AND E.OWNER_DEPT_HIERARCHY_RECID IS NOT NULL)
              OR (S.OWNER_DEPT_HIERARCHY_RECID IS NOT NULL AND E.OWNER_DEPT_HIERARCHY_RECID IS NULL)
            )
            -- if the location is different
            OR (NOT(S.LOCATIONS_RECID <=> E.LOCATIONS_RECID) AND S.MULTIPLE_LOCATIONS = 0)
            -- if the GLAs are different
            OR  NOT(SEG.GLA_RECID  <=>  EEG.GLA_RECID )
         );
SQL
);

foreach ($records as $rec) {
    $eventParams = [
        "contact" => 101452,  // PCR Admin contact
        "users_recid" => 485, // pcradmin user
        "selectedEquipmentRecids" => [$rec['EQUIPMENT_RECID']],
        "gla_enabled" => false,
        "condition_enabled" => false,
        "cabling_eqp_type_enabled" => false,
        "status_enabled" => false,
        "location_enabled" => false,
        "assoc_service_enabled" => false,
        "equipment_type_enabled" => false,
        "dhcp_enabled" => false,
        "lan_name_enabled" => false,
        "host_name_enabled" => false,
        "private_enabled" => false,
        "billable_enabled" => false,
        "billable" => $rec["BILLABLE"],
        "war_date_enabled" => false,
        "war_date" => $rec["WARRANTY_END_DATE"],
        "dept_hier_owner_enabled" => false,
        "contact_owner_enabled" => false,
        // other junk from the EQP Bulk UPdate
        "gla_format" => $rec["GLA_FORMAT"],
        "selectedEquipmentTypeListRecid" => null,
        "isLocationRequired" => null,
        "comment" => null,
    ];

    if (empty($rec['SERVICE_OWNER_CONTACTS_RECID'])
        && $rec['SERVICE_OWNER_DEPT_HIERARCHY_RECID'] != $rec['EQUIPMENT_OWNER_DEPT_HIERARCHY_RECID']
    ) {
        $eventParams['dept_hier_owner_enabled'] = true;
        $eventParams['dept_hier_owner'] = $rec['SERVICE_OWNER_DEPT_HIERARCHY_RECID'];
    } elseif(empty($rec['SERVICE_OWNER_DEPT_HIERARCHY_RECID'])
        && $rec['SERVICE_OWNER_CONTACTS_RECID'] != $rec['EQUIPMENT_OWNER_CONTACTS_RECID']
    ) {
        $eventParams['contact_owner_enabled'] = true;
        $eventParams['contact_owner'] = $rec['SERVICE_OWNER_CONTACTS_RECID'];
    } elseif(empty($rec['SERVICE_OWNER_DEPT_HIERARCHY_RECID'])
        && $rec['SERVICE_OWNER_CONTACTS_RECID'] == $rec['EQUIPMENT_OWNER_CONTACTS_RECID']
    ) {
        // Equipment has both Contact and Dept Owners -
        // @see https://jira.pcr.com/browse/PCR360-7612
        // updating the contact Owner even though it is already set will clear the Dept Owner
        $eventParams['contact_owner_enabled'] = true;
        $eventParams['contact_owner'] = $rec['SERVICE_OWNER_CONTACTS_RECID'];
    }

    if($rec['MULTIPLE_LOCATIONS'] == "0"
        && $rec['SERVICE_LOCATION'] != $rec['EQUIPMENT_LOCATION']
    ){
        $eventParams['location_enabled'] = true;
        $eventParams['location'] = $rec['SERVICE_LOCATION'];
    }

    if($rec['SERVICE_GLA'] != $rec['EQUIPMENT_GLA']){
        $eventParams['gla_enabled'] = true;
        $eventParams['gla'] = $rec['SERVICE_GLA'];
    }

    // Only trigger the bulk update if any of the options are enabled.  Otherwise nothing is changing, there is no
    // need to trigger a bulk update if nothing is changing.
    if($eventParams['dept_hier_owner_enabled']
        || $eventParams['location_enabled']
        || $eventParams['gla_enabled']
        || $eventParams['contact_owner_enabled']
    ){
        PCR_Event::trigger("equipment-bulk-update", $eventParams);
    }
}

GLA Rollover

This Custom Event relies on UDFs for 'End_Date' and "Rollover_GLA" to roll over a GLA for billing on a given date.

GLA Rollover
/**
 * Event: Custom PHP Event
 * Frequency: Daily
 * Time: 12:00am
 * Listener Class: Core_Model_Event
 * Listener Method: eventCustom
 */

$glas = $this->query(<<<SQL
    SELECT G.STATUS AS STATUS, V.GLA_FULL_CODES AS OLD_GLA, 
           G.RECID AS OLD_GLA_RECID, V1.GLA_FULL_CODES AS NEW_GLA, 
           G1.RECID AS NEW_GLA_RECID, U2.DATETIME_VALUE AS END_DATE
    FROM V_GLA_COMP_COMB_ADMIN V
    INNER JOIN GLA G ON V.RECID = G.RECID
    INNER JOIN USER_DEFINED_FIELDS_VALS U1 
        ON G.RECID = U1.TABLE_RECID AND U1.TABLE_NAME = 'GLA' AND U1.UDF_RECID = (
            SELECT RECID FROM USER_DEFINED_FIELDS WHERE LABEL = 'Rollover_GLA'
        )
    LEFT JOIN GLA G1 ON G1.RECID = U1.INTEGER_VALUE
    LEFT JOIN V_GLA_COMP_COMB_ADMIN V1 ON G1.RECID = V1.RECID
    INNER JOIN USER_DEFINED_FIELDS_VALS U2 
        ON G.RECID = U2.TABLE_RECID AND U2.TABLE_NAME = 'GLA' AND U2.UDF_RECID = (
            SELECT RECID FROM USER_DEFINED_FIELDS WHERE LABEL = 'End_Date'
        )
    WHERE
    U2.DATETIME_VALUE IS NOT NULL
    AND U2.DATETIME_VALUE <= NOW()
    AND G.STATUS = 1
    ;
SQL
);

$results = ["deactivateGla" => [], "activateGla" => [], "rolledGla" => []];
PCR_Event::attachDb("replace-gla", [
    "Application_Model_Gla_Gla" => "eventReplaceGla"
]);
foreach ($glas as $gla) {

    // deactivate anything with past end_date
    $results["deactivateGla"][] = $gla["OLD_GLA_RECID"];

    // only Roll to the new GLA if there is a new GLA
    if(!empty($gla["NEW_GLA_RECID"])) {
        $results["activateGla"][] = $gla["NEW_GLA_RECID"];
        // only rollover if the END_DATE was within the last 30 days
        if (time() - strtotime($gla["END_DATE"]) < (30 * 24 * 60 * 60)) {
            $results["rolledGla"][] = $gla["OLD_GLA_RECID"];
            PCR_Event::trigger("replace-gla", [
                "contact" => 101452,  // PCR Admin contact
                "users_recid" => 485, // pcradmin user
                "glaRecid" => [$gla["OLD_GLA_RECID"]],
                "replaceGlaRecid" => $gla["NEW_GLA_RECID"],
                "prorate" => true,
                "setInactiveGla" => true,
                "comment" => "Nightly GLA Rollover from {$gla['OLD_GLA']} to {$gla['NEW_GLA']} recid"
                             . " {$gla['OLD_GLA_RECID']} to {$gla['NEW_GLA_RECID']}",
            ]);
        }
    }
}

// if anything Rolled/Deactivated then we need to fire that event
if(!empty($results["activateGla"]) || !empty($results["rolledGla"]) || !empty($results["deactivateGla"])){
    $results["ACTIVATE_COUNT"] = count($results["activateGla"]);
    $results["DEACTIVATE_COUNT"] = count($results["deactivateGla"]);
    $results["ROLLED_COUNT"] = count($results["rolledGla"]);

    // set the gla-status event and attach for a notification too
    PCR_Event::attachDb("gla-status", [
        "Core_Model_Notification" => "eventSend",
        "Application_Model_Gla_Gla" => "eventGlaStatus"
    ]);
    PCR_Event::trigger("gla-status", $results);
} else {
    $results["ACTIVATE_COUNT"] = $results["DEACTIVATE_COUNT"] = $results["ROLLED_COUNT"] = 0;

    // set the gla-status event and attach for a notification to indicate no glas rolled over
    PCR_Event::attachDb(
        "gla-status",
        [
            "Core_Model_Notification"   => "eventSend",
            "Application_Model_Gla_Gla" => "eventGlaStatus"
        ]
    );
    PCR_Event::trigger("gla-status", $results); 
}

Inactive Service Locations Clean Up

Inactive Locations Clean Up
<?php
/**
 * IN201620553 - Created to clean up Inactive service locations and owners before aging occurs.
 * Event: Custom PHP Event
 * Frequency: Hourly
 * Time:
 * Listener Class: Core_Model_Event
 * Listener Method: eventCustom
 * Description: This event queries for Inactive services with billed charges (or no charges at all)
 * and triggers the service bulk update to remove the owner and location.
 */


PCR_Event::attachDb('services-bulk-update', ['Application_Model_Service_Service' => 'eventBulkUpdate']);

$records = $this->query(<<<SQL
    SELECT DISTINCT S.RECID AS SERVICES_RECID,
    FROM SERVICES AS S
    JOIN LISTS AS L ON L.RECID = S.SERVICE_STATUS_LISTS_RECID
    LEFT JOIN SERVICES_CHARGES AS SC ON S.RECID = SC.SERVICES_RECID
    LEFT JOIN CHARGES AS C
        ON C.ORIG_TABLE_NAME = 'SERVICES_CHARGES' AND C.ORIG_TABLE_RECID = SC.RECID
    LEFT JOIN CHARGES_BILLED AS CB_MAX 
       ON CB_MAX.CHARGES_RECID = C.RECID
    LEFT JOIN CHARGES_BILLED AS CB_MIN
       ON CB_MIN.CHARGES_RECID = C.RECID AND CB_MAX.RECID < CB_MIN.RECID
    LEFT JOIN BILLS AS B ON B.RECID = CB_MAX.BILLS_RECID
    WHERE
        L.CODE = 'INACTIVE'
        AND S.LOCATIONS_RECID IS NOT NULL
        AND ( 
           CB_MAX.BILLING_COMPLETE = 1
           OR 
           SC.RECID IS NULL 
        )
        AND CB_MIN.RECID IS NULL
    GROUP BY S.RECID, SC.RECID
    LIMIT 400;
SQL
);

$eventParams = [
    'contact'     => 101452,  // PCR Admin contact
    'users_recid' => 485, // pcradmin user
];

//$eventParams['contact_owner_enabled'] = '1';
//$eventParams['contact_owner'] = null;
//$eventParams['dept_hier_owner_enabled'] = '1';
//$eventParams['dept_hier_owner'] = null;
$eventParams['location_enabled'] = '1';
$eventParams['location'] = null;
$eventParams['comment'] = 'Cleanup event to remove Locations from Inactive Services';

if(!empty($records)){
    foreach ($records as $rec) {
        $eventParams['selectedServiceRecids'][] = $rec['SERVICES_RECID'];
    }
    PCR_Event::trigger('services-bulk-update', $eventParams);
}

Move Available Services to Parent

Move Available Services to their Parent Category

Move Available Services to Parent
<?php

// >>>> COPY START !!! <<<< //

/**
 * This looks for any Phone Services which, after aging are changed from 'Inactive' to 'Available', and which
 * are in any of the child Categories of 'Telephones & Voicemail'. It then creates a Bulk Update Event to
 * move those Services to the parent.
 *
 * Note: The child Catalog Type must be 'Phone'.
 *
 * Event:           Custom PHP Event
 * Frequency:       Daily
 * Time:
 * Listener Class:  Core_Model_Event
 * Listener Method: eventCustom
 */

PCR_Event::attachDb('services-bulk-update', ['Application_Model_Service_Service' => 'eventBulkUpdate']);

$parentCatalogRecidSql = <<<SQL
SELECT RECID
FROM   SERV_CATALOG
WHERE  SERVICE_NAME = 'Telephones & Voicemail'
SQL;

$listsRecidSql = <<<SQL
SELECT    LISTS.RECID
FROM      LISTS
LEFT JOIN LIST_TYPES
    ON LISTS.LIST_TYPES_RECID = LIST_TYPES.RECID
WHERE     LIST_TYPES.TYPE = 'SERVICE_TYPE'
AND       LISTS.CODE = 'PHONE';
SQL;

if (($parentCatalogRecid = $this->query($parentCatalogRecidSql)) &&
    ($listsRecid = $this->query($listsRecidSql))
) {
    $parentCatalogRecid = (int) $parentCatalogRecid[0]['RECID'];
    $listsRecid = (int) $listsRecid[0]['RECID'];

    $servicesToMoveSql = <<<SQL
SELECT SERVICES.RECID
FROM   SERVICES
LEFT JOIN LISTS
    ON SERVICES.SERVICE_STATUS_LISTS_RECID = LISTS.RECID
LEFT JOIN LIST_TYPES
    ON LISTS.LIST_TYPES_RECID = LIST_TYPES.RECID
WHERE  LISTS.CODE = 'AVAILABLE'
AND    LIST_TYPES.TYPE = 'SERVICE_STATUS'
AND    SERVICES.SERV_CATALOG_RECID IN (
    SELECT SERV_CATALOG_FULLPATH.SERV_CATALOG_RECID
    FROM   SERV_CATALOG_FULLPATH
    LEFT JOIN SERV_CATALOG
        ON SERV_CATALOG_FULLPATH.SERV_CATALOG_RECID = SERV_CATALOG.RECID
    LEFT JOIN LISTS
        ON SERV_CATALOG.SERVICE_TYPE_LISTS_RECID = LISTS.RECID
    LEFT JOIN LIST_TYPES
        ON LISTS.LIST_TYPES_RECID = LIST_TYPES.RECID
    WHERE  PATH_SERV_CATALOG_RECID = {$parentCatalogRecid}
    AND    SERV_CATALOG_RECID <> {$parentCatalogRecid}
    AND    LISTS.CODE = 'PHONE'
    AND    LIST_TYPES.TYPE = 'SERVICE_TYPE'
)
SQL;

    $userSql = <<<SQL
SELECT RECID, CONTACTS_RECID
FROM USERS
WHERE USERID = 'pcr'
SQL;

    if (($servicesToMove = $this->query($servicesToMoveSql)) &&
        ($user = $this->query($userSql))
    ) {
        $eventParams = [
            'service_type_enabled'    => 1,
            'location_enabled'        => 0,
            'status_enabled'          => 0,
            'service_host_enabled'    => 0,
            'sla_enabled'             => 0,
            'contact_owner_enabled'   => 0,
            'dept_hier_owner_enabled' => 0,
            'gla_enabled'             => 0,
            'pools_enabled'           => 0,
            'billable_enabled'        => 0,
            'directory_enabled'       => 0,
            'essential_enabled'       => 0,
            'report_911_enabled'      => 0,
            'isLocationRequired'      => 0,
            'isServiceHostRequired'   => 0,

            'contact'     => (int) $user[0]['CONTACTS_RECID'],
            'users_recid' => (int) $user[0]['RECID'],

            'service_type'                 => $parentCatalogRecid,
            'selectedServiceTypeListRecid' => $listsRecid,
            'comment'                      => 'Custom Event: Move all "Available" Services to parent Catalog.'
        ];

        foreach ($servicesToMove as $service) {
            $eventParams['selectedServiceRecids'][] = (int) $service['RECID'];
        }

        PCR_Event::trigger('services-bulk-update', $eventParams);
    }
}

// >>>> COPY STOP !!! <<<< //

?>

Nightly Service Location Update

Nightly Service Location Update
/**
 * Event: Custom PHP Event
 * Frequency: Daily
 * Time: 12:00am
 * Listener Class: Core_Model_Event
 * Listener Method: eventCustom
 */

$services = $this->query(
   "SELECT S.RECID AS SERVICE_RECID, L.RECID AS LOCATION_RECID 
   FROM PCR360_PROD.SERVICES S
   JOIN PCR360_PROD.PATHS P ON P.SERVICES_RECID = S.RECID
   JOIN PCR360_PROD.PATH_LEGS PL ON PL.PATHS_RECID = P.RECID
   JOIN PCR360_PROD.EQUIPMENT E ON PL.FROM_EQUIPMENT_RECID = E.RECID
   JOIN PCR360_PROD.LOCATIONS L ON E.LOCATIONS_RECID = L.RECID
   JOIN PCR360_PROD.EQP_CATALOG EC ON E.EQP_CATALOG_RECID = EC.RECID 
   WHERE S.MULTIPLE_LOCATIONS = 0
   AND EC.PART_NUMBER = 'Jacks'
   AND S.LOCATIONS_RECID != E.LOCATIONS_RECID"
);

PCR_Event::attachDb("services-bulk-update", [
    "Application_Model_Service_Service" => "eventBulkUpdate"
]);
foreach ($services as $service) {
    PCR_Event::trigger("services-bulk-update", [
        "selectedServiceRecids" => [$service["SERVICE_RECID"]],
        "location_enabled" => "1",
        "location" => $service["LOCATION_RECID"],
	"service_type_enabled" => "0",
	"status_enabled" => "0",
	"service_host_enabled" => "0",
	"sla_enabled" => "0",
	"contact_owner_enabled" => "0",
	"dept_hier_owner_enabled" => "0",
	"gla_enabled" => "0",
	"pools_enabled" => "0",
	"billable_enabled" => "0",
	"directory_enabled" => "0",
	"essential_enabled" => "0",
	"report_911_enabled" => "0",    
	"isLocationRequired" => true,
	"isServiceHostRequired" => false,
	"selectedServiceTypeListRecid" => null,
    "selectedServiceFilters" => [],
	"billable" => "0",
	"essential" => "0",
	"directory" => "0",
	"status" => "1",
	"report_911" => "0",
	"users_recid" => "2",
	"contact" => "2",
	"comment" => "nightly jack/service location update",
    ]);
}

Scheduled Maintenance

Scheduled Maintenance required for Equipment is a key component in using PCR-360 for Facilities Management.  Users can set up a Custom Event that will assist in scheduling regular maintenance for Equipment by automatically creating Incidents for that Equipment to be maintained. In order to create this automated behavior first there need to be three User Defined Fields (UDFs) set to track needed maintenance.


To set up the UDFs first navigate to Admin > User Defined Fields > User Defined Fields. Create the UDFs needed by following these steps:

  1. Create a Maintenance Period Type UDF
    1. Create a new UDF by clicking the 'Add' button.
    2. In the 'UDF Identifier' field set the value to "MAINTENANCE_PERIOD_TYPE".
    3. Add a 'Label' of "Maintenance Period".
    4. Set the 'Field Type' to "Dropdown".
    5. The header should look like this example:
    6. In the 'UDF Associations' click the 'Add' button to open the 'Add New Field Association' form.
      1.  Set the 'Association Table' dropdown to "Eqp Catalog"
      2. Click the 'Save New' button.
      3. Close the 'Manage Field Association' form.
    7. Click the 'Save New' button to save the UDF.
    8. When the form refreshes select the 'Dropdown Options' tab.
      1. Click the 'Add' button and add three new options:
        1. Add a 'Value' and 'Code' of "Years".
        2. Add a 'Value' and 'Code' of "Months".
        3. Add a 'Value' and 'Code' of "Days".
        4. When done the options should look like this:
    9. Close the 'Manage Field Association' form.


  2. Create a Maintenance Period Quantity UDF
    1. Create a new UDF by clicking the 'Add' button.
    2. In the 'UDF Identifier' field set the value to "MAINTENANCE_PERIOD_QTY".
    3. Add a 'Label' of "Maintenance Period Quantity".
    4. Set the 'Field Type' to "Number".
    5. The header should look like this example:
    6. In the 'UDF Associations' click the 'Add' button to open the 'Add New Field Association' form.
      1.  Set the 'Association Table' dropdown to "Eqp Catalog"
      2. Click the 'Save New' button.
      3. Close the 'Manage Field Association' form.
    7. Click the 'Save New' button to save the UDF.


  3. Create a Maintenance Date UDF
    1. Create a new UDF by clicking the 'Add' button.
    2. In the 'UDF Identifier' field set the value to "MAINTENANCE_DATE.
    3. Add a 'Label' of "Maintenance Date".
    4. Set the 'Field Type' to "Date".
    5. The header should look like this example:
    6. In the 'UDF Associations' click the 'Add' button to open the 'Add New Field Association' form.
      1.  Set the 'Association Table' dropdown to "Equipment"
      2. Select an 'Equipment Catalog' to limit the UDF to the type that should set for the regular maintenance.
      3. Click the 'Save New' button.
      4. Close the 'Manage Field Association' form.
    7. Click the 'Save New' button to save the UDF.


Once all of three of the UDFs have been created the next step is to add a Custom Event. To add the Custom Event follow these steps:

  1. Navigate to Admin > Custom Logic > Events.
  2. Click the 'Add' button to start a new Event.
  3. Set the 'Identifier' field to "Scheduled Maintenance".
  4. In the 'Logic' tab enter the logic  from the "Schedule Maintenance" expand below:
  5.  Basic Scheduled Maintenance Example
    <?php
    
    $eqp = $this->query(<<<SQL
        SELECT E.*,
           MAINT_DATE.VALUE as MAINTENANCE_DATE,
           MAINT_PERIOD_TYPE.VALUE as MAINTENANCE_PERIOD_TYPE,
           MAINT_PERIOD_QTY.VALUE as MAINTENANCE_PERIOD_QTY
           
        FROM EQUIPMENT E
        INNER JOIN EQP_CATALOG EC 
            ON EC.RECID = E.EQP_CATALOG_RECID
            
        INNER JOIN V_UDF MAINT_DATE 
            ON E.RECID = MAINT_DATE.VALUE_TABLE_RECID AND MAINT_DATE.VALUE_TABLE_NAME = 'EQUIPMENT' AND MAINT_DATE.IDENTIFIER = 'MAINTENANCE_DATE'
            
        INNER JOIN V_UDF MAINT_PERIOD_TYPE 
            ON EC.RECID = MAINT_PERIOD_TYPE.VALUE_TABLE_RECID AND MAINT_PERIOD_TYPE.VALUE_TABLE_NAME = 'EQP_CATALOG' AND MAINT_PERIOD_TYPE.IDENTIFIER = 'MAINTENANCE_PERIOD_TYPE'
    
        INNER JOIN V_UDF MAINT_PERIOD_QTY 
            ON EC.RECID = MAINT_PERIOD_QTY.VALUE_TABLE_RECID AND MAINT_PERIOD_QTY.VALUE_TABLE_NAME = 'EQP_CATALOG' AND MAINT_PERIOD_QTY.IDENTIFIER = 'MAINTENANCE_PERIOD_QTY'
    
        WHERE MAINT_DATE.VALUE = CURRENT_DATE 
        ;
    SQL
    );
    
    
    foreach($eqp as $equipment){
    
        $incident = [
            "type" => "IN",
            "csr" => "1",
            "owner" => $equipment["OWNER_CONTACTS_RECID"] ? $equipment["OWNER_CONTACTS_RECID"] : $equipment["OWNER_DEPT_HIERARCHY_RECID"],
            "owner_type" => $equipment["OWNER_CONTACTS_RECID"] ? "contact" : "department",
            "description" => "Scheduled Maintenance",
            "prob_code" => 3,
            "equipment" => $equipment["RECID"]
        ];
    
        $result = $this->call("saveServiceDesk", $incident);
    
        $maintenanceDate = new DateTime($equipment["MAINTENANCE_DATE"]);
        $intervalType = substr($equipment["MAINTENANCE_PERIOD_TYPE"], 0, 1);
        $interval = new DateInterval("P{$equipment["MAINTENANCE_PERIOD_QTY"]}{$intervalType}");
        $maintenanceDate->add($interval);
    
        $result = $this->call("saveEquipment", [
            "type" => "UDFS",
            "equipment_recid" => $equipment["RECID"],
            "udf_MAINTENANCE_DATE" => $maintenanceDate->format("Y-m-d")
        ]);
    
    }
  6.  Multiple Time frame Example

    The following example uses 10 separate UDFs to control the Custom Event and allows setting multiple different maintenance periods for the same piece of Equipment.

    <?php
    /*
     * Custom Events
     * Basic Instructions: https://confluence.pcr.com/x/WA2BAQ
     * Since adapted for multiple timeframes on the same catalog
     */
    
    $eqp = $this->query(<<<SQL
        SELECT E.*,
           MAINTENANCE_DATE_ANNUAL.VALUE as MAINTENANCE_DATE_ANNUAL,
           MAINTENANCE_DATE_SEMIANNUAL.VALUE as MAINTENANCE_DATE_SEMIANNUAL,
           MAINTENANCE_DATE_QUARTERLY.VALUE as MAINTENANCE_DATE_QUARTERLY,
           MAINTENANCE_DATE_MONTHLY.VALUE as MAINTENANCE_DATE_MONTHLY,
           MAINTENANCE_DATE_WEEKLY.VALUE as MAINTENANCE_DATE_WEEKLY,
           
           MAINTENANCE_DATE_ANNUAL.DESCRIPTION as MAINTENANCE_DATE_ANNUAL_DESC,
           MAINTENANCE_DATE_SEMIANNUAL.DESCRIPTION as MAINTENANCE_DATE_SEMIANNUAL_DESC,
           MAINTENANCE_DATE_QUARTERLY.DESCRIPTION as MAINTENANCE_DATE_QUARTERLY_DESC,
           MAINTENANCE_DATE_MONTHLY.DESCRIPTION as MAINTENANCE_DATE_MONTHLY_DESC,
           MAINTENANCE_DATE_WEEKLY.DESCRIPTION as MAINTENANCE_DATE_WEEKLY_DESC,
           
           COALESCE(MAINTENANCE_PERIOD_QTY_ANNUAL.VALUE,1) as MAINTENANCE_PERIOD_QTY_ANNUAL,
           COALESCE(MAINTENANCE_PERIOD_QTY_SEMIANNUAL.VALUE,1) as MAINTENANCE_PERIOD_QTY_SEMIANNUAL,
           COALESCE(MAINTENANCE_PERIOD_QTY_QUARTERLY.VALUE,1) as MAINTENANCE_PERIOD_QTY_QUARTERLY,
           COALESCE(MAINTENANCE_PERIOD_QTY_MONTHLY.VALUE,1) as MAINTENANCE_PERIOD_QTY_MONTHLY,
           COALESCE(MAINTENANCE_PERIOD_QTY_WEEKLY.VALUE,1) as MAINTENANCE_PERIOD_QTY_WEEKLY
           
        FROM EQUIPMENT E
        INNER JOIN EQP_CATALOG EC 
            ON EC.RECID = E.EQP_CATALOG_RECID
            
        LEFT JOIN V_UDF MAINTENANCE_DATE_ANNUAL 
            ON E.RECID = MAINTENANCE_DATE_ANNUAL.VALUE_TABLE_RECID 
            AND MAINTENANCE_DATE_ANNUAL.VALUE_TABLE_NAME = 'EQUIPMENT' AND MAINTENANCE_DATE_ANNUAL.IDENTIFIER = 'MAINTENANCE_DATE_ANNUAL'
        LEFT JOIN V_UDF MAINTENANCE_DATE_SEMIANNUAL 
            ON E.RECID = MAINTENANCE_DATE_SEMIANNUAL.VALUE_TABLE_RECID 
            AND MAINTENANCE_DATE_SEMIANNUAL.VALUE_TABLE_NAME = 'EQUIPMENT' AND MAINTENANCE_DATE_SEMIANNUAL.IDENTIFIER = 'MAINTENANCE_DATE_SEMIANNUAL'
        LEFT JOIN V_UDF MAINTENANCE_DATE_QUARTERLY 
            ON E.RECID = MAINTENANCE_DATE_QUARTERLY.VALUE_TABLE_RECID 
            AND MAINTENANCE_DATE_QUARTERLY.VALUE_TABLE_NAME = 'EQUIPMENT' AND MAINTENANCE_DATE_QUARTERLY.IDENTIFIER = 'MAINTENANCE_DATE_QUARTERLY'
        LEFT JOIN V_UDF MAINTENANCE_DATE_MONTHLY 
            ON E.RECID = MAINTENANCE_DATE_MONTHLY.VALUE_TABLE_RECID 
            AND MAINTENANCE_DATE_MONTHLY.VALUE_TABLE_NAME = 'EQUIPMENT' AND MAINTENANCE_DATE_MONTHLY.IDENTIFIER = 'MAINTENANCE_DATE_MONTHLY'
        LEFT JOIN V_UDF MAINTENANCE_DATE_WEEKLY 
            ON E.RECID = MAINTENANCE_DATE_WEEKLY.VALUE_TABLE_RECID 
            AND MAINTENANCE_DATE_WEEKLY.VALUE_TABLE_NAME = 'EQUIPMENT' AND MAINTENANCE_DATE_WEEKLY.IDENTIFIER = 'MAINTENANCE_DATE_WEEKLY'
    
        LEFT JOIN V_UDF MAINTENANCE_PERIOD_QTY_ANNUAL 
            ON EC.RECID = MAINTENANCE_PERIOD_QTY_ANNUAL.VALUE_TABLE_RECID 
            AND MAINTENANCE_PERIOD_QTY_ANNUAL.VALUE_TABLE_NAME = 'EQP_CATALOG' AND MAINTENANCE_PERIOD_QTY_ANNUAL.IDENTIFIER = 'MAINTENANCE_PERIOD_QTY_ANNUAL'
        LEFT JOIN V_UDF MAINTENANCE_PERIOD_QTY_SEMIANNUAL 
            ON EC.RECID = MAINTENANCE_PERIOD_QTY_SEMIANNUAL.VALUE_TABLE_RECID 
            AND MAINTENANCE_PERIOD_QTY_SEMIANNUAL.VALUE_TABLE_NAME = 'EQP_CATALOG' AND MAINTENANCE_PERIOD_QTY_SEMIANNUAL.IDENTIFIER = 'MAINTENANCE_PERIOD_QTY_SEMIANNUAL'
        LEFT JOIN V_UDF MAINTENANCE_PERIOD_QTY_QUARTERLY 
            ON EC.RECID = MAINTENANCE_PERIOD_QTY_QUARTERLY.VALUE_TABLE_RECID 
            AND MAINTENANCE_PERIOD_QTY_QUARTERLY.VALUE_TABLE_NAME = 'EQP_CATALOG' AND MAINTENANCE_PERIOD_QTY_QUARTERLY.IDENTIFIER = 'MAINTENANCE_PERIOD_QTY_QUARTERLY'
        LEFT JOIN V_UDF MAINTENANCE_PERIOD_QTY_MONTHLY 
            ON EC.RECID = MAINTENANCE_PERIOD_QTY_MONTHLY.VALUE_TABLE_RECID 
            AND MAINTENANCE_PERIOD_QTY_MONTHLY.VALUE_TABLE_NAME = 'EQP_CATALOG' AND MAINTENANCE_PERIOD_QTY_MONTHLY.IDENTIFIER = 'MAINTENANCE_PERIOD_QTY_MONTHLY'
        LEFT JOIN V_UDF MAINTENANCE_PERIOD_QTY_WEEKLY 
            ON EC.RECID = MAINTENANCE_PERIOD_QTY_WEEKLY.VALUE_TABLE_RECID 
            AND MAINTENANCE_PERIOD_QTY_WEEKLY.VALUE_TABLE_NAME = 'EQP_CATALOG' AND MAINTENANCE_PERIOD_QTY_WEEKLY.IDENTIFIER = 'MAINTENANCE_PERIOD_QTY_WEEKLY'
    
        WHERE 
    
        (MAINTENANCE_DATE_ANNUAL.VALUE IS NOT NULL
        OR MAINTENANCE_DATE_SEMIANNUAL.VALUE IS NOT NULL
        OR MAINTENANCE_DATE_QUARTERLY.VALUE IS NOT NULL
        OR MAINTENANCE_DATE_MONTHLY.VALUE IS NOT NULL
        OR MAINTENANCE_DATE_WEEKLY.VALUE IS NOT NULL)
        AND
        (MAINTENANCE_DATE_ANNUAL.VALUE = CURRENT_DATE
        OR MAINTENANCE_DATE_SEMIANNUAL.VALUE = CURRENT_DATE
        OR MAINTENANCE_DATE_QUARTERLY.VALUE = CURRENT_DATE
        OR MAINTENANCE_DATE_MONTHLY.VALUE = CURRENT_DATE
        OR MAINTENANCE_DATE_WEEKLY.VALUE = CURRENT_DATE)
        ;
    SQL
    );
    
    $dateTypes = [
        'ANNUAL'     => 'P1Y',
        'SEMIANNUAL' => 'P6M',
        'QUARTERLY'  => 'P3M',
        'MONTHLY'    => 'P1M',
        'WEEKLY'     => 'P1W'
    ];
    $now = new DateTime();
    $now->setTime(0,0);
    
    foreach($eqp as $equipment){
    
        $incident = [
            'type' => 'IN',
            'csr' => '1',
            'owner' => $equipment['OWNER_CONTACTS_RECID'] ? $equipment['OWNER_CONTACTS_RECID'] : $equipment['OWNER_DEPT_HIERARCHY_RECID'],
            'owner_type' => $equipment['OWNER_CONTACTS_RECID'] ? 'contact' : 'department',
            'description' => 'Scheduled Maintenance',
            'prob_code' => 3,
            'equipment' => $equipment['RECID']
        ];
    
        foreach($dateTypes as $dateType => $dateInterval){
            $maintenanceDate = new DateTime($equipment["MAINTENANCE_DATE_{$dateType}"]);
    
            if($maintenanceDate == $now) {
                $incident['description'] = $equipment["MAINTENANCE_DATE_{$dateType}_DESC"];
    
                $result = $this->call('saveServiceDesk', $incident);
                $interval = new DateInterval($dateInterval);
    
                for($qty = 1; $qty <= $equipment["MAINTENANCE_PERIOD_QTY_{$dateType}"]; $qty++){
                    $maintenanceDate->add($interval);
                }
    
                $result = $this->call('saveEquipment', [
                    'type' => 'UDFS',
                    'equipment_recid' => $equipment['RECID'],
                    "udf_MAINTENANCE_DATE_{$dateType}" => $maintenanceDate->format('Y-m-d')
                ]);
            }
        }
    }
  7. Click the 'Save New' button.


    Now that initial data set up is finished, simply find the Equipment Catalog from step 1 and enter information into the two UDFs setup in steps 1 and 2, Maintenance Period and Maintenance Period Quantity respectively. The Quantity should represent how many periods should pass before triggering the event. For example, to set a maintenance period every 3 months, set the Quantity to "3". Next, open the Equipment record and set the Maintenance Period Date UDF to the next Maintenance Date.

    The Custom Event will now automatically run in the background. When the Custom Event runs, a new Incident for each Equipment with a Maintenance Date that matches the current date will be created and then the Maintenance Date will be set to the next interval period. These Incidents can then be worked normally to accomplish the regularly scheduled maintenance tasks.

Help Desk Portal - Email: help@pcr.com - Phone: 616.259.9242