POST WorkOrder

The POST Work Order method within the Planning and Scheduling – Work Order API enables integration users to create work orders within the referenced REVEAL account. There are several business rules and details regarding the field specifics within a work order request, so please be sure to review the documentation associated with the Planning and Scheduling – Work Order API before beginning.

<?php
   $token = 'TOKEN_STRING';
   $FIM_app_id = 'APP_ID';
   $FIM_endpoint = 'https://fim.api.us.fleetmatics.com/pas/v1/workorders';

   //Set local variables
   $wo_actual_date_utc = '2017-04-14Z19:00:00';
   $wo_actual_duration_secs = 120;
   $wo_address_line1 = '4444 East Ridgewood Drive';
   $wo_address_line2 = '';
   $wo_locality = 'Seven Hills';
   $wo_administrative_area = 'Ohio';
   $wo_postal_code = '44131';
   $wo_country = 'USA';
   $wo_client_customer_id = "10150";
   $wo_description = 'This is a Test WO';
   $wo_driver_number = '101';
   $wo_latitude = 0.0;
   $wo_longitude = 0.0;
   $wo_on_site_duration_secs = 0;
   $wo_radius_in_km = '.322';
   $wo_scheduled_date_utc = '2017-04-14Z18:00:00';
   $wo_scheduled_duration_secs = 120;
   $wo_status_change_date_utc = NULL;
   $wo_number = 'WO-PHP-TEST7';
   $wo_status_code = 'Open';
   $wo_status_type = 'SO';
   
   //Using variables, create an array to store data for POST. Note: '=>' is necessary
   $post_data = array( 'ActualDateUtc' => $wo_actual_date_utc,
                       'ActualDurationSeconds' => $wo_actual_duration_secs,
                       'Address' => array(
                           'AddressLine1' => $wo_address_line1,
                           'AddressLine2' => $wo_address_line2,
                           'Locality' => $wo_locality,
                           'AdministrativeArea' => $wo_administrative_area,
                           'PostalCode' => $wo_postal_code,
                           'Country' => $wo_country),
                       'ClientCustomerId' => $wo_client_customer_id,
                       'Description' => $wo_description,
                       'DriverNumber' => $wo_driver_number,
                       'Latitude' => $wo_latitude,
                       'Longitude' => $wo_longitude,
                       'OnSiteDurationSeconds' => $wo_on_site_duration_secs,
                       'RadiusInKm' => $wo_radius_in_km,
                       'ScheduledDateUtc' => $wo_scheduled_date_utc,
                       'ScheduledDurationSeconds' => $wo_scheduled_duration_secs,
                       'StatusChangeDateUtc' => $wo_status_change_date_utc,
                       'WorkOrderNumber' => $wo_number,
                       'WorkOrderStatusCode' => $wo_status_code,
                       'WorkOrderTypeCode' => $wo_status_type );

   //Call method
   post_workorder($post_data, $FIM_endpoint, $FIM_app_id, $token);
   
   function post_workorder($data, $url, $app_id, $token)
   {
       //Get necessary headers for REST call   
       $headers = get_call_headers($app_id, $token);
   
       //convert data to JSON format   
       $json_data = json_encode($data);
       
       $session = curl_init($url);                                 //Initialize transfer with URL
       curl_setopt($session, CURLOPT_POST, true);                  //Use 'CURLOPT_POST' set to true for REST POST
       curl_setopt($session, CURLOPT_RETURNTRANSFER, true);        //Return transfer as a string of the return value of curl_exec() 
       curl_setopt($session, CURLOPT_HTTPHEADER, $headers);        //Pass in headers 
       curl_setopt($session, CURLOPT_POSTFIELDS, $json_data);      //Pass in PUT data 
   
       //Execute transfer of $session      
       $response = curl_exec($session); 
       
       //Get http code outcome of the #session transfer        
       $http_code = curl_getinfo($session, CURLINFO_HTTP_CODE);    
    
       //Measure false response/error
       if($response === false)
       {
           echo 'Error: '. curl_error($session);
       }
   
       //ALWAYS close transfer connection 
       curl_close($session);

       //WorkOrder not created, evaluate http code 
       if($http_code !== 201)
       {
           echo 'Error: Http Status Code returned '.$http_code;
           echo '  '.$response;
       }
       else    //http code 201 returned, workorder created!
       {    
           echo 'Workorder created!';
           echo $response;             //or return
       }
   }

   function get_call_headers($app_id, $token)
   {
       //Inserts app_id and token into respective '%s' spaces in the auth header   
       $auth_header = sprintf('Authorization: Atmosphere atmosphere_app_id=%s, Bearer %s', $app_id, $token);

       //Create necessary headers for REST call    
       $headers = array();
       $headers[] = $auth_header;  
       //IMPORTANT! - You must use 'Content-Type' as opposed to Accept as you are describing how the info is being sent    
       $headers[] = 'Content-Type: application/json';
       
       return $headers;
   }
?>

DISCLAIMER

All sample code is provided by Fleetmatics, A Verizon Company, for illustrative purposes only. These examples have not been thoroughly tested under all conditions. Fleetmatics, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. All programs contained herein are provided to you “AS IS” without any warranties of any kind.

The POST Work Order method within the Planning and Scheduling – Work Order API enables integration users to create work orders within the referenced REVEAL account. There are several business rules and details regarding the field specifics within a work order request, so please be sure to review the documentation associated with the Planning and Scheduling – Work Order API before beginning.

Main Method
import  java.util.Calendar;
import  java.text.SimpleDateFormat;
import  java.util.*;

public class Program{
  public static void main(String[] args){
    
    // Token call goes here, see TokenGenerator example 
    
    // App Id from Fleetmatics Integration Manager (FIM) 
    String appId = "companyname-p-us-4654sdf4fa351af65dsf1d";
        
    // Post Workorder URI  
    String postWorkOrderUri = "https://fim.api.us.fleetmatics.com/pas/v1/workorders";    
    
    // Local variables that correspond to post body fields (Workorder and Address)
    String actualDateUtc = CreateDateTime(2017, 1, 25, 13, 00, 02);
    Integer actualDurationSecs = 120;
    String addressLine1 = "935 John Glenn Dr";
    String addressLine2 = null;
    String locality = "Independence";
    String administrativeArea = "Oh";
    String postalCode = "44131";
    String country = "US";
    String clientCustomerId = "10150";
    String description = "This is a Test WO";
    String driverNumber = "101";
    Double latitude = 0.0;
    Double longitude = 0.0;
    Integer onSiteDurationSecs = 0;
    Double radiusInKM = .322;
    String scheduledDateUtc = CreateDateTime(2017, 04, 25, 19, 00, 00);
    Integer scheduledDurationSecs = null;
    String statusChangeDateUtc = null;
    String workOrderNumber = "WOTEST";
    String statusCode = "Open";
    String typeCode = "SO";
    
    // Create new POST_WorkOrder object
    POST_WorkOrder rest_post = new POST_WorkOrder();
    
    // Pass in local variables to create a workorder object
    rest_post.CreateWorkOrder(actualDateUtc, actualDurationSecs, addressLine1, addressLine2, locality, administrativeArea, postalCode,
                              country, clientCustomerId, description, driverNumber, latitude, longitude, onSiteDurationSecs, radiusInKM,
                              scheduledDateUtc, scheduledDurationSecs, statusChangeDateUtc, workOrderNumber, statusCode, typeCode);
    
    // Call method to execute the API call
    rest_post.PostWorkOrder(/* token auth string passed here */, postWorkOrderUri, appId);
  }  
  
  // Function to construct a DateTime string from supplied parameters
  private static String CreateDateTime(int year, int month, int day, int hr, int min, int sec){    
    // Set the formatter for the DateTime string
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    // Construct date: Jan = 0, Dec = 11 so we shift left 1 from input
    Calendar calendar = new GregorianCalendar(year, month-1, day, hr, min, sec);

    // Returns a formatted DateTime object from the calendar's constructed DateTime
    return sdf.format(calendar.getTime());
  }
}
POST_WorkOrder Class
import java.io.BufferedReader;;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import javax.net.ssl.HttpsURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.lang.reflect.*;

public class POST_WorkOrder
{
  private WorkOrder _workOrder;
  
  private Address _address;
  
  public void PostWorkOrder(String authString, String postWorkOrderUri, String appId)
  {   
    try
    {
      // Construct authentication header for FIM   
      String authHeader = String.format("Atmosphere atmosphere_app_id=%s, Bearer %s", appId, authString);             
      
      // Serialize workorder object into JSON for POST request body     
      String json = WorkOrderDummySerializer(_workOrder);           
      
      URL url = new URL(postWorkOrderUri);                                     // Create URL object from uri parameter   
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();     // Begin new Https connection       
      conn.setRequestMethod("POST");                                           // Set REST method to POST  
      conn.setRequestProperty("Authorization", authHeader);                    // Set Authorization Header   
      conn.setRequestProperty("Content-Type", "application/json");             // Set Content-Type to json 
      conn.setDoOutput(true);                                                  // Allow output to come back in response 
      
      OutputStream os = conn.getOutputStream();   // Create new output stream for body from connection   
      os.write(json.getBytes());                  // Transmit the json workorder object       
      os.close();                                 // Flush and close stream  
      
      // Read response, 201 "created" evaluation for "success", if not throw exception 
      if (conn.getResponseCode() != HttpsURLConnection.HTTP_CREATED) {
        throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
      }
      
      // Read the response body into a readable stream 
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
               
      String workOrderCreated = br.readLine();   // Begin reading, store into variable  
      _workOrder = null;                         // Clear object    
      _address = null;                           // Clear object    
      
      System.out.println(workOrderCreated);      // Logging 
      
      conn.disconnect();                         // End connection to free resources 
      
    } catch (MalformedURLException e) {          // Required Exception 
      e.printStackTrace();
    } catch (IOException e) {                    // Required Exception 
      e.printStackTrace();
    }
  } 
  
  // Public method used to create the workorder object which contains a nested Address object. 
  // After serialization, this will be used as the body for the POST command
  public void CreateWorkOrder(String actualDateUtc, Integer actualDurationSecs, String addressLine1, String addressLine2, String locality, String administrativeArea,
                              String postalCode, String country, String clientCustomerId, String description, String driverNumber, Double latitude, Double longitude,
                              Integer onSiteDurationSecs, Double radiusInKM, String scheduledDateUtc, Integer scheduledDurationSecs, String statusChangeDateUtc, String workOrderNumber,
                              String statusCode, String typeCode)
  {
    // Construct Address object
    _address = new Address();
    _address.AddressLine1 = addressLine1;
    _address.AddressLine2 = addressLine2;
    _address.Locality = locality;
    _address.AdministrativeArea = administrativeArea;
    _address.PostalCode = postalCode;
    _address.Country = country;
    
    // Construct WorkOrder object
    _workOrder = new WorkOrder();
    _workOrder.ActualDateUtc = actualDateUtc;
    _workOrder.ActualDurationSeconds = actualDurationSecs;
    _workOrder.ClientCustomerId = clientCustomerId;
    _workOrder.Description = description;
    _workOrder.DriverNumber = driverNumber;
    _workOrder.Latitude = latitude;
    _workOrder.Longitude = longitude;
    _workOrder.OnSiteDurationSecs = onSiteDurationSecs;
    _workOrder.RadiusInKM = radiusInKM;
    _workOrder.ScheduledDateUtc = scheduledDateUtc;
    _workOrder.ScheduledDurationSecs = scheduledDurationSecs;
    _workOrder.StatusChangeDateUtc = statusChangeDateUtc;
    _workOrder.WorkOrderNumber = workOrderNumber;
    _workOrder.WorkOrderStatusCode = statusCode;
    _workOrder.WorkOrderTypeCode = typeCode;
    _workOrder.Address = _address;       //Pass in the Address object
  }
  
  // Custom "object to JSON" serializer for the workorder object
  private String WorkOrderDummySerializer(Object object)
  {    
    try{
      StringBuilder sb = new StringBuilder();
      sb.append("{");                                             // Open parentheses
      
      for (Field field : object.getClass().getDeclaredFields())   // Loop through object
      {
        field.setAccessible(true);                                // Override
        if (field != null && !field.getName().contains("this$"))  // Skip "this$" - outer class
        {
          if(field.getType() == Address.class){
            sb.append("\"Address\" : ");                          // Process nested object
            sb.append(WorkOrderDummySerializer(_address) + ", "); // Recursive call to process _address object
          }
          else{
            sb.append("\"" + field.getName() + "\" : ");
            sb.append(field.get(object) != null ? ("\"" + field.get(object) + "\"") : "null");   
            sb.append(", ");
          }
        }
      }
      
      sb.setLength(sb.length() - 2);                              // Remove last ", "
      sb.append("}");                                             // Close parentheses
      
      return sb.toString
      
    } catch (IllegalAccessException e) {                          // Required exception
      throw new RuntimeException("Error accessing object value!");
    }
  }
  
  public class WorkOrder
  {
    public String ActualDateUtc;
    public Integer ActualDurationSeconds;
    public Address Address;
    public String ClientCustomerId;
    public String Description;
    public String DriverNumber;
    public Double Latitude;
    public Double Longitude;
    public Integer OnSiteDurationSecs;
    public Double RadiusInKM;
    public String ScheduledDateUtc;
    public Integer ScheduledDurationSecs;
    public String StatusChangeDateUtc;
    public String WorkOrderNumber;
    public String WorkOrderStatusCode;
    public String WorkOrderTypeCode;
  }
  
  public class Address
  {
    public String AddressLine1;
    public String AddressLine2;
    public String Locality;
    public String AdministrativeArea;
    public String PostalCode;
    public String Country;
  }
}

DISCLAIMER

All sample code is provided by Fleetmatics, A Verizon Company, for illustrative purposes only. These examples have not been thoroughly tested under all conditions. Fleetmatics, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. All programs contained herein are provided to you “AS IS” without any warranties of any kind.

The POST Work Order method within the Planning and Scheduling – Work Order API enables integration users to create work orders within the referenced REVEAL account. There are several business rules and details regarding the field specifics within a work order request, so please be sure to review the documentation associated with the Planning and Scheduling – Work Order API before beginning.

Main Method
using System;

namespace Rest_Post_WorkOrder_Example
{
    class Program
    {
        static void Main()
        {
            // Token call goes here, see Rest_Token_Example

            // App Id from Fleetmatics Integration Manager (FIM)
            string appId = "companyname-p-us-4654sdf4fa351af65dsf1d";

            // Post Workorder URI
            string postWorkOrderUri = "https://fim.api.us.fleetmatics.com/pas/v1/workorders";

            // Local variables that correspond to post body fields (Workorder and Address)
            string actualDateUtc = new DateTime(2017, 04, 17, 13, 00, 02).ToString("yyyy-MM-ddTHH:mm:ss");
            int actualDurationSecs = 120;
            string addressLine1 = "935 John Glenn Dr";
            string addressLine2 = null;
            string locality = "Independence";
            string administrativeArea = "Oh";
            string postalCode = "44131";
            string country = "US";
            string clientCustomerId = "10150";
            string description = "This is a Test WO";
            string driverNumber = "101";
            double latitude = 0.0;
            double longitude = 0.0;
            int? onSiteDurationSecs = null;
            double radiusInKM = .322;
            string scheduledDateUtc = new DateTime(2017, 04, 18, 19, 00, 00).ToString("yyyy-MM-ddTHH:mm:ss");
            int scheduledDurationSecs = 120;
            string statusChangeDateUtc = null;
            string workOrderNumber = "WOTEST_#";
            string statusCode = "Open";
            string typeCode = "SO";

            // Create new POST_WorkOrder object
            var rest_post = new POST_WorkOrder();

            // Pass in local variables to create a workorder object
            rest_post.CreateWorkOrder(actualDateUtc, actualDurationSecs, addressLine1, addressLine2, locality, administrativeArea, postalCode,
                                      country, clientCustomerId, description, driverNumber, latitude, longitude, onSiteDurationSecs, radiusInKM,
                                      scheduledDateUtc, scheduledDurationSecs, statusChangeDateUtc, workOrderNumber, statusCode, typeCode);

            // Call method to execute the API call
            rest_post.PostWorkOrder(/* token object or auth string passed in here */, postWorkOrderUri, appId);
        }
    }
}
POST_WorkOrder Class
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Script.Serialization;

namespace Rest_Post_WorkOrder_Example
{
    public class POST_WorkOrder
    {
         private WorkOrder _workOrder { get; set; }

         public void PostWorkOrder(/* token object or auth string passed here */, string postWorkOrderUri, string appId)
         {
            // Construct authentication header for FIM
            string authHeader = string.Format("Atmosphere atmosphere_app_id={0}, Bearer {1}", appId, /* token authentication string goes here */);

	    // Serialize workorder object into JSON for POST body
            string workOrderContent = new JavaScriptSerializer().Serialize(_workOrder);

	    // Create the body, pass in serialized data and set content type
            string bodyContent = new StringContent(workOrderContent, Encoding.UTF8, "application/json");

            // Begin new HttpClient. Use "using" to ensure the resource is released
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", authHeader);     // Pass in FIM auth header

                // Pass in URI, supply bodyContent, and execute REST POST
                using(HttpResponseMessage response = client.PostAsync(postWorkOrderUri, bodyContent).Result)
                (
                    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);       // Logging
                    Console.WriteLine(response.Content.ReadAsStringAsync().Result);                        // Read result from response

                    // True if HttpStatusCode was in the successful range (200-299); otherwise false
                    if (response.IsSuccessStatusCode)
                    {
                        _workOrder = null;                                         // Clear workorder object
                        return;
                    }

                    // If this is reached, the call has failed
                    switch (response.StatusCode)
                    {
                        case HttpStatusCode.Unauthorized:
                            // Optional token renewal here, see Rest_Token_Example
                        break;
                        /*
                          ... Other cases here
                        */
                    default:
                        // Take another action
                        break;
                }
            }
        }

        // Public method used to create the workorder object which contains a nested Address object.
        // After serialization, this will be used as the body for the POST command
        public void CreateWorkOrder(string actualDateUtc, int? actualDurationSecs, string addressLine1, string addressLine2, string locality, string administrativeArea,
                                    string postalCode, string country, string clientCustomerId, string description, string driverNumber, double latitude, double longitude,
                                    int? onSiteDurationSecs, double radiusInKM, string scheduledDateUtc, int? scheduledDurationSecs, string statusChangeDateUtc,
                                    string workOrderNumber, string statusCode, string typeCode)
        {
            _workOrder = new WorkOrder
            {
                ActualDateUtc = actualDateUtc,
                ActualDurationSeconds = actualDurationSecs,
                Address = new Address
                {
                    AddressLine1 = addressLine1,
                    AddressLine2 = addressLine2,
                    Locality = locality,
                    AdministrativeArea = administrativeArea,
                    PostalCode = postalCode,
                    Country = country,
                },
                ClientCustomerId = clientCustomerId,
                Description = description,
                DriverNumber = driverNumber,
                Latitude = latitude,
                Longitude = longitude,
                OnSiteDurationSecs = onSiteDurationSecs,
                RadiusInKM = radiusInKM,
                ScheduledDateUtc = scheduledDateUtc,
                ScheduledDurationSecs = scheduledDurationSecs,
                StatusChangeDateUtc = statusChangeDateUtc,
                WorkOrderNumber = workOrderNumber,
                WorkOrderStatusCode = statusCode,
                WorkOrderTypeCode = typeCode,
            };
        }
    }

    public class WorkOrder
    {
         public string ActualDateUtc { get; set; }
         public int? ActualDurationSeconds { get; set; }
         public Address Address { get; set; }
         public string ClientCustomerId { get; set; }
         public string Description { get; set; }
         public string DriverNumber { get; set; }
         public double Latitude { get; set; }
         public double Longitude { get; set; }
         public int? OnSiteDurationSecs { get; set; }
         public double RadiusInKM { get; set; }
         public string ScheduledDateUtc { get; set; }
         public int? ScheduledDurationSecs { get; set; }
         public string StatusChangeDateUtc { get; set; }
         public string WorkOrderNumber { get; set; }
         public string WorkOrderStatusCode { get; set; }
         public string WorkOrderTypeCode { get; set; }
    }

    public class Address
    {
         public string AddressLine1 { get; set; }
         public string AddressLine2 { get; set; }
         public string Locality { get; set; }
         public string AdministrativeArea { get; set; }
         public string PostalCode { get; set; }
         public string Country { get; set; }
    }
}

DISCLAIMER

All sample code is provided by Fleetmatics, A Verizon Company, for illustrative purposes only. These examples have not been thoroughly tested under all conditions. Fleetmatics, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. All programs contained herein are provided to you “AS IS” without any warranties of any kind.

Microsoft Visual Studio

To open and use the zipped Visual Studio projects, you will need a copy of Microsoft Visual Studio. Unzip the file and click on the Visual Studio solution file to begin, after the above requirements have been met.

Xamarin Interactive Workbooks

Xamarin Workbooks provide a blend of documentation and code that is perfect for experimentation, learning, and creating code. To be able to view the interactive workbooks provided by Fleetmatics, please check the specific requirements for your OS and install Xamarin Workbooks, here.