Calculating Values with Custom Functions

Prev Next
  • PT

  • ES

  • AO

  • CV

  • MZ

  • Professional

  • Executive

  • Public Sector

  • Omnia

  • Evolution


Available with Service Release 6 of version 10.20

Custom functions let you perform value calculations through scripts (written in JavaScript), without using extensibility. These functions can be used to calculate earnings, deductions, and overtime amounts.

Implementing and validating these functions requires knowledge of JavaScript programming, as well as of the Primavera ERP's API, particularly the entities involved in payroll processing.


Calculation

This feature lets you calculate earnings, deductions, and overtime by defining specific calculation rules. It's mainly intended for scenarios where the values to calculate cannot be obtained through the application's standard formulas, letting you implement custom calculation logic.

Custom functions are a simplified version of extensibility, meaning they let you define a JavaScript formula that calculates the value, without needing to use classic extensibility.

Cegid Pulse Assistance (Evolution only)

Cegid Pulse can help create custom functions by converting a request written in natural language into a JavaScript script. Despite this assistance, you should always review, validate, and test the generated code before using it in a production environment.

The custom function must return only the value of the item (earnings, deduction, or overtime). Whenever applicable, the quantity continues to be calculated according to the normal rules for the respective item.

Specific Aspects of Deductions

For deductions, the custom function is not applied to system deductions:

  • IRS;

  • Social Security;

  • CGA;

  • Funds;

  • ADSE;

  • Insurance

As an exception, the feature can be used for the following deduction types:

  • Other IRS deductions;

  • Union deductions;

  • Any other deduction that does not fall under system deductions.

When a deduction is calculated through a custom function, the returned value is treated as the deduction's taxable amount, with the percentage configured on the item subsequently applied. This means that, when the value returned by the function corresponds to the desired final amount, the deduction's percentage should be set to 100%.


Creation

To add a custom function, follow these steps:

  1. Go to the corresponding entity (the Earnings Items, Deductions, or Overtime tables) where you want to calculate the value;

  2. Create the item and fill in the usual fields;

  3. Configure the calculation as follows:

    • Earnings Items: select the Custom Function formula;

    • Overtime and Deductions: select the Custom Function option;

  4. Click the Fx button to open the formula editor;

  5. Enter the code, or use Pulse to generate the function's code;

  6. Validate the function's behavior through a manual processing run;

  7. Use the function in the production environment.

The custom function's expression should return the value of the earnings item, deduction, or overtime that will be considered for the final amount, and the value returned must be a number (Number).

You should write functions that are simple and efficient, since the function will be evaluated for every case in which it's referenced. Functions with high complexity can impact processing performance.

Learn more about the formula editor in the support article.


Context Objects

When the custom function is evaluated, the system will provide the following parameters as context variables:

Earnings Items

Variable

Description

Processamento

Processing entity being processed (RhpBEProcessamento);

Funcionario

Employee entity being processed (RhpBEFuncionario);

Remuneracao

Earnings item entity being calculated (RhpBERemuneracao);

ProcRemuneracao

Processing earnings item entity being processed (RhpBEProcRemuneracao);

Parametros

HR module parameters (RhpBEParametros).

Overtime

Variable

Description

Processamento

Processing entity being processed (RhpBEProcessamento);

Funcionario

Employee entity being processed (RhpBEFuncionario);

HoraExtra

Overtime entity being calculated (RhpBEHoraExtra);

ProcHoraExtra

Processing overtime entity being processed (RhpBEProcHoraExtra);

Parametros

HR module parameters (RhpBEParametros).

Deductions

Variable

Description

Processamento

Processing entity being processed (RhpBEProcessamento);

Funcionario

Employee entity being processed (RhpBEFuncionario);

Desconto

Deduction entity being calculated (RhpBEDesconto);

ProcDesconto

Processing deduction entity being processed (RhpBEProcDesconto);

Parametros

HR module parameters (RhpBEParametros).

Examples

The parameters listed above provide information that may be needed for the custom function to correctly calculate the value, by considering them in its calculation logic. Below are some examples of how to use these variables:

let dataAdmissao = Funcionario.DataAdmissao; // Employee's hire date
let dataProcessamento = Processamento.DataProcessamento; // Processing date
let codigoRemuneracaoVenc = Params.CodVencimento; // Code of the salary earnings item

The entities' structure is available in the custom function's editing form (context window), where you can navigate the entities' properties and view each property's data types.

There may be properties that are not filled in for the current processing run, or at the time the custom function is evaluated. For example:

  • the Processamento.DataSaida property will only be filled in if the processing run is for contract termination;

  • the Processamento.SalarioHoraHExtra property has no value because it's only obtained after calculating all the processing's earnings items, including the earnings item currently being calculated.

Learn more in the support article.


Cegid Pulse

To simplify the function creation process, you can write the calculation you want in natural language and ask Cegid Pulse to convert it into a JavaScript function. To get better results, you should:

  • use objective, detailed descriptions;

  • clearly specify the desired calculation rules;

  • identify the relevant entities and properties.

Since the result is generated by Artificial Intelligence, you should always validate and test the code before using it.

Custom function examples

Earnings Items

Returns 10% of the total value of the processing's earnings items. Note that it excludes the earnings item being processed, to prevent the earnings item's value from being included in the calculation.

This example also demonstrates the use of the dependencia function, to tell the application that this earnings item depends on the ones referenced.

Result:

 var valor = 0;
    for (const remuneracao of Processamento.Remuneracoes) {
        if (!Object.is(remuneracao, Remuneracao)) {
            valor += remuneracao.Valor;
            dependencia(remuneracao);
        }
    }
    return valor * 0.1;

Overtime

Calculates the value as follows:

  • If the overtime day is a Saturday or Sunday, apply 200% per hour;

  • On other days, consider:

    1. 150% for the first hour on a working day;

    2. 175% per hour or fraction of the following hours on a working day;

Result:

const diaSemana = ProcHoraExtra.Data.getDay(); // 0 = Sunday, 6 = Saturday
const tempoHoras = ProcHoraExtra.Tempo;
if (tempoHoras <= 0) {
    throw new Error("Invalid overtime duration (must be greater than 0).");
}
const valorBaseHora = ProcHoraExtra.ValorUnitario;
if (valorBaseHora <= 0) {
    throw new Error("Invalid base overtime value (must be greater than 0).");
}
let valorCalculado;
if (diaSemana === 0 || diaSemana === 6) {
    // Weekend: 200% per hour
    valorCalculado = tempoHoras * valorBaseHora * 2;
} else {
    // Working day: 150% for the first hour, 175% for the remaining hours or fractions
    const primeiraHora = Math.min(tempoHoras, 1); // maximum 1 hour for the first hour
    const horasRestantes = Math.max(tempoHoras - primeiraHora, 0);
    const valorPrimeiraHora = primeiraHora * valorBaseHora * 1.5; // 150% = 1.5 * base
    const valorHorasSeguintes = horasRestantes * valorBaseHora * 1.75; // 175% = 1.75 * base
    valorCalculado = valorPrimeiraHora + valorHorasSeguintes;
}
// Rounds the final result to 2 decimal places
const valorFinal = Number(valorCalculado.toFixed(2));
return valorFinal;

Deductions

Calculates a deduction amount that is:

  • €480.92 per active spouse

  • €250 per active child (descendant)

Result:

const valorPorConjugeAtivo = 480.92;
const valorPorFilhoAtivo = 250;
let numConjugesAtivos;
if (Funcionario.EstadoCivil === "001") {
    numConjugesAtivos = 1;
} else {
    numConjugesAtivos = 0;
}
const numFilhosAtivos = Funcionario.Dependentes;
let valorDesconto = (numConjugesAtivos * valorPorConjugeAtivo) + (numFilhosAtivos * valorPorFilhoAtivo);
valorDesconto = Number(valorDesconto.toFixed(2));
return valorDesconto;

These examples were generated using Artificial Intelligence. If you try to replicate the example, you may get different scripts.


Special Methods

In addition to the context variables, there are some special methods that can be used in the custom function:

dependencia()

dependencia(RhpBEProcRemuneracao procRemuneracao)

Lets you declare dependencies on other earnings items, so the system knows that the earnings item for which the custom function is being calculated depends on the value of other earnings items.

    dependencia(remuneracao);

log()

log(mensagem: string): void

Lets you add a log message to the ERP's Log. This option can be useful for diagnosing the value of variables being used in the function.

    log('Valor = ' + valor.toString());

DaValorAtributos()

DaValorAtributos(tabela: string, atributos: string, campoChave: string, valorChave: any): StdBECampos

Returns the value of the attributes for the specified table. In the atributos parameter, specify the attribute names separated by commas.

// Get the fields from the Instrumentos table, requesting only the 'NumHoras' attribute
 const camposInstrumento = DaValorAtributos(
    'Instrumentos',   // table name
    'NumHoras',       // list of attributes to return (only NumHoras)
    'Instrumento',    // key field in the Instrumentos table
    Funcionario.Instrumento // key value: employee's instrument
);
const campoNumHoras = camposInstrumento[0];
log("numHoras" + campoNumHoras.valor.toString());
return campoNumHoras.Valor;

DaValorAtributosCondicao()

DaValorAtributosCondicao(tabela: string, atributos: string, expressaoCondicao: string): StdBECampos

Returns the value of the attributes for the specified table. In the atributos parameter, specify the attribute names separated by commas, and a sql condition in the expressaoCondicao parameter.

const camposInstrumento = DaValorAtributosCondicao(
    "RHP_ParametrosIAS", //table name
    "ValorIAS,Tipo",     //list of attributes to return (valorIAS and tipo)
    "DataInicio = '2026-01-01' and tipo = 1" //condition expression
);
if (camposInstrumento)
{
    return camposInstrumento["ValorIAS"].Valor;
}
return 0;