Chapter 7.1

SuiteScript Overview

Understand NetSuite's JavaScript-based scripting platform, API versions, script types, governance model, and when to use code vs. configuration for business requirements.

What is SuiteScript?

SuiteScript is NetSuite's JavaScript-based API that enables developers to extend and customize the platform beyond its native capabilities. It provides programmatic access to NetSuite data, business logic, and user interface components.

โ„น๏ธ SuiteScript Versions
  • SuiteScript 1.0: Legacy API, still supported but no longer enhanced
  • SuiteScript 2.0: Modern module-based API (recommended for all new development)
  • SuiteScript 2.1: ES2019+ JavaScript features (async/await, arrow functions)

All new scripts should use SuiteScript 2.1 unless specific compatibility requirements exist.

When to Use SuiteScript

Before writing code, evaluate whether your requirement can be met through configuration. SuiteScript should be used when native features are insufficient.

Requirement Configuration Option When SuiteScript Needed
Field validation Mandatory fields, validation rules Complex cross-field logic, external validation
Auto-populate fields Sourcing, default values, formulas Complex calculations, external lookups
Approval workflows SuiteFlow workflows Complex routing, external system integration
Scheduled tasks Saved search alerts, reminders Data processing, integration syncs
Custom UI Custom forms, custom records Custom pages, portlets, dynamic interfaces
Integrations Native connectors (if available) Custom APIs, bidirectional sync
๐ŸŽฏ The Configuration-First Principle

Always try configuration before coding. Native features are:

  • Maintained by NetSuite (automatic upgrades)
  • Better documented and supported
  • No governance consumption
  • Easier for administrators to maintain

Script Types Overview

Script Type Execution Context Primary Use Cases
Client Script Browser (user's machine) Field validation, UI behavior, real-time calculations
User Event Script Server (on record save/load) Data validation, auto-population, transformations
Scheduled Script Server (time-based) Batch processing, data cleanup, integrations
Map/Reduce Script Server (parallel processing) Large data sets, complex transformations
Suitelet Server (on-demand page) Custom UI pages, wizards, internal tools
Restlet Server (HTTP endpoint) REST APIs, external integrations

Governance Model

NetSuite uses a governance system to ensure fair resource allocation. Each script execution is allocated governance units, and API calls consume these units.

โš ๏ธ Governance Limits by Script Type
Script Type Governance Units
Client Script1,000 units
User Event Script1,000 units
Suitelet1,000 units
Restlet5,000 units
Scheduled Script10,000 units
Map/Reduce Script10,000 units per phase

Common API Governance Costs

Operation                               Units
--------------------------------------------------
record.load()                           10
record.save()                           20
record.delete()                         20
search.create().run()                   10
search.lookupFields()                   1
email.send()                            20
http.request()                          10
file.load()                             10

Script Deployment

Every script requires two components: the Script record and the Script Deployment record.

Customization โ€บ Scripting โ€บ Scripts โ€บ New
1

Upload Script File

Upload .js file to File Cabinet (SuiteScripts folder recommended)

2

Create Script Record

Select script file, configure script parameters if needed

3

Create Deployment

Link script to record types/contexts, set execution roles

4

Set Status to Released

Change deployment status from Testing to Released for production

SuiteScript Readiness Checklist

Chapter 7.2

User Event Scripts

Master server-side scripts that execute on record load, before save, and after saveโ€”the workhorses of NetSuite automation.

What Are User Event Scripts?

User Event scripts run on the server whenever a record is loaded, created, edited, or deleted. They execute automatically with record operationsโ€”no user action required.

โ„น๏ธ User Event Entry Points
  • beforeLoad: Runs before record is displayed (view/edit modes)
  • beforeSubmit: Runs before record is saved to database
  • afterSubmit: Runs after record is saved to database

Entry Point Details

beforeLoad

Executes before the record form is displayed. Use for UI modifications.

Use Case Example
Add custom buttonsAdd "Generate PDF" button to sales order
Hide/show fieldsHide discount field for non-managers
Set field defaultsDefault ship date to tomorrow
Add sublist columnsAdd calculated column to item sublist

beforeSubmit

Executes before the record is written to the database. Perfect for validation and data transformation.

Use Case Example
Data validationEnsure margin meets minimum threshold
Data transformationUppercase customer name
Auto-populate fieldsSet approval status based on amount
Block savesPrevent duplicate PO numbers

afterSubmit

Executes after the record is saved. Use for operations that require the saved record ID.

Use Case Example
Create related recordsCreate task when opportunity closes
Send notificationsEmail customer when order ships
Update other recordsUpdate customer status based on orders
External integrationsPush data to external CRM
โš ๏ธ Common User Event Mistakes
  • Infinite loops: afterSubmit that edits the same record triggers another afterSubmit
  • Blocking on external APIs: Slow beforeSubmit makes saves timeout
  • Not handling null: Fields may be empty; always check before operations
  • Ignoring oldRecord: Always compare to detect actual changes
๐ŸŽฏ User Event Script Best Practices
  • Always check context.type: Don't run validation on DELETE
  • Handle errors gracefully: Use try/catch and log errors
  • Minimize governance: Avoid record.load() when context.newRecord suffices
  • Use afterSubmit for external calls: Don't block saves with slow API calls

User Event Script Checklist

Chapter 7.3

Client Scripts

Browser-side scripts that enhance user experience with real-time validation, field manipulation, and dynamic form behavior.

Client Script Overview

Client Scripts execute in the user's browser when interacting with NetSuite forms. They provide immediate feedback, enforce business rules before submission, and create dynamic user experiences.

Client Script Entry Points

Entry Point Trigger Common Uses
pageInit Form loads in browser Initialize field values, hide/show fields
fieldChanged User changes field value Dynamic sourcing, conditional logic
postSourcing After sourcing completes Override sourced values
sublistChanged Line added/removed/changed Sublist totals, line validation
validateField Before field value commits Field-level validation
saveRecord Before form submits Final validation, confirmation dialogs
โš–๏ธ Key Decision

Client Script vs. User Event

โš ๏ธ Client Script Limitations
  • Only run in browser (not CSV import, web services, scripts)
  • Can be bypassed by disabling JavaScript
  • Governance limits apply (1,000 units)
  • Cannot access server resources directly (use N/https for API calls)
๐Ÿ‘” Professional Services
Professional Services Consideration
Client scripts are excellent for retail POS-style order entry. Implement real-time inventory checks, dynamic pricing calculations, and promotional discount validation to create a fast, responsive order entry experience.

Client Script Checklist

Chapter 7.4

Scheduled Scripts

Time-based server scripts for batch processing, data maintenance, and scheduled integrations.

Scheduled Script Overview

Scheduled Scripts run on a defined schedule (daily, hourly, or specific times) to perform background processing without user interaction. They're ideal for batch operations, data cleanup, and scheduled integrations.

Customization โ€บ Scripting โ€บ Scripts โ€บ [Script] โ€บ Deployments โ€บ Schedule

Common Use Cases

Use Case Schedule Description
Invoice Generation Daily, early morning Create invoices from fulfilled orders
Data Cleanup Weekly, off-hours Archive old records, clean temp data
Integration Sync Every 15-30 minutes Pull/push data from external systems
Report Generation Daily/Weekly Generate and email reports
Reminder Emails Daily Send overdue invoice reminders
๐Ÿ’ก Scheduled Script Best Practices
  • Monitor governance: Check remaining units and reschedule if needed
  • Use script parameters: Allow configuration without code changes
  • Log progress: Track processed records for debugging
  • Handle restarts: Design for resumable processing
  • Test timing: Verify schedule works across time zones
๐Ÿ‘” Professional Services
Professional Services Consideration
Manufacturing companies use scheduled scripts for nightly MRP runs, calculating reorder points, generating work orders from demand, and updating standard costs. Schedule these during off-hours to avoid impacting users.

Scheduled Script Checklist

Chapter 7.5

Map/Reduce Scripts

Parallel processing scripts for high-volume data operations with automatic governance management.

Map/Reduce Overview

Map/Reduce scripts process large data sets by breaking work into parallel stages. They automatically manage governance, handle failures, and scale across NetSuite's infrastructure.

The Four Stages

Stage Purpose Concurrency
getInputData Define data to process (search, query, array) Single execution
map Transform each input into key-value pairs Parallel (up to 50)
reduce Process grouped values by key Parallel (up to 50)
summarize Handle results, errors, generate summary Single execution
โš–๏ธ Key Decision

Scheduled vs. Map/Reduce

โ„น๏ธ Map/Reduce Benefits
  • Automatic parallelization: NetSuite manages concurrent execution
  • Governance reset: Each map/reduce invocation gets fresh governance
  • Error isolation: One failed record doesn't stop the entire job
  • Built-in reporting: Summary stage provides execution statistics

Map/Reduce Script Checklist

Chapter 7.6

Suitelets & Restlets

Build custom UI pages with Suitelets and RESTful APIs with Restlets for internal tools and external integrations.

Suitelet Overview

Suitelets are server-side scripts that generate custom UI pages. They can display forms, process user input, and perform any NetSuite operation.

Common Suitelet Use Cases

  • Custom data entry wizards
  • Bulk update tools
  • Reporting dashboards
  • Integration configuration pages
  • Customer portals (with "Available Without Login")

Restlet Overview

Restlets provide RESTful API endpoints for external integrations. They handle HTTP GET, POST, PUT, and DELETE requests.

Restlet Authentication

Method Use Case Security
Token-Based Auth (TBA) Production integrations OAuth 1.0 signature (recommended)
OAuth 2.0 Modern integrations Bearer token
NLAuth Legacy/testing only Not recommended for production
๐Ÿ‘” Professional Services
Professional Services Consideration
Customer Portal: Suitelets for self-service license management, usage dashboards, and support ticket submission. Restlets for product activation and usage reporting APIs.
๐Ÿ‘” Professional Services
Professional Services Consideration
B2B Portal: Suitelet-based order entry forms for customers. Restlet APIs for real-time inventory checks and order status from partner systems.

Suitelet/Restlet Checklist

Chapter 7.7

Workflow Automation

Design and implement business process automation using SuiteFlow workflows without coding.

Workflow Fundamentals

SuiteFlow is NetSuite's visual workflow builder that automates business processes without coding. Workflows consist of states, transitions, and actions that execute based on triggers and conditions.

Workflows vs SuiteScript

Criteria Workflows (SuiteFlow) SuiteScript
Complexity Simple to moderate logic Complex, conditional logic
Maintenance Business users can modify Developers required
Debugging Workflow history visible Script logs and debugger
Performance Lightweight, efficient Full API access, more overhead
Best For Approvals, notifications, field updates Integrations, complex calculations
Customization โ€บ Workflow โ€บ Workflows โ€บ New

Workflow Components

Component Description Example
State A step in the workflow process Pending Approval, Manager Review, Approved
Transition Movement from one state to another Pending โ†’ Manager Review (on submit)
Action Work performed during a state Send email, set field, create record
Condition Logic that controls execution Amount > 1000 AND Department = Sales

Trigger Types

Trigger On When It Fires Common Use
Before Record Load Record opens in UI Set defaults, show/hide fields
Before Record Submit Before record saves Validation, calculated fields
After Record Submit After record saves Send emails, create related records
Scheduled On defined schedule Periodic updates, reminders
Entry When entering a state State-specific actions
โš ๏ธ Important Setting
"Keep Instance and Allow Re-initiate" โ€” Enable this for approval workflows to ensure the workflow continues when records are edited during the approval process. Without this, editing a record cancels the workflow.

Workflow Configuration Checklist

Chapter 7.8

SuiteFlow Advanced

Master advanced workflow patterns including multi-level approvals, conditional routing, and workflow actions.

Approval Workflow Pattern

Approvals are the most common workflow use case. The standard pattern includes states for Draft, Pending Approval, Manager Review, Approved, and Rejected.

Multi-Level Approval Configuration

Transition Trigger Condition
Draft โ†’ Pending Approval After Record Submit Status = Pending Approval
Pending โ†’ Manager Review After Record Submit Amount > $10,000
Pending โ†’ Approved After Record Submit Approved AND Amount โ‰ค $10,000
Manager Review โ†’ Approved After Record Submit Manager Approval = Approved
Any โ†’ Rejected After Record Submit Approval Status = Rejected

Workflow Actions

Field Actions

  • Set Field Value: Update any field on the record
  • Set Field Display Type: Make field hidden, disabled, or normal
  • Set Field Mandatory: Make field required or optional

Communication Actions

  • Send Email: Send email notifications with templates
  • Add Note: Create note on record

Record Actions

  • Create Record: Create new related record (task, event, custom)
  • Transform Record: Convert to another record type
  • Lock Record: Prevent editing of approved records

Advanced Actions

  • Custom Action: Execute SuiteScript for complex logic
  • Initiate Workflow: Trigger another workflow
  • Return User Error: Show error message for validation
๐Ÿ’ก Workflow Debugging

Use the Workflow History tab on records to see workflow execution details. Navigate to: Record > Workflow > View History. This shows states entered, actions executed, and any errors.

Advanced Workflow Checklist

Chapter 7.9

Formula Fields & Expressions

Leverage formulas in saved searches, workflows, and custom fields for calculations without SuiteScript.

Formula Overview

Formulas provide a code-free way to create calculated values in NetSuite. They use SQL-like syntax and can be used in saved searches, workflow conditions, and custom fields.

Formula Locations

Location Syntax Type Use Cases
Saved Search Formula(Text/Numeric/Date/Currency) Calculated columns, conditional formatting
Workflow Conditions Workflow formula syntax Transition conditions, action filters
Custom Fields Default value formulas Auto-calculated field values
Mass Update Formula expressions Calculated updates

Common Formula Functions

Text Functions

  • CONCAT(field1, ' ', field2) โ€” Combine text values
  • SUBSTR(field, start, length) โ€” Extract substring
  • UPPER(field) / LOWER(field) โ€” Change case
  • NVL(field, 'default') โ€” Handle null values

Numeric Functions

  • ROUND(value, decimals) โ€” Round to decimal places
  • ABS(value) โ€” Absolute value
  • NVL(field, 0) โ€” Replace null with zero

Date Functions

  • SYSDATE โ€” Current date
  • ADD_MONTHS(date, n) โ€” Add months to date
  • TRUNC(date) โ€” Remove time portion
  • date2 - date1 โ€” Days between dates

Conditional Logic

  • CASE WHEN condition THEN value1 ELSE value2 END
  • DECODE(field, match1, result1, match2, result2, default)
  • NVL2(field, if_not_null, if_null)
๐Ÿ’ก Formula Performance

Formulas are calculated at runtime. Complex formulas on large result sets can slow searches significantly. For performance-critical reports, consider pre-calculating values via scheduled scripts and storing in custom fields.

๐Ÿ‘” Professional Services
Professional Services Consideration
Use formulas to calculate project metrics: utilization rate = (billable hours / total hours) * 100, project margin = (revenue - cost) / revenue * 100. These can be displayed in dashboards without custom scripting.

Formula Implementation Checklist