---
sourceDocument: Referência de API do Brasil
sourceDocumentLink: https://servicenow-prod.fluidtopics.net/r/pt-BR/api-reference

 Release :

    - brazil

ft:locale :

    - pt-BR

ft:publication_title :

    - Referência de API do Brasil

ft:clusterId :

    - crapiref

bundleId :

    - crapiref

workflow :

    - Creator


---

# Scripts de atribuição de aprovação

# Scripts de atribuição de aprovação {#ariaid-title1}

Versão de lançamento: Brazil  
Atualizado 10 de set. de 2026  
![](https://www.servicenow.com/docs/portal-asset/ico-clock) 3 min. de leitura  
Esta é uma versão pesquisável dos scripts de aprovação e atribuição úteis.
Aviso:  
A personalização descrita aqui foi desenvolvida para uso em instâncias específicas e não é compatível com Now Support. Este método é fornecido no estado em que se encontra e deve ser testado cuidadosamente antes da implementação. Publique todas as perguntas e comentários sobre esta personalização no [fórum](http://community.service-now.com/) da nossa comunidade.

Para consulte [Viewing my approvals](https://www.servicenow.com/docs/access?context=viewing-my-approvals&version=brazil&pubname=brazil-security-management&ft:locale=en-US).

Atribua um grupo para solicitações de ESS
:
    O script de regras de atribuição a seguir atribui automaticamente um grupo para todas as solicitações de ESS.

        if(current.opened_by.roles==""){
            current.assignment_group.setDisplayValue('Network');
            current.update();}


Atribua item do catálogo ao grupo com base na tarefa do plano de entrega
:
    Esta regra de atribuição atribui um item do catálogo de serviços ao grupo de banco de dados se ele usar um plano de entrega que tenha uma tarefa de catálogo atribuída ao grupo de desktop.

        //Return catalog items that have no group but do have a delivery plan assigned
        var ri =new GlideRecord("sc_cat_item");
        ri.addQuery("group","=",null);
        ri.addQuery("delivery_plan","!=",null);
        ri.query();
        while(ri.next()){
            gs.log("Found an item");
            //Return tasks that point to the same delivery plan as the above item
            var dptask =new GlideRecord("sc_cat_item_delivery_task");
            dptask.addQuery("delivery_plan","=",ri.delivery_plan);
            dptask.query();while(dptask.next()){
                gs.log("Found a task");var gp = dptask.group.getDisplayValue();
                gs.log(gp);//If the task is assigned to desktop, assign the item's group to desktop
                if(dptask.group.getDisplayValue()=="Desktop"){
                    ri.group.setDisplayValue("Desktop");
                    gs.log("updating "+ ri.getDisplayValue());
                    ri.update();break;}}}


Atribua itens com uma tarefa
:
    Esta regra de atribuição atribui automaticamente todos os itens do catálogo com apenas uma tarefa associada a um grupo específico.

        //Get the catalog item for the current requested item
        var scCatItem =new GlideRecord("sc_cat_item");
        if(scCatItem.get('sys_id', current.cat_item)){
        // If the catalog item already has an assignment group or if using workflow we don't need to make an assignment
          if(!scCatItem.delivery_plan.nil()&& scCatItem.group.nil()){
                var dpTask =new GlideRecord("sc_cat_item_delivery_task");
                dpTask.addQuery("delivery_plan","=",scCatItem.delivery_plan);
                dpTask.query();
                if(dpTask.getRowCount()==1&& dpTask.next()){
                // Check that there is only 1 record in the GlideRecord
                    dpTask.group;}}}


Atribuição baseada na carga de trabalho

:   Tipo: Regra de negócio.

    Descrição: Preencha Atribuído a com base no membro do grupo de atribuição que tem a menor quantidade de incidentes ativos.  
    Parâmetros:

    * ordem: \> 1000 se você quiser executar após as regras de atribuição
    * condição: current.assigned_to: '' \&\& current.assignment_group !: ''
    * quando: antes, inserir/atualizar
    {#r_UsefulApprovalAssignmentScripts__ul_abh_ksv_qx}  

        var assignTo = getLowestUser();
        gs.addInfoMessage("assigning to is "+ assignTo);
        current.assigned_to= assignTo;
         
        function getLowestUser(){
          var userList =new Array();
          var cg =new GlideRecord('sys_user_grmember');
          cg.addQuery('group', current.assignment_group);
          cg.query();
          while(cg.next()){
            var tech = cg.user.toString();
            var cnt = countTickets(tech);
            gs.addInfoMessage("Tech counts "+ cg.user.name+' '+ cnt +" "+ tech);
            userList.push({ sys_id: tech,name: cg.user.name, count: cnt });}

          for(var i=0; i < userList.length; i++){
            gs.addInfoMessage(userList[i].sys_id+" "+ userList[i].name+" "+ userList[i].count);}
          userList.sort(function(a, b){
            gs.addInfoMessage("Sorting: "+ a.sys_id+"("+ a.count+");
            "+ b.sys_id+"("+ b.count+")");
            return a.count- b.count;});

          if(userList.length<=0)return"";
          return userList[0].sys_id;}
         
        function countTickets(tech){
          var ct =new GlideRecord('incident');
          ct.addQuery('assigned_to',tech);
          ct.addQuery('active',true);
          ct.query();
          return ct.getRowCount();}

Execute regras de atribuição quando a categoria for alterada

:   Tipo: Client script.

    Tabela: Incidente.  
    Descrição: Este exemplo é um client script onChange no campo de categoria em Incidente. Observação: Este script usado para usar AJAX síncrono (o comportamento assíncrono é especificado pelo terceiro parâmetro da chamada ajaxRequest). A implementação abaixo usa AJAX assíncrono. A desvantagem de usar a versão síncrona é que um problema de resposta de rede pode fazer com que o navegador trave.

        // Make an AJAX request to the server to get who this incident would be
        // assigned to given the current values in the record. This runs the assignment
        // rules thathave been defined in System Policy and returns the assigned_to and
        // the assignment_group
         
        function onChange(control, oldValue, newValue, isLoading){
          if(isLoading){return;
          // No change, do not do anything
          }

           // Construct the URL to ask the server for the assignment
          var url ="xmlhttp.do?sysparm_processor=AJAXAssignment&sys_target=incident";
          var uv = gel('sys_uniqueValue');
          if(uv){
                url +="&sys_uniqueValue="+ uv.value;}
          // Make the AJAX request to the server and get the response
          var serial = g_form.serialize();
          // get all values currently assigned to the incident
          var response = ajaxRequest(url, serial,true, responseFunc);}
         
        // This callback function handles the AJAX response.
        function responseFunc(response){
          varitem= response.responseXML.getElementsByTagName("item")[0];
          // Process the item returned by the server
          if(item){
          // Get the assigned_to ID and its display value and put them on the form
            varname=item.getAttribute("name");
            var name_label =item.getAttribute("name_label");
            if(name_label &&name){
              g_form.setValue('assigned_to',name, name_label);}
            else{
              g_form.setValue('assigned_to','','');}
            // Get the assignment_group ID and its display value and put then on the form
            var group =item.getAttribute("group");
            var group_label =item.getAttribute("group_label");
            if(group_label && group){
              g_form.setValue('assignment_group', group, group_label);}
            else{
              g_form.setValue('assignment_group','','');}}}

Aprovação personalizada de macro de IU
:   Para obter informações sobre como criar uma macro de IU de aprovação personalizada, consulte [Macros de IU](https://servicenow-prod.fluidtopics.net/ESVg5AxRLG2Lm9OYktnT_w#c_UIMacros "Macros de IU são componentes discretos em script que os administradores podem adicionar à interface do usuário.").

