CAP | FE v4 | Totales en tabla analítica

Activar totales y subtotales por grupo en una tabla analítica de Fiori Elements v4 con SAP CAP (Node.js) y HANA, paso a paso.

Este post explica paso a paso cómo activar totales (sumatorios) en una tabla analítica de Fiori Elements v4 usando SAP CAP (Node.js) y HANA. El objetivo es que puedas replicarlo rápido en tu propio proyecto.

Repositorio de referencia (código completo): https://github.com/GonzaloMB/Totals_CAP_v4

De dónde salen los totalesABC123db/ Bookstitle · stock01srv/ projectionservice.Books02annotations.cdsMeasure · #SUM03HANAgroupby · aggregateCAP Node.jsodata_new_parser05AnalyticalTableFE v4 · UI5 1.112+06footer total+ group sumsUI.Total$apply
FIG. 1De dónde salen los totales

Requisitos

  • CAP en Node.js + HANA
  • App FE v4 (List Report) con AnalyticalTable
  • UI5 1.112.1 o superior
  • Entorno: SAP BAS (recomendado) o local con @sap/cds

Modelo de datos (db/)

Define la entidad y marca el campo numérico que quieres totalizar (aquí, stock).

spec · abap
namespace my.bookshop;

entity Books {
  key ID       : Integer;
      title    : String  @Common.Label: 'Title';
      bookshop : String  @Common.Label: 'BookShop';
      stock    : Integer @Common.Label: 'Stock';
}

Servicio (srv/)

Proyecta la entidad en tu servicio para exponerla vía OData.

spec · abap
using my.bookshop as my from '../db/data-model';

service CatalogService {
    entity Books as projection on my.Books;
}

UI: manifest.json (APP/)

Configura el List Report para usar AnalyticalTable y asegúrate de fijar bien la versión de UI5.

Cambia el tipo de tabla:

spec · json
"targets": {
  "BooksList": {
    "type": "Component",
    "id": "BooksList",
    "name": "sap.fe.templates.ListReport",
    "options": {
      "settings": {
        "initialLoad": "Enabled",
        "entitySet": "Books",
        "controlConfiguration": {
          "@com.sap.vocabularies.UI.v1.LineItem": {
            "tableSettings": {
              "type": "AnalyticalTable"
            }
          }
        }
      }
    }
  }
}

Fija la versión de UI5 (ejemplo 1.112.1):

spec · json
"sap.platform.cf": {
  "ui5VersionNumber": "1.112.1"
},
"sap.ui5": {
  "flexEnabled": true,
  "dependencies": {
    "minUI5Version": "1.112.1",
    "libs": {
      "sap.m": {},
      "sap.ui.core": {},
      "sap.ushell": {},
      "sap.fe.templates": {}
    }
  }
}

Anotaciones (APP/annotations.cds)

Define la agrupación, los totales por defecto y la medida con su agregación. Esto activa el total en el pie de la tabla y los totales por grupo.

spec · abap
using CatalogService as service from '../../srv/cat-service';

annotate service.Books with @(
    Aggregation.ApplySupported        : { GroupableProperties: [
        title,
        bookshop
    ]},
    Aggregation.CustomAggregate #stock: 'Edm.Int32',
    UI.PresentationVariant            : {
        Total         : [stock],
        Visualizations: ['@UI.LineItem']
    },
    UI.SelectionFields                : [
        title,
        bookshop,
        stock
    ],
    UI.HeaderInfo                     : {
        $Type         : 'UI.HeaderInfoType',
        TypeName      : 'Book Stock Totals',
        TypeNamePlural: 'Book Stock Totals',
        Title         : { Value: 'Book Stock Totals' }
    },
    UI.LineItem                       : [
        { $Type: 'UI.DataField', Value: title },
        { $Type: 'UI.DataField', Value: bookshop },
        { $Type: 'UI.DataField', Value: stock }
    ]
);

annotate service.Books with @(
    UI.FieldGroup #GeneratedGroup1: {
        $Type: 'UI.FieldGroupType',
        Data : [
            { $Type: 'UI.DataField', Value: title },
            { $Type: 'UI.DataField', Value: bookshop },
            { $Type: 'UI.DataField', Value: stock }
        ]
    },
    UI.Facets: [{
        $Type : 'UI.ReferenceFacet',
        ID    : 'GeneratedFacet1',
        Label : 'General Information',
        Target: '@UI.FieldGroup#GeneratedGroup1'
    }]
) {
    stock @Analytics.Measure @Aggregation.default: #SUM;
    ID    @UI.Hidden: true;
};

Puntos clave:

  • UI.PresentationVariant.Total: muestra la fila de totales en el pie de la tabla para stock.
  • Aggregation.ApplySupported.GroupableProperties: qué campos se pueden agrupar.
  • Aggregation.CustomAggregate: tipo de agregado para stock (entero).
  • @Analytics.Measure + @Aggregation.default: #SUM: marca stock como medida sumable.

CAP Node.js: parser OData para $apply

En CAP (Node.js), ciertas combinaciones de $apply (como concat(...)) pueden fallar con el parser por defecto. Activa el nuevo parser (experimental) en package.json para soportar las consultas con agrupación de la AnalyticalTable de FE v4.

spec · json
{
  "cds": {
    "requires": {
      "db": "hana"
    },
    "features": {
      "odata_new_parser": true
    }
  }
}

Sin esta opción, peticiones como la siguiente pueden fallar en Node.js aunque funcionen en CAP Java:

spec · http
GET /BooksAggregate?$apply=concat(groupby((ID,category,title))/aggregate($count%20as%20UI5__leaves),groupby((category))/concat(aggregate($count%20as%20UI5__count),%20top(72)))

Ejecuta y verifica

  1. Arranca el proyecto: cds watch.
  2. Abre la app FE (List Report de Books).
  3. Comprueba:
    • El pie de la tabla muestra el total de stock.
    • Aparecen totales por grupo al agrupar por title/bookshop.
    • No hay errores de $apply (si los hay, revisa el nuevo parser y los targets de tus anotaciones).

Errores habituales

  • No se ve la fila de totales: confirma UI.PresentationVariant.Total y que stock es @Analytics.Measure con #SUM.
  • La agrupación no suma: añade el campo a GroupableProperties y revisa CustomAggregate.
  • $apply falla con concat(...): activa "odata_new_parser": true en package.json.
  • Target de anotación incorrecto: annotate debe apuntar a service.Books (no a la entidad del namespace).

Enlaces