Class ItemSummaryQuery<T extends PersistedObject & HasCalculableObjectItems>

Object
ItemSummaryQuery<T>
Type Parameters:
T - the type of the object whose items are summarized, for example a Simulation

public class ItemSummaryQuery<T extends PersistedObject & HasCalculableObjectItems> extends Object
A summary query that groups the line items of one or more Simulations and aggregates their numeric fields, for example as a sum or an average. The query can group the items by an item field, by a product field, or by both, and it can count the items in each group.

You do not create an instance yourself. Get one from PublicGroovyAPI.getSimulationSummaryQuery(), set it up with the methods of this class, and run it with PublicGroovyAPI.runSummaryQuery(ItemSummaryQuery). Setting up the query does not read or change any data. The database is read only when api.runSummaryQuery() runs, and the query never writes data.

Deprecated entry points: the summary queries for Price Lists (api.getPricelistSummaryQuery()), Live Price Grids (api.getPriceGridSummaryQuery()) and Rebate Records (api.getRebateRecordSummaryQuery()) are deprecated since version 14.0. For those items, use PublicGroovyAPI.queryApi() with QapiPriceListLineItem, QapiPriceGridLineItem or QapiRebateRecord instead.

Result rows: api.runSummaryQuery() returns a list with one map per group. Each map contains these keys:

  • groupKey: the value of the group-by field. When both an item and a product group-by are set, this is the product field value.
  • groupKey2: the item field value. Present only when both an item and a product group-by are set.
  • countKey: the number of items in the group. Present only when setDoCount(boolean) is set to true.
  • One key per projection: the lower-case form of <aggregation>_<field>_<weight>, with spaces removed. For example, addProjection("Cost", "SUM") returns its value under sum_cost_.
  • totalWeight_ followed by the projection key: the weight used to combine the projection value with other groups.
The list also contains a row whose groupKey is "TOTAL"<T extends PersistedObject & HasCalculableObjectItems>. It combines the values of all groups. When no group-by is set, it is the only row.

Combining values: the same rules apply to the "TOTAL"<T extends PersistedObject & HasCalculableObjectItems> row and to a group that is merged over several objects (see addObjectTypedId(String)). SUM, MIN and MAX values are added up, so the MIN and MAX values of these rows are sums of the minimums or maximums. AVG values are combined as a weighted average.

Simulation projections: in the query from api.getSimulationSummaryQuery(), every call of addProjection(String, String) or addProjection(String, String, String) also adds a projection of the previous value of the field (prefix oldVal_). getProjections() and getNumberOfProjections() therefore return two projections per call. Each result row then also contains these keys, for example for addProjection("resultPrice", "SUM"):

  • oldval_sum_resultprice_: the aggregated previous value, and its totalWeight_oldval_sum_resultprice_.
  • changeabs_sum_resultprice_: the new value minus the previous value.
  • changepct_sum_resultprice_: that difference divided by the previous value, or null when the previous value is 0.
The change keys are present only when both the new and the previous value are not null. They are reliable only with one aggregation per field: the query finds the new value by the field name alone, so with several projections of the same field (for example SUM and AVG of resultPrice), the change keys compare the previous value with the new value of the last projection of that field.

Example:


 def query = api.getSimulationSummaryQuery()
 query.addObjectTypedId("12.SIM")
 query.setItemGroupBy("attribute1")
 query.setDoCount(true)
 query.addProjection("resultPrice", "SUM")

 def rows = api.runSummaryQuery(query)
 def total = rows.find { it.groupKey == "TOTAL" }
 
See Also:
  • Field Details

    • TOTAL_KEY

      public static final String TOTAL_KEY
      The groupKey value of the result row that holds the totals over all groups.
      See Also:
  • Constructor Details

    • ItemSummaryQuery

      public ItemSummaryQuery()
      Internal: used by the server to read saved queries. Not for use in logic. Get a query from PublicGroovyAPI.getSimulationSummaryQuery() instead.
    • ItemSummaryQuery

      public ItemSummaryQuery(String itemToObjectFkName)
      Internal: used by the server. Not for use in logic. Get a query from PublicGroovyAPI.getSimulationSummaryQuery() instead.
      Parameters:
      itemToObjectFkName - the item field that holds the Id of the parent object, for example simulationId
  • Method Details

    • isDualGroupBy

      public boolean isDualGroupBy()
      Checks whether the query groups the items by both an item field and a product field. In that case, each result row has a groupKey (product field value) and a groupKey2 (item field value).
      Returns:
      true when both setItemGroupBy(String) and setProductGroupBy(String) are set to a non-empty value
    • isNoGroupBy

      public boolean isNoGroupBy()
      Checks whether the query has no group-by. In that case, the result contains only the "TOTAL"<T extends PersistedObject & HasCalculableObjectItems> row.
      Returns:
      true when neither an item nor a product group-by is set
    • getItemGroupBy

      public String getItemGroupBy()
      Returns the item field that the query groups by.
      Returns:
      the item field name or label, or null when not set
      See Also:
    • setItemGroupBy

      public void setItemGroupBy(String itemGroupBy)
      Groups the items by the value of an item field. Each distinct value produces one result row. You can combine it with setProductGroupBy(String); the product field value is then returned as groupKey and the item field value as groupKey2.

      Example:

      
       def query = api.getSimulationSummaryQuery()
       query.addObjectTypedId("12.SIM")
       query.setItemGroupBy("attribute1")
       query.addProjection("resultPrice", "SUM")
       def rows = api.runSummaryQuery(query)
       
      Parameters:
      itemGroupBy - the name of the item field (for example "attribute1") or its label. null or an empty string removes the item group-by. If the name or label cannot be resolved to an item field, api.runSummaryQuery() fails with an error.
      See Also:
    • isDoCount

      public boolean isDoCount()
      Checks whether the query counts the items in each group.
      Returns:
      true when the result rows contain countKey
      See Also:
    • setDoCount

      public void setDoCount(boolean doCount)
      Sets whether the query counts the items in each group. When true, each result row contains the number of items under the countKey key. The default is false.

      Example:

      
       def query = api.getSimulationSummaryQuery()
       query.addObjectTypedId("12.SIM")
       query.setDoCount(true)
       query.addProjection("resultPrice", "SUM")
       def itemCount = api.runSummaryQuery(query)[0].countKey
       
      Parameters:
      doCount - true to count the items in each group
    • getItemToObjectFkName

      public String getItemToObjectFkName()
      Internal: used by the server to build the database query. Not for use in logic.
      Returns:
      the item field that holds the Id of the parent object
    • setItemToObjectFkName

      public void setItemToObjectFkName(String itemToObjectFkName)
      Internal: used by the server to build the database query. Not for use in logic.
      Parameters:
      itemToObjectFkName - the item field that holds the Id of the parent object
    • getItemSqlAlias

      public String getItemSqlAlias()
      Internal: used by the server to build the database query. Not for use in logic.
      Returns:
      the alias of the item table in the database query
    • setItemSqlAlias

      public void setItemSqlAlias(String itemSqlAlias)
      Internal: used by the server to build the database query. Not for use in logic.
      Parameters:
      itemSqlAlias - the alias of the item table in the database query
    • getAllItemsFilter

      public Filter getAllItemsFilter(T calcObj)
      Internal: used by the server to build the database query. Not for use in logic.
      Parameters:
      calcObj - the object whose items are queried
      Returns:
      a filter that matches all items of the object
    • getItemFilter

      public Filter getItemFilter()
      Returns the filter that limits which items are summarized.
      Returns:
      the item filter, or null when not set
      See Also:
    • setItemFilter

      public void setItemFilter(Filter itemFilter)
      Limits the summary to the items that match a filter on item fields. The filter is combined with AND with the restriction to the objects added by addObjectTypedId(String).

      Example:

      
       def query = api.getSimulationSummaryQuery()
       query.addObjectTypedId("12.SIM")
       query.setItemFilter(Filter.equal("attribute1", "EU"))
       query.addProjection("resultPrice", "SUM")
       def rows = api.runSummaryQuery(query)
       
      Parameters:
      itemFilter - the filter on item fields, or null to summarize all items
      See Also:
    • setCastCallback

      public void setCastCallback(ItemSummaryQuery.QueryGeneratorCallback castCallback)
      Internal: set by the server before the query runs. Not for use in logic.
      Parameters:
      castCallback - the callback that reads fields as numbers
    • getProductFilter

      public Filter getProductFilter()
      Returns the filter on Product fields that limits which items are summarized.
      Returns:
      the product filter, or null when not set
      See Also:
    • setProductFilter

      public void setProductFilter(Filter productFilter)
      Limits the summary to the items whose product matches a filter on Product fields. Items are matched to products by Stock Keeping Unit (SKU). When a product filter or a product group-by is set, items without a matching product are left out.

      Example:

      
       def query = api.getSimulationSummaryQuery()
       query.addObjectTypedId("12.SIM")
       query.setProductFilter(Filter.equal("attribute2", "Beef"))
       query.addProjection("resultPrice", "SUM")
       def rows = api.runSummaryQuery(query)
       
      Parameters:
      productFilter - the filter on Product fields, or null for no product filter
      See Also:
    • getSanitizedProductGroupBy

      public String getSanitizedProductGroupBy()
      Internal: used by the server to build the database query. Not for use in logic.
      Returns:
      the product group-by field with all characters except letters, digits and underscores removed, or null when not set
    • getProductGroupBy

      public String getProductGroupBy()
      Returns the Product field that the query groups by.
      Returns:
      the Product field name, or null when not set
      See Also:
    • setProductGroupBy

      public void setProductGroupBy(String productGroupBy)
      Groups the items by the value of a field of their product. Items are matched to products by Stock Keeping Unit (SKU), and items without a matching product are left out. You can combine it with setItemGroupBy(String); the product field value is then returned as groupKey and the item field value as groupKey2.

      Use the Product field name, not its label. Characters other than letters, digits and underscores are removed from the value.

      Example:

      
       def query = api.getSimulationSummaryQuery()
       query.addObjectTypedId("12.SIM")
       query.setProductGroupBy("attribute3")
       query.addProjection("resultPrice", "SUM")
       def rows = api.runSummaryQuery(query)
       
      Parameters:
      productGroupBy - the name of the Product field, for example "attribute3". null or an empty string removes the product group-by.
      See Also:
    • getObjectTypedIds

      public List<String> getObjectTypedIds()
      Returns the typed Ids of the objects whose items are summarized.
      Returns:
      the list of typed Ids, or null when no object was added
      See Also:
    • setObjectTypedIds

      public void setObjectTypedIds(List<String> objectTypedIds)
      Replaces the objects whose items are summarized. See addObjectTypedId(String).
      Parameters:
      objectTypedIds - the typed Ids of the objects, for example ["12.SIM", "13.SIM"]
      See Also:
    • addObjectTypedId

      public void addObjectTypedId(String objectTypedId)
      Adds an object whose items are summarized. Add at least one object before you run the query; without an object, api.runSummaryQuery() fails with an error. When you add several objects, their results are merged by group: SUM, MIN and MAX values are added up (so merged minimums and maximums are sums), and AVG values are combined as weighted averages. Objects that do not exist are skipped.

      Example:

      
       def query = api.getSimulationSummaryQuery()
       query.addObjectTypedId("12.SIM")
       query.addObjectTypedId("13.SIM")
       query.addProjection("resultPrice", "SUM")
       def rows = api.runSummaryQuery(query)
       
      Parameters:
      objectTypedId - the typed Id of the object, for example "12.SIM"
      See Also:
    • getProjections

      public List<ItemSummaryQuery.Projection> getProjections()
      Returns the projections (aggregated fields) of the query, in the order they were added. In a Simulation summary query, this includes the oldVal_ projection that each addProjection(String, String) call adds automatically (see the class description).
      Returns:
      the list of projections, or null when no projection was added
      See Also:
    • setProjections

      public void setProjections(List<ItemSummaryQuery.Projection> projections)
      Internal: used by the server to read saved queries. Not for use in logic. Use addProjection(String, String) and its overloads instead.
      Parameters:
      projections - the projections of the query
    • getNumberOfProjections

      public int getNumberOfProjections()
      Returns the number of projections (aggregated fields) of the query. In a Simulation summary query, this is twice the number of addProjection(String, String) calls, because each call also adds an oldVal_ projection (see the class description).
      Returns:
      the number of projections, or 0 when none was added
    • addProjection

      public void addProjection(String field, String aggregation)
      Adds an aggregated item field to the query. Add at least one projection before you run the query; without a projection, api.runSummaryQuery() fails with an error. In a Simulation summary query, this also adds a projection of the previous value of the field (see the class description).

      If the field cannot be found, for example because it was renamed, the projection returns 0.

      Example:

      
       def query = api.getSimulationSummaryQuery()
       query.addObjectTypedId("12.SIM")
       query.addProjection("resultPrice", "SUM")
       query.addProjection("attribute5", "AVG")
       def total = api.runSummaryQuery(query).find { it.groupKey == "TOTAL" }
       def sum = total["sum_resultprice_"]
       
      Parameters:
      field - the name of the numeric item field (for example "attribute5") or its label
      aggregation - the aggregation: "SUM", "AVG", "MIN" or "MAX", in upper case. Any other value, including lower case, makes the query fail or returns values under the wrong keys.
      See Also:
    • addProjection

      public void addProjection(String field, String aggregation, String weight)
      Adds an aggregated item field that is weighted by another item field. With "AVG", the result is the weighted average: the sum of field multiplied by weight, divided by the sum of the weights (0 when the weights add up to 0). With "SUM", "MIN" or "MAX", the query aggregates the field multiplied by the weight. In a Simulation summary query, this also adds a projection of the previous value of the field (see the class description).

      Example:

      
       def query = api.getSimulationSummaryQuery()
       query.addObjectTypedId("12.SIM")
       query.addProjection("resultPrice", "AVG", "attribute4")
       def rows = api.runSummaryQuery(query)
       
      Parameters:
      field - the name or label of the numeric item field
      aggregation - the aggregation: "SUM", "AVG", "MIN" or "MAX", in upper case. Any other value, including lower case, makes the query fail or returns values under the wrong keys.
      weight - the name or label of the numeric item field to weight by, or null for no weighting. If the name or label cannot be resolved to an item field, the weight is ignored and the projection is not weighted.
      See Also:
    • addProjection

      public void addProjection(String fieldPrefix, String field, String aggregation, String weight)
      Adds an aggregated value that is stored in the attribute extension of the items. The query reads the attribute-extension entry named by fieldPrefix followed by the resolved field name. For example, in a Simulation the prefix "oldVal_" reads the previous value of the field. The Simulation summary query already adds the oldVal_ projection for every addProjection(String, String) call, so do not add it yourself: an oldVal_ projection without the matching addProjection(field, ...) call makes api.runSummaryQuery() fail.

      With "AVG" and a weight, the prefix is also added to the weight field in the average, but the totalWeight_ value (used to combine groups, objects and the "TOTAL"<T extends PersistedObject & HasCalculableObjectItems> row) is the sum of the weight field without the prefix. With "SUM", "MIN" or "MAX", the weight field is read without the prefix.

      Example, reading the previous value that the Simulation summary query adds automatically:

      
       def query = api.getSimulationSummaryQuery()
       query.addObjectTypedId("12.SIM")
       query.addProjection("resultPrice", "SUM")
       def total = api.runSummaryQuery(query).find { it.groupKey == "TOTAL" }
       def oldSum = total["oldval_sum_resultprice_"]
       
      Parameters:
      fieldPrefix - the attribute-extension prefix, for example "oldVal_". Pass an empty string for a regular item field.
      field - the name or label of the numeric item field
      aggregation - the aggregation: "SUM", "AVG", "MIN" or "MAX", in upper case. Any other value, including lower case, makes the query fail or returns values under the wrong keys.
      weight - the name or label of the numeric item field to weight by, or null for no weighting
      See Also:
    • generateQuerySQL

      public String generateQuerySQL(PersistedObjectService objService, String productSQL, String itemSQL, T calcObj)
      Internal: used by the server to run the query. Not for use in logic.
      Parameters:
      objService - the server service that resolves fields
      productSQL - the condition generated from the product filter, or null
      itemSQL - the condition generated from the item filter
      calcObj - the object whose items are queried
      Returns:
      the database query, or null when there are no projections or no object
    • withProduct

      public boolean withProduct()
      Internal: used by the server to run the query. Not for use in logic.
      Returns:
      true when a product filter or a product group-by is set
    • aggregate

      public void aggregate(Map<String,Object[]> results, List<Object[]> queryResults)
      Internal: used by the server to merge the results of several objects. Not for use in logic.
      Parameters:
      results - the merged result rows by group key, updated in place
      queryResults - the rows returned by the database for one object
    • addTotal

      public void addTotal(Map<String,Object[]> results)
      Internal: used by the server to add the "TOTAL"<T extends PersistedObject & HasCalculableObjectItems> row. Not for use in logic.
      Parameters:
      results - the merged result rows by group key, updated in place
    • getProjectionName

      protected String getProjectionName(ItemSummaryQuery.Projection p)
      Internal: used by the server to build the result of api.runSummaryQuery(). Not for use in logic.
      Parameters:
      p - the projection
      Returns:
      the key of the projection value in the result rows
    • asListOfMaps

      public List<Map<String,Object>> asListOfMaps(Map<String,Object[]> resultList)
      Internal: used by the server to build the result of api.runSummaryQuery(). Not for use in logic.
      Parameters:
      resultList - the merged result rows by group key
      Returns:
      one map per result row, keyed as described in the class description
    • postProcessRow

      protected void postProcessRow(Map<String,Object> row)
      Internal: used by the server to add computed keys to a result row. Not for use in logic.
      Parameters:
      row - the result row
    • resolveFieldName

      protected String resolveFieldName(AbstractCalculableObjectItem calcObjItem, String fieldNameOrLabel, String itemSqlAlias, PersistedObjectService objService)
      Internal: used by the server to resolve a field name or label to a database column. Not for use in logic.
      Parameters:
      calcObjItem - an item of the summarized object
      fieldNameOrLabel - the field name or label to resolve
      itemSqlAlias - the alias of the item table
      objService - the service used to read the attribute metadata
      Returns:
      the resolved field name, or null if it cannot be resolved
    • getProjectionSQL

      public String getProjectionSQL(PersistedObjectService objService, T calcObj)
      Internal: used by the server to build the database query. Not for use in logic.
      Parameters:
      objService - the server service that resolves fields
      calcObj - the object whose items are queried
      Returns:
      the aggregate part of the database query, or null when there are no projections or no object