lsc-custom-scripts
Skill10 starsChanged 29 days agoApache-2.0View on GitHub
Guides Life Sciences Cloud (LSC) Custom Script configuration for validation, checklists, and Visit Action Validation. Use when user asks about custom scripts, visit validation scripts, CodeText, LifeScienceCustomScript, IIFE patterns, Locker Service proxy issues, headless LWC validation components, or a visit script that passes institution accounts.
In this repository39 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- roz-uiSkill
- lsc-account-managementSkill
- lsc-activity-planSkill
- lsc-agentforceSkill
- lsc-app-alertsSkill
- lsc-briefingsSkill
- lsc-calendar-tot-routineSkill
- lsc-config-migrationSkill
- lsc-consent-managementSkill
- lsc-data-migrationSkill
- lsc-data-modelSkill
- lsc-db-schemaSkill
- lsc-demo-data-loadingSkill
- lsc-events-managementSkill
- lsc-field-emailSkill
- lsc-health-checkSkill
- lsc-home-page-configurationSkill
- lsc-implementation-reviewSkill
- lsc-implementationSkill
- lsc-integration-patternsSkill
- lsc-intelligent-contentSkill
- lsc-key-account-managementSkill
- lsc-lists-filtersSkill
- lsc-mobile-app-settingsSkill
- lsc-mobile-validationSkill
- lsc-next-bestSkill
- lsc-performance-validationSkill
- lsc-product-managementSkill
- lsc-provider-engagement-complianceSkill
- lsc-quick-actions-configurationSkill
- lsc-reporting-analyticsSkill
- lsc-sample-managementSkill
- lsc-surveysSkill
- lsc-territory-alignmentSkill
- lsc-troubleshootSkill
- lsc-user-managementSkill
- lsc-visit-managementSkill
- salesforce-querySkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
20 rules. About 0 are common, 14 are distinctive, and 6 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈14
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 21
Always preserve the citation block (lines starting with > 📖, > 🔗, > 📂) from the tool response verbatim in your answer.
- Distinctive: line 31
Before building a custom script, help the user choose the right mechanism:
- Distinctive: line 39
Guidance: Start with validation rules whenever possible.
- Distinctive: line 53
Only one Visit Action Validation script runs per org: If multiple scripts of this type exist, only the first one executes (based on ID or …
- Distinctive: line 97
When debugging, look in the browser console on web and in device logs on iPad.
- Distinctive: line 103
All Visit Action Validation scripts must follow this pattern.
- Very specific: line 259
Always check both: record.ProductItemId || record.productitemid
- Very specific: line 325
Every builder/condition class has a _noNs variant for accessing custom (__c) fields without the managed-package namespace prefix — use the …
- Distinctive: line 345
When helping users write or debug custom scripts, always warn about these:
- Distinctive: line 351
Large scripts crash silently: If a script is too large, Locker Service fails to evaluate it.
- Very specific: line 361
Use
env.log()for debugging: Add env.log('scriptName - message') calls to trace execution. - Very specific: line 363
Guard globals: Always wrap execution in if (record && user && env && db).
- Distinctive: line 385
When the user asks about configuring custom scripts, ask them which mode they prefer:
- Distinctive: line 390
Default to guided setup when connected to an org, or documentation mode if no org is connected.
- Distinctive: line 407
If more than one Visit Action Validation script exists, warn immediately — only the first one (by ID/creation date) runs.
- Distinctive: line 427
After any LWC deployment, the user must click Refresh in Admin Console > Workflow Configuration > Custom Scripts to sync code to CodeText.
- Distinctive: line 431
If the user wants to create a new validation script:
- Distinctive: line 432
Ask what they want to validate
- Very specific: line 454
DO NOT: use run_soql for Admin Console settings — use list_admin_settings
- Very specific: line 455
DO NOT: use run_soql for mobile cache — use check_mobile_cache_status()
≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
How to Answer Custom Script Questions
Always call MCP tools to get sourced documentation first. Then supplement with the domain knowledge in this skill.
| User asks about... | Call this tool |
| Custom script concepts, setup, documentation | search_lsc_knowledge({ query: "custom scripts validation" }) |
| Current org custom script records | run_soql({ query: "SELECT Id, Name, ComponentName, Type, ObjectName, OperationEventType FROM LifeScienceCustomScript ORDER BY Type, Name" }) |
| Workflow configuration / stage objects | search_lsc_knowledge({ query: "workflow configuration stage objects" }) |
| Admin Console custom script settings | list_admin_settings({ category: "CustomScript" }) |
| Object fields and relationships | describe_sobject({ sobject: "LifeScienceCustomScript" }) |
| Mobile cache status | check_mobile_cache_status() |
| Visit configuration (related) | check_visit_config() |
| Visit validation passes for institutions, or does not run on Save | search_lsc_knowledge({ query: "Visit Action Validation institution guard Save" }) then follow Institution script guard below. |
Always preserve the citation block (lines starting with > 📖, > 🔗, > 📂) from the tool response verbatim in your answer.
Institution script guard
Load knowledge/modules/visit-management/support-engineering-visit-script-institution-guard.md. Finish only when the reply states every fact under Required answer. The primary cause is an inverted institution check in the customer's script. A Save path that does not run the script is a second cause, and only when neither account type runs it on Save.
Choosing a Validation Mechanism
Before building a custom script, help the user choose the right mechanism:
| Mechanism | When to use | Online (Web) | Offline (iPad) |
| Validation Rule | Simple, single-object, field-level checks expressible with standard formulas | Yes | Yes |
| Custom Script (Visit Action Validation) | Complex validations spanning multiple objects (samples, details, attendees, messages) | Yes | Yes |
| Apex Trigger | Last resort — validation requires data not available on mobile | Yes | No |
Guidance: Start with validation rules whenever possible. Move to Custom Script Visit Action Validation when the logic spans multiple objects or needs conditional checks that validation rules can't express. Use Apex triggers only when the required data isn't synced to the mobile app.
Custom Script Types
| Type | When it runs | How it's assigned |
| Validation | Any workflow action (Record Update) | Assigned to Stage Objects |
| Checklist | User clicks info icon on Record Update actions | Assigned to Stage Objects |
| Visit Action Validation | User clicks Sign or Submit on a visit | Runs automatically (only one script runs — first by ID/creation date) |
Critical: Only One Visit Action Validation Runs
Only one Visit Action Validation script runs per org. If multiple scripts of this type exist, only the first one executes (based on ID or creation date). All validation rules must be combined in a single script returning multiple results in the array.
For Validation and Checklist scripts, different scripts can be assigned to different Stage Objects.
Required Record Fields for LifeScienceCustomScript
| Field | Validation/Checklist | Visit Action Validation |
| Name | Required | Required |
| ComponentName | LWC component name | LWC component name |
| Type | Validation or Checklist | VisitActionValidation |
| ObjectName | Not required | ProviderVisit (required!) |
| OperationEventType | Not required | OnUpdate (required!) |
Without ObjectName and OperationEventType, Visit Action Validation scripts silently don't execute.
How Custom Scripts Work
Custom scripts are headless LWC components deployed to the org. The platform stores the JavaScript in the CodeText field of LifeScienceCustomScript records and executes it from there — not from the deployed LWC directly.
After deploying an updated LWC, the user must click Refresh in Admin Console > Workflow Configuration > Custom Scripts to sync the code to the CodeText field.
CodeTextis the runtime source of truthCodeTextis read-only via API — it can only be updated through the Refresh button
Two Runtimes: Web vs. iPad (Locker Service vs. JavaScriptCore)
The same CodeText script runs in two completely different JavaScript engines depending on platform:
| Web (Lightning) | iPad (LSC Mobile) | |
| Engine | Browser + Locker Service (WKWebView-style sandbox) | Native JavaScriptCore (JSContext) — no Locker Service |
Globals (record, user, db, env) | Locker Service secure proxies | Native Swift objects bridged via JSExport |
| Return values | Wrapped in Locker Service Proxy objects | Bridged native objects (not Locker proxies) |
Where env.log() / console.log goes | Browser devtools console | Device logs (Console.app / Xcode device console) — NOT a browser console |
Why this matters:
- The
unwrapProxy(results)requirement (gotcha #2) exists to strip Locker Service proxies on web. On iPad there is no Locker Service, butJSON.parse(JSON.stringify(results))is still the correct way to return plain data across the JavaScriptCore bridge — keep it for both platforms. - When debugging, look in the browser console on web and in device logs on iPad. A script that "works on web but not on iPad" usually differs because of the engine/bridge, not the logic — check the runtime before rewriting the validation.
Confirmed Working IIFE Pattern (Visit Action Validation)
All Visit Action Validation scripts must follow this pattern. Do not deviate.
(() => {
function parseContextData(record) {
try {
if (!record || typeof record.getContextData !== 'function') return {};
var contextData = record.getContextData();
if (typeof contextData === 'string') return JSON.parse(contextData);
if (typeof contextData === 'object' && contextData !== null) return contextData;
return {};
} catch (e) { return {}; }
}
function getFieldData(contextData, baseFieldName) {
return contextData[baseFieldName + '.VisitId'] || contextData[baseFieldName];
}
function unwrapProxy(results) {
return JSON.parse(JSON.stringify(results));
}
async function myValidation(contextData) {
try {
// Validation logic here
// Return { title: "message", status: "success" | "warning" | "error" }
} catch (e) {
return { title: 'Validation error: ' + e.message, status: 'error' };
}
}
async function validateVisit() {
try {
var contextData = parseContextData(record);
var hasWebField = contextData['ProviderVisit'] !== undefined;
var result = await myValidation(contextData);
var results = [result];
if (hasWebField) { var resolved = await Promise.all(results); return unwrapProxy(resolved); }
return unwrapProxy(results);
} catch (error) {
return [{ title: 'Validation error: ' + error.message, status: 'error' }];
}
}
if (record && user && env && db) {
var contextData = parseContextData(record);
var hasWebField = contextData['ProviderVisit'] !== undefined;
if (hasWebField) return [validateVisit()];
else return validateVisit();
}
})();Validation Script Pattern (for Workflow)
Workflow Validation and Checklist scripts use a simpler pattern — no platform detection needed:
(() => {
async function validateSomething() {
try {
// Validation logic using record, db, env globals
return { title: "Validation passed", status: "success" };
} catch (error) {
return { title: "Error: " + error.message, status: "error" };
}
}
return [validateSomething()];
})();Context Data Structure (Visit Action Validation)
record.getContextData() returns a JSON object with the visit and all related child records.
Top-Level Keys (Web)
On web, child records are keyed by ObjectName.VisitId. On mobile, they use just the object name.
{
"ProviderVisit": { ... }, // The visit record
"PresentationForum.ForumReferenceId": [ ... ], // CLM presentations
"ProviderVisitProdDetailing.VisitId": [ ... ], // Detailed products
"ProductDisbursement.VisitId": [ ... ], // Samples left
"ProviderVisitRqstSample.VisitId": [ ... ], // Sample requests
"ProviderVisitMarketingItem.VisitId": [ ... ], // Marketing items
"Visit.ParentVisitId": [ ... ], // Attendee child visits
"version": "...", // Data version
"sObjectType": "..." // Object type
}Data Available Without db.query (Sync)
These objects are in the context payload and can be read directly:
ProviderVisit— visit header fields (Id, AccountId, Channel, Status, Description, etc.)ProviderVisitProdDetailing.VisitId— detailed products (withAdditionalInformationJSON)ProductDisbursement.VisitId— samples (withAdditionalInformationJSON)ProviderVisitRqstSample.VisitId— sample requestsProviderVisitMarketingItem.VisitId— marketing itemsPresentationForum.ForumReferenceId— CLM presentationsVisit.ParentVisitId— attendee child visits
Nested (NOT top-level):
ProviderVisitDtlProductMsg— nested on eachProviderVisitProdDetailingrecord asdetailRecord['ProviderVisitDtlProductMsg.VisitId']ProviderVisitProdDiscussion— nested on each detail record similarly
Data Requiring db.query (Async)
These are NOT in the context and require await db.query(...):
Account(IsPersonAccount, Specialty, etc.)Product2(Brand, Name, custom fields)ProductItem(ExpirationDate, Product2Id)Profile(Name — query by name, not hardcoded ID)UserAdditionalInfo(ProfileIdentifier)ObjectTerritory2Association/UserTerritory2AssociationIndividualConsentor custom consent objects
AdditionalInformation JSON (on ProductDisbursement)
{
"Product2": { "Name": "Immunexis 10mg" },
"ProductionBatch": {
"Name": "IMX-BG6678",
"ExpirationDate": "2030-01-30T00:00:00.000Z"
}
}AdditionalInformation JSON (on ProviderVisitProdDetailing)
{
"LifeScienceMarketableProduct": { "Name": "Immunexis" },
"Indication": { "Name": null },
"Brand": { "Name": null },
"TherapeuticArea": { "Name": null }
}Field Name Casing (Web vs Mobile)
Web and mobile may use different casing:
| Web | Mobile |
ProductItemId | productitemid |
AccountId | accountid |
QuantityDisbursed | quantitydisbursed |
Channel | channel |
Always check both: record.ProductItemId || record.productitemid
Accessing Custom Fields from db.query Results
stringValue() does NOT work for custom fields (__c) on either platform. Standard fields and custom fields require different access methods:
| Method | Standard Fields | Custom Fields (Web) | Custom Fields (iPad) |
stringValue('Field') | Works | Does NOT work | Does NOT work |
.sObject.Field__c | Works | Works | No sObject on mobile |
noNs_stringValue('Field__c') | Works | Not needed | Works |
Cross-platform helper (always use this for custom fields):
function getCustomField(queryResult, fieldName) {
if (!queryResult) return null;
// Web: use sObject property
if (queryResult.sObject && queryResult.sObject[fieldName] !== undefined) {
return queryResult.sObject[fieldName];
}
// iPad: use noNs_stringValue
if (typeof queryResult.noNs_stringValue === 'function') {
var val = queryResult.noNs_stringValue(fieldName);
if (val !== undefined) return val;
}
return null;
}Important details:
- Custom fields with null values are silently dropped from
sObjecton web — they returnundefined, notnull - On iPad, custom fields must be in the DB Schema (mobile metadata cache). If a field isn't in the cache, it won't sync to the device. Regenerate cache and re-login after adding fields.
- The
db.queryresult object is completely different between platforms:- Web: has
sObject,accessibleFields,sObjectName,namespaceUtilsproperties - iPad: opaque object with only methods:
enableAccessErrors,stringValue,numValue,boolValue,dateValue,setValue,noNs_stringValue,noNs_numValue,noNs_boolValue,noNs_dateValue,noNs_setValue,recordTypeName,save
- Web: has
Getting AccountId on Mobile
On web, AccountId is available in contextData.ProviderVisit.AccountId. On mobile, ProviderVisit doesn't exist in the context. Use the record global as a fallback:
var visit = contextData.ProviderVisit || {};
var accountId = visit.AccountId || visit.accountid;
if (!accountId) {
try { accountId = record.stringValue('AccountId'); } catch (e) {}
}Available Globals
| Global | Description | Key Methods |
record | Current record | stringValue(field), boolValue(field), getContextData() |
user | Current user | stringValue(field) |
db | Database access | query(entity, conditions, fields) |
env | Environment | getOption(key), log(message) |
Available Classes
Injected globals (confirmed against businessRuleValidator/objectInitialization.js):
ConditionBuilder, ConditionBuilder_noNs, ConditionEnhancedBuilder, ConditionEnhancedBuilder_noNs, Query, SetCondition, SetCondition_noNs, FieldCondition, FieldCondition_noNs, DateFieldCondition, DateFieldCondition_noNs, DateTimeFieldCondition, DateTimeFieldCondition_noNs, AndCondition, OrCondition, enableAccessErrors
- Every builder/condition class has a
_noNsvariant for accessing custom (__c) fields without the managed-package namespace prefix — use the_noNsform when working with custom fields (mirrors thenoNs_stringValuepattern fordb.queryresults). Queryis the query builder;enableAccessErrorssurfaces field-access errors instead of silently returning null.GroupConditionis NOT injected — it is an internal base class, not available to scripts. Do not reference it.
Output Format
{ title: string, status: string } // "success", "warning", or "error"| Status | Checklist | Validation |
success | Green check | Not displayed |
warning | Yellow alert | Shows warning dialog, user can continue |
error | Red X | Blocks action, shows error dialog |
Critical Gotchas
When helping users write or debug custom scripts, always warn about these:
- No comment blocks before the IIFE. JSDoc or multi-line comment blocks (
/** ... */) before(() => {cause Locker Service to silently fail — the platform shows a generic error with zero console output. Put comments inside the IIFE only. - Proxy wrapping breaks results. On web, return values get wrapped in Locker Service Proxy objects and
translateValidationResultscannot read them. Always callunwrapProxy(results)(JSON.parse(JSON.stringify(results))) before returning. Without this, the platform silently allows the visit through. (iPad runs in native JavaScriptCore with no Locker Service — butunwrapProxyis still required to return plain data across the bridge. See "Two Runtimes" above.) - Large scripts crash silently. If a script is too large, Locker Service fails to evaluate it. Keep scripts small and focused.
- CodeText is the runtime source. The platform executes from
CodeText, not the deployed LWC. Always click Refresh after deploying. - ObjectName and OperationEventType required. Without
ObjectName = 'ProviderVisit'andOperationEventType = 'OnUpdate'on the LifeScienceCustomScript record, Visit Action Validation scripts silently don't execute. Visit Action Validation has no removal event.OnDeleteis not a hook for removing an attendee. Do not tell a user to add anOnDeleteVisit Action Validation script to block that removal. - Only one Visit Action Validation runs. First by ID/creation date. Combine all rules in one script.
- Product messages are nested.
ProviderVisitDtlProductMsgis NOT a top-level context key. Access viadetailRecord['ProviderVisitDtlProductMsg.VisitId']. - Use
env.log()for debugging. Addenv.log('scriptName - message')calls to trace execution. Output goes to the browser console on web and to device logs on iPad (JavaScriptCore has no browser console). This is the only way to debug custom scripts. - Guard globals. Always wrap execution in
if (record && user && env && db). - Sharing defaults to Private. Rep users need record-level access to
LifeScienceCustomScriptrecords. Change OWD to Public Read Only if reps can't see scripts. - Query Profile by name, not ID. Profile IDs differ between orgs. Query
ProfilewhereName = 'Field Sales Representative'and use the returned ID. - The quantity field is
QuantityDisbursed, notQuantity. On mobile, field names may be lowercase. - Custom fields (
__c) require special access.stringValue()does NOT work for custom fields on either platform. On web, use.sObject.Field__c. On iPad, usenoNs_stringValue('Field__c'). Always use thegetCustomField()helper for cross-platform code. See the "Accessing Custom Fields" section above. - Null custom fields are silently dropped on web.
db.queryomits custom fields with null values from thesObject— accessing them returnsundefined, which looks identical to "field not supported". Always test with non-null values. - iPad custom fields require DB Schema configuration. Custom fields must be in the mobile metadata cache (Admin Console > Mobile > Object Metadata Cache Configuration). Regenerate cache and re-login after adding fields. Without this,
noNs_stringValuereturnsundefined. - Mobile
db.queryresults have nosObjectproperty. The result object on iPad is completely opaque — no enumerable properties,JSON.stringifyreturns{}. Use the method-based API (noNs_stringValue,numValue,boolValue, etc.) instead. - AccountId not in contextData on mobile. On web,
contextData.ProviderVisit.AccountIdworks. On mobile,ProviderVisitdoesn't exist in the context. Fall back torecord.stringValue('AccountId').
Configuration Mode
When the user asks about configuring custom scripts, ask them which mode they prefer:
- Show me the documentation — call
search_lsc_knowledge({ query: "custom scripts" })and present the relevant sections - Walk me through it — configure it directly in their org step-by-step (guided setup below)
Default to guided setup when connected to an org, or documentation mode if no org is connected.
Guided Setup Workflow
Step 1: Check Current State
run_soql({ query: "SELECT Id, Name, ComponentName, Type, ObjectName, OperationEventType, CreatedDate FROM LifeScienceCustomScript ORDER BY Type, CreatedDate" })Report:
- How many scripts exist, by type
- For Visit Action Validation: which one will actually run (first by CreatedDate)
- Whether ObjectName and OperationEventType are set correctly
Step 2: Check for Multiple Visit Action Validation Scripts
If more than one Visit Action Validation script exists, warn immediately — only the first one (by ID/creation date) runs. The others are silently ignored.
Step 3: Verify Required Fields
For each Visit Action Validation script, verify:
ObjectName=ProviderVisitOperationEventType=OnUpdate
If either is missing, the script will silently not execute.
Step 4: Check Sharing Settings
run_soql({ query: "SELECT Id, Name FROM LifeScienceCustomScript LIMIT 1" })Remind user that LifeScienceCustomScript defaults to Private sharing. If field reps can't see validation results, OWD needs to be changed to Public Read Only.
Step 5: Remind About Refresh
After any LWC deployment, the user must click Refresh in Admin Console > Workflow Configuration > Custom Scripts to sync code to CodeText.
Step 6: Help Write or Debug Scripts
If the user wants to create a new validation script:
- Ask what they want to validate
- Help decide sync vs async (does the data need
db.query?) - Generate the script using the confirmed IIFE pattern above
- Include
env.log()calls for debugging - Remind them about all gotchas (no JSDoc before IIFE, unwrapProxy, etc.)
Tool Usage Rules
Correct Object Names
| Correct | Wrong (NEVER use) |
LifeScienceCustomScript | CustomScript__c, LifeSciCustomScript |
ProviderVisit | ProviderVisit__c, Visit__c |
ProviderVisitProdDetailing | ProviderVisitProductDetailing__c |
ProductDisbursement | SampleDrop__c |
ProductItem | InventoryItem__c |
Product2 | SampleProduct__c |
Profile | (query by Name, not hardcoded ID) |
Tool Restrictions
- DO NOT use
run_soqlfor Admin Console settings — uselist_admin_settings - DO NOT use
run_soqlfor mobile cache — usecheck_mobile_cache_status() - DO NOT suggest OmniStudio/FlexCard/OmniScript for mobile — NOT available on LSC Mobile iPad app
- DO NOT suggest updating
CodeTextvia API — it is read-only and can only be synced via the Refresh button
Example Scripts Repository
Reference examples are available at https://github.com/lsc-ideas/lsc-custom-scripts-examples. Point users here for working code examples covering common pharma validation patterns.
Admin Console Navigation
| Task | Path |
| Custom Scripts | Admin Console > Workflow Configuration > Custom Scripts |
| Refresh CodeText | Admin Console > Workflow Configuration > Custom Scripts > Refresh (per row) |
| Stage Objects (assign scripts) | Admin Console > Workflow Configuration > Stage Objects > Edit |
| Workflow Paths | Admin Console > Workflow Configuration > Workflow Paths |
| Sharing Settings | Setup > Sharing Settings > LifeScienceCustomScript |
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

