The Zurich release has arrived! Interested in new features and functionalities? Click here for more

Calculating End of Useful Life on the alm_hardware table

dbowens
Mega Contributor

I am trying to set the end of useful life for assets on the hardware table by using a combination of the created field on the hardware table and the useful life field set on the hardware models table. 

 

I have created the business rule below, but not able to get the 'end of useful life' calculation to work. Any assistance or direction would be helpful:

 

(function executeRule(current, previous /*null when async*/ ) {

    // SKip if no model selected
    if (!current.model) return;

    // Get the hardware model
    var model = new GlideRecord('cmdb_hardware_product_model');
    if (!model.get(current.model)) return;

    // Skip if not a computer or no useful life set
    if (model.model_category != 'Computer' || !model.useful_life) return;

    // Calculate end of useful life: created date + useful life months
    var endDate = new GlideDateTime(current.sys_created_on);
    endDate.addMonth(parseInt(model.useful_life));
    current.cmn_end_of_useful_life = endDate;


})(current, previous);
2 REPLIES 2

kaushal_snow
Mega Sage

Hi @dbowens ,

 

In your current script, you're assigning a GlideDateTime object directly to the cmn_end_of_useful_life field:

current.cmn_end_of_useful_life = endDate;

 

This might not work as expected because cmn_end_of_useful_life is likely a GlideDate field, not a GlideDateTime. Assigning a GlideDateTime object to a GlideDate field can lead to unexpected behavior...

 

If you found my response helpful, please mark it as ‘Accept as Solution’ and ‘Helpful’. This helps other community members find the right answer more easily and supports the community.

 

Thanks and Regards,
Kaushal Kumar Jha - ServiceNow Consultant - Lets connect on Linkedin: https://www.linkedin.com/in/kaushalkrjha/

J Siva
Tera Sage

Hi @dbowens 
As Kaushal mentioned, please validate the type of the date fields. Also, I found a typo in your script.
In line number 15, it should be addMonths, but in your script it has been written as addMonth.
Just update that and see..

(function executeRule(current, previous /*null when async*/ ) {

    // SKip if no model selected
    if (!current.model) return;

    // Get the hardware model
    var model = new GlideRecord('cmdb_hardware_product_model');
    if (!model.get(current.model)) return;

    // Skip if not a computer or no useful life set
    if (model.model_category != 'Computer' || !model.useful_life) return;

    // Calculate end of useful life: created date + useful life months
    var endDate = new GlideDateTime(current.sys_created_on);
    endDate.addMonths(parseInt(model.useful_life)); //TYPO - addMonths
    current.cmn_end_of_useful_life = endDate;


})(current, previous);

Regards,
Siva