Newer Version Available

This content describes an older version of this product. View Latest

tpmGenericUtils Module

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

Namespace

1cgcloud

Implementation Example

1import {
2  apex,
3  apexCacheable,
4  getResponse,
5  getStaticResourceURL,
6  i18n,
7  UserId,
8  refreshApex,
9  getSObjectValue,
10  FORM_FACTOR,
11  CGCloudNamespace,
12  CGCloudNamespaceWithUnderscore,
13  TPMManualInput
14} 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.

1global with sharing class ApexTest implements System.Callable {
2  global class ApexTestException extends Exception {}
3
4  // Interface method
5  public Object call(String method, Map<String, Object> params) {
6    // Both method and params will be received
7    if (method == 'getAccounts') {
8        return getAccounts(params);
9    } else {
10        // Exceptions can be thrown
11        throw new Exception('Invalid method!');
12    }
13  }
14  
15  private static List<Account> getAccounts(Map<String, Object> params) {
16    // Validate parameters
17    if (params == null || String.isBlank((String) params.get('searchKey')) == null) {
18        return new List<Account>();
19    }
20    
21    // Extract parameters.
22    // NOTE: Javascript Dates are received as Strings, they need to be parsed 
23    // with
24    // Date newDate = Date.valueOf((String.valueOf(dateString)));
25    String searchKey = String.valueOf(params.get('searchKey'));
26    String searchKeyProcessed = '%' + String.escapeSingleQuotes(searchKey) + '%';
27    
28    // return
29    return [SELECT Id, Name FROM Account WHERE Name LIKE :searchKeyProcessed LIMIT 100];
30  }
31}

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.

1import { api, wire, LightningElement } from 'lwc';
2
3import {
4  CGCloudNamespaceWithUnderscore,
5  apexCacheable,
6  apex,
7  getResponse,
8  refreshApex
9} from 'cgcloud/tpmGenericUtils';
10
11export default class MyApexTestComponent extends LightningElement {
12    
13    imperativeData = null;
14    
15    wiredResponse = null;
16    wiredData = null;
17    
18    // Store the params for the request
19    requestParams = {
20        searchKey = ''
21    };
22    
23    // It's possible to use the wire adapter only with the apexCacheable method
24    @wire(apexCacheable, {
25      descriptor: {
26        className: 'ApexTest',
27        method: 'getAccounts'
28      },
29        params: '$requestParams'
30    })
31    wiredFunction(value) {
32      this.wiredResponse = value; // Save wired data to be able to call
33                                    // refreshApex later
34      const { data, error } = getResponse(value); // Use 'getResponse' to extract data
35      if (error) {
36        console.error(error);
37      }
38      this.wiredData = data;
39    }
40    
41    onSearchKeyChange(event) {
42        // Set the new parameters
43        this.requestParams = {
44            searchKey = event.detail.value
45        };
46        // The change to requestParams will trigger a refresh of 
47        // the wire adapter data.
48    }
49    
50    onOtherEvent() {
51        // You can force-refresh the wire adapter data
52        // with refreshApex
53        refreshApex(this.wiredResponse);
54    }
55    
56    // You can call Apex method imperatively
57    imperativeApex() {
58        apex({ // You can also use apexCacheable to cache the response
59          descriptor: {
60            className: 'ApexTest',
61            method: 'getAccounts'
62          },
63          params: this.requestParams
64        })
65        .then(getResponse) // use getResponse to extract data
66        .then((data) => {
67            this.imperativeData = data;
68        });
69    }
70}

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.

1import { LightningElement } from 'lwc';
2import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
3import {
4  getStaticResourceURL
5} from 'cgcloud/tpmGenericUtils';
6
7// getStaticResourceURL returns a Promise
8const myZippedResourceURLPromise = getStaticResourceURL('MyZippedResource');
9
10export default class MyStaticResourceComponent extends LightningElement {
11
12    connectedCallback() {
13        // Wait for the Base URL promise to resolve
14        myZippedResourceURLPromise
15            .then((baseURL) => Promise.all([
16                // load your resources
17                loadScript(this, baseURL + '/MyScript.js'),
18                loadStyle(this, baseURL + '/MyStyle.css')
19            ]))
20            .then(() => {
21                // You can use your resource after loaded
22                window.MyApp.run();
23            });
24    }
25}

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.

1import {
2  i18n
3} from 'cgcloud/tpmGenericUtils';
4
5console.log(i18n);
6
7// {
8//   "lang": "en-US",
9//   "dir": "ltr",
10//   "locale": "en-US",
11//   "currency": "USD",
12//   "firstDayOfWeek": 1,
13//   "datetime": {
14//     "shortDateFormat": "M/d/yyyy",
15//     "mediumDateFormat": "MMM d, yyyy",
16//     "longDateFormat": "MMMM d, yyyy",
17//     "shortDateTimeFormat": "M/d/yyyy, h:mm a",
18//     "mediumDateTimeFormat": "MMM d, yyyy, h:mm:ss a",
19//     "shortTimeFormat": "h:mm a"
20//   },
21//   "number": {
22//     "currencyFormat": "ยค#,##0.00",
23//     "currencySymbol": "$",
24//     "decimalSeparator": ".",
25//     "groupingSeparator": ",",
26//     "numberFormat": "#,##0.###",
27//     "percentFormat": "#,##0%"
28//   },
29//   "timeZone": "America/Los_Angeles"
30// }

Example: Get the Current User ID

The UserId attribute returns the current User ID.

1import {
2  UserId
3} from 'cgcloud/tpmGenericUtils';
4
5console.log(UserId);
6
7// 005TC0000002jXJYAY

Example: Get the Client Form Factor

The FORM_FACTOR attribute returns the client form factor.

1import {
2  FORM_FACTOR
3} from 'cgcloud/tpmGenericUtils';
4
5console.log(FORM_FACTOR);
6
7// Large

Example: Get the CGCloud Namespace

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

1import {
2  CGCloudNamespace,
3  CGCloudNamespaceWithUnderscore
4} from 'cgcloud/tpmGenericUtils';
5
6console.log(CGCloudNamespace);
7
8// cgcloud
9
10console.log(CGCloudNamespaceWithUnderscore);
11
12// 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:
Property Type Description
options.kpi KPIDefinition Optional. The KPI definition to create the manual input for. You can get KPI definitions by calling the getKPIs() method. To create the manual input, a KPI definition must be for an editable or an editable calculated compound main KPI.

Provide either options.kpi or options.kpiCode.

options.kpiCode String Optional. The editable KPI code to create the manual input for.

Provide either options.kpi or options.kpiCode.

options.period PeriodDefinition Required. The period definition to create the manual input for. You can get period definitions by calling the getPeriods() method.
options.tacticId String Optional. The Tactic ID the manual input applies to.

Required if the KPI has the promotion tactic scope. Default value is null.

options.productId String Optional. The product ID the manual input applies to. It can be any level of the product hierarchy (Category, Brand, and more).

If not set, the manual input references the KPI total value. Default value is null.

options.componentId String Optional. The product ID of the BOM Component part where the input is applied.

This option is only used for KPIs whose scope include BOM Components. The default value is null.

options.value Number Optional. The numeric value for the KPI. The default value is null.
Example
1import { TPMManualInput } from 'cgcloud/tpmGenericUtils';
2
3...
4
5myMethod() {
6   // Get TPM component relevant to the custom page
7   const cmp = this.template.querySelector('cgcloud-...');
8   
9   // Get periods data
10   const periods = await cmp.getPeriods();
11   
12   // Create a new TPM manual input instance
13   const mi = new TPMManualInput({
14        kpiCode: 'ABCD',
15        period: periods.find((p) => p.periodtype === 'Total'),
16        tacticId: sampleTacticId,
17        productId: sampleCategoryId,
18        value: 12345
19   });
20   
21   // After creating the TPM Manual input you can add it to the existing
22   // array and set it on the TPM component
23   cmp.set...
24}