---
schema_version: "1"
id: 25f6d0fae9181e471f60457ba4835a65b80e8c9143cde1df3a1b9cb46673c365
title: tpmGenericUtils Module
collection: legacydeveloper
version: current
locale: en-us
portal_url: https://docs.salesforce.com/legacydeveloper/current/en-us/retail_api/tpmGenericUtils_Module_Reference.md
canonical_url: https://developer.salesforce.com/docs/atlas.en-us.retail_api.meta/retail_api/tpmGenericUtils_Module_Reference.htm
source_site: developer.salesforce.com
content_type: documentation
content_hash: fa2d7aeaf79060f1a53d7e84d040a8fd5272e7f8b993e1c717fa54b350399b88
description: The tpmGenericUtils module provides replacements for accessing the @salesforce modules on components that have the cgcloud runtime namespace.
---
# tpmGenericUtils Module

The tpmGenericUtils module provides replacements for accessing the @salesforce modules on components that have the cgcloud runtime namespace.

## Namespace

cgcloud

## Implementation Example

import {
  apex,
  apexCacheable,
  getResponse,
  getStaticResourceURL,
  i18n,
  UserId,
  refreshApex,
  getSObjectValue,
  FORM\_FACTOR,
  CGCloudNamespace,
  CGCloudNamespaceWithUnderscore,
  TPMManualInput
} from 'cgcloud/tpmGenericUtils';

## Example: Perform Apex Calls

To call Apex methods, this module provides the apex, and apexCacheable functions. The Apex method to be called must be a global class, implementing the System.Callable interface.

global with sharing class ApexTest implements System.Callable {
  global class ApexTestException extends Exception {}

  // Interface method
  public Object call(String method, Map<String, Object> params) {
    // Both method and params will be received
    if (method == 'getAccounts') {
        return getAccounts(params);
    } else {
        // Exceptions can be thrown
        throw new Exception('Invalid method!');
    }
  }
  
  private static List<Account> getAccounts(Map<String, Object> params) {
    // Validate parameters
    if (params == null || String.isBlank((String) params.get('searchKey')) == null) {
        return new List<Account>();
    }
    
    // Extract parameters.
    // NOTE: Javascript Dates are received as Strings, they need to be parsed 
    // with
    // Date newDate = Date.valueOf((String.valueOf(dateString)));
    String searchKey = String.valueOf(params.get('searchKey'));
    String searchKeyProcessed = '%' + String.escapeSingleQuotes(searchKey) + '%';
    
    // return
    return \[SELECT Id, Name FROM Account WHERE Name LIKE :searchKeyProcessed LIMIT 100\];
  }
}

In your custom LWC, use the apex, and apexCacheable methods. The difference between apex, and apexCacheable is that apexCacheable uses the Lightning Web Components caching layer.

import { api, wire, LightningElement } from 'lwc';

import {
  CGCloudNamespaceWithUnderscore,
  apexCacheable,
  apex,
  getResponse,
  refreshApex
} from 'cgcloud/tpmGenericUtils';

export default class MyApexTestComponent extends LightningElement {
    
    imperativeData = null;
    
    wiredResponse = null;
    wiredData = null;
    
    // Store the params for the request
    requestParams = {
        searchKey = ''
    };
    
    // It's possible to use the wire adapter only with the apexCacheable method
    @wire(apexCacheable, {
      descriptor: {
        className: 'ApexTest',
        method: 'getAccounts'
      },
        params: '$requestParams'
    })
    wiredFunction(value) {
      this.wiredResponse = value; // Save wired data to be able to call
                                    // refreshApex later
      const { data, error } = getResponse(value); // Use 'getResponse' to extract data
      if (error) {
        console.error(error);
      }
      this.wiredData = data;
    }
    
    onSearchKeyChange(event) {
        // Set the new parameters
        this.requestParams = {
            searchKey = event.detail.value
        };
        // The change to requestParams will trigger a refresh of 
        // the wire adapter data.
    }
    
    onOtherEvent() {
        // You can force-refresh the wire adapter data
        // with refreshApex
        refreshApex(this.wiredResponse);
    }
    
    // You can call Apex method imperatively
    imperativeApex() {
        apex({ // You can also use apexCacheable to cache the response
          descriptor: {
            className: 'ApexTest',
            method: 'getAccounts'
          },
          params: this.requestParams
        })
        .then(getResponse) // use getResponse to extract data
        .then((data) => {
            this.imperativeData = data;
        });
    }
}

## Example: Load Static Resources

To get the URL of the static resource to be loaded, use the getStaticResourceURL function, and then load the static resource using the standard Lightning Web Components tools.

import { LightningElement } from 'lwc';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
import {
  getStaticResourceURL
} from 'cgcloud/tpmGenericUtils';

// getStaticResourceURL returns a Promise
const myZippedResourceURLPromise = getStaticResourceURL('MyZippedResource');

export default class MyStaticResourceComponent extends LightningElement {

    connectedCallback() {
        // Wait for the Base URL promise to resolve
        myZippedResourceURLPromise
            .then((baseURL) => Promise.all(\[
                // load your resources
                loadScript(this, baseURL + '/MyScript.js'),
                loadStyle(this, baseURL + '/MyStyle.css')
            \]))
            .then(() => {
                // You can use your resource after loaded
                window.MyApp.run();
            });
    }
}

## Example: Access the Internationalization Properties

You can use the i18n object to get the internationalization properties. The properties exposed are the ones described in [Salesforce Developer Component Library Documentation](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.create_i18n).

import {
  i18n
} from 'cgcloud/tpmGenericUtils';

console.log(i18n);

// {
//   "lang": "en-US",
//   "dir": "ltr",
//   "locale": "en-US",
//   "currency": "USD",
//   "firstDayOfWeek": 1,
//   "datetime": {
//     "shortDateFormat": "M/d/yyyy",
//     "mediumDateFormat": "MMM d, yyyy",
//     "longDateFormat": "MMMM d, yyyy",
//     "shortDateTimeFormat": "M/d/yyyy, h:mm a",
//     "mediumDateTimeFormat": "MMM d, yyyy, h:mm:ss a",
//     "shortTimeFormat": "h:mm a"
//   },
//   "number": {
//     "currencyFormat": "¤#,##0.00",
//     "currencySymbol": "$",
//     "decimalSeparator": ".",
//     "groupingSeparator": ",",
//     "numberFormat": "#,##0.###",
//     "percentFormat": "#,##0%"
//   },
//   "timeZone": "America/Los\_Angeles"
// }

## Example: Get the Current User ID

The UserId attribute returns the current User ID.

import {
  UserId
} from 'cgcloud/tpmGenericUtils';

console.log(UserId);

// 005TC0000002jXJYAY

## Example: Get the Client Form Factor

The FORM\_FACTOR attribute returns the client form factor.

import {
  FORM\_FACTOR
} from 'cgcloud/tpmGenericUtils';

console.log(FORM\_FACTOR);

// Large

## Example: Get the CGCloud Namespace

You can get the CGCloud namespace through the properties, CGCloudNamespace, and CGCloudNamespaceWithUnderscore.

import {
  CGCloudNamespace,
  CGCloudNamespaceWithUnderscore
} from 'cgcloud/tpmGenericUtils';

console.log(CGCloudNamespace);

// cgcloud

console.log(CGCloudNamespaceWithUnderscore);

// cgcloud\_\_

## Example: Use the TPMManualInput Class

The TPMManualInput class represents a manual input entry for the TPM grids. When reading manual inputs on TPM components, you receive an array of instances of the TPMManualInput class. By manipulating and setting this array again into the TPM component, you can change the loaded inputs for the TPM grids.

**Methods**

The TPMManualInput class supports the following methods:

- **getKPICode():** Returns the manual input editable KPI code.
- **getPeriodDateFrom():** Returns the period from date for the manual input. If the manual input is for the total period, it returns null.
- **getPeriodDateThru():** Returns the period through date for the manual input. If the manual input is for the total period, it returns null.
- **getTacticId():** Returns the tactic ID of the tactic the manual input applies to.
- **getProductId():** Returns the product ID of the product the manual input applies to.
- **getComponentId():** Returns the component ID of the BOM Component the manual input applies to.
- **getValue():** Returns the value of the manual input.

**Constructor**

The constructor for creating an instance of the TPMManualInput expects the options object as a single parameter. The options passed in this object define the characteristics of the manual input entry. Here are the possible options you can pass to the constructor:

<table class="featureTable sort_table" summary="">



          <thead class="thead sorted" align="left">
            <tr>
              <th class="featureTableHeader  " id="d47695e322">Property</th>

              <th class="featureTableHeader  " id="d47695e325">Type</th>

              <th class="featureTableHeader  " id="d47695e328">Description</th>

            </tr>

          </thead>

          <tbody class="tbody">
            <tr>
              <td class="entry" headers="d47695e322" data-title="Property"><samp class="codeph nolang">options.kpi</samp></td>

              <td class="entry" headers="d47695e325" data-title="Type">KPIDefinition</td>

              <td class="entry" headers="d47695e328" data-title="Description">Optional. The KPI definition to create the manual
                input for.&nbsp;You can get KPI definitions by calling the
                <samp class="codeph nolang">getKPIs()</samp>
                method. To create the manual input, a KPI definition
                must be for an editable or an editable calculated
                compound main KPI.<p class="p">Provide either <samp class="codeph nolang">options.kpi</samp> or
                  <samp class="codeph nolang">options.kpiCode</samp>.
                </p>
              </td>

            </tr>

            <tr>
              <td class="entry" headers="d47695e322" data-title="Property"><samp class="codeph nolang">options.kpiCode</samp></td>

              <td class="entry" headers="d47695e325" data-title="Type">String</td>

              <td class="entry" headers="d47695e328" data-title="Description">Optional. The editable KPI code to create the manual
                input for. <p class="p">Provide either <samp class="codeph nolang">options.kpi</samp> or <samp class="codeph nolang">options.kpiCode</samp>.</p>
              </td>

            </tr>

            <tr>
              <td class="entry" headers="d47695e322" data-title="Property"><samp class="codeph nolang">options.period</samp></td>

              <td class="entry" headers="d47695e325" data-title="Type">PeriodDefinition</td>

              <td class="entry" headers="d47695e328" data-title="Description">Required. The period definition to create the manual
                input for.&nbsp;You can get period definitions by calling the
                <samp class="codeph nolang">getPeriods()</samp>
                method.
              </td>

            </tr>

            <tr>
              <td class="entry" headers="d47695e322" data-title="Property"><samp class="codeph nolang">options.tacticId</samp></td>

              <td class="entry" headers="d47695e325" data-title="Type">String</td>

              <td class="entry" headers="d47695e328" data-title="Description">Optional. The Tactic ID the manual input applies to.
                <p class="p">Required if the KPI has the promotion tactic
                  scope. Default value is null.</p>
              </td>

            </tr>

            <tr>
              <td class="entry" headers="d47695e322" data-title="Property"><samp class="codeph nolang">options.productId</samp></td>

              <td class="entry" headers="d47695e325" data-title="Type">String</td>

              <td class="entry" headers="d47695e328" data-title="Description">Optional. The product ID the manual input applies to.
                It can be any level of the product hierarchy (Category,
                Brand, and more).<p class="p">If not set, the manual input
                  references the KPI total value. Default value is
                  null.</p>
              </td>

            </tr>

            <tr>
              <td class="entry" headers="d47695e322" data-title="Property"><samp class="codeph nolang">options.componentId</samp></td>

              <td class="entry" headers="d47695e325" data-title="Type">String</td>

              <td class="entry" headers="d47695e328" data-title="Description">Optional. The product ID of the BOM Component part
                where the input is applied.<p class="p">This option is only used
                  for KPIs whose scope include BOM Components. The
                  default value is null.</p>
              </td>

            </tr>

            <tr>
              <td class="entry" headers="d47695e322" data-title="Property"><samp class="codeph nolang">options.value</samp></td>

              <td class="entry" headers="d47695e325" data-title="Type">Number</td>

              <td class="entry" headers="d47695e328" data-title="Description">Optional. The numeric value for the KPI. The default
                value is null.</td>

            </tr>

          </tbody>

        </table>

**Example**

import { TPMManualInput } from 'cgcloud/tpmGenericUtils';

...

myMethod() {
   // Get TPM component relevant to the custom page
   const cmp = this.template.querySelector('cgcloud-...');
   
   // Get periods data
   const periods = await cmp.getPeriods();
   
   // Create a new TPM manual input instance
   const mi = new TPMManualInput({
        kpiCode: 'ABCD',
        period: periods.find((p) => p.periodtype === 'Total'),
        tacticId: sampleTacticId,
        productId: sampleCategoryId,
        value: 12345
   });
   
   // After creating the TPM Manual input you can add it to the existing
   // array and set it on the TPM component
   cmp.set...
}