SDK & Scripting Reference

Build powerful automations with GetCost's JavaScript scripting engine. Customize templates, automate workflows, and extend functionality.

Global Objects

Core Concept

The SDK provides several global objects that are available in your scripts depending on the context.

Context Variables: The document, template, and client variables are available when the user is viewing or editing a document or template.

document

The active document object (estimate, invoice, job, or project):

Property Type Access Description
id number read Unique identifier
name string read/write Display name
typeId string read Document type (estimate, invoice, job, project)
clientId number read/write Associated client ID
items Collection read Child elements/items collection

template

The active template object (when editing a template):

Property Type Access Description
id number read Unique identifier
name string read/write Template name
accessRight string read/write Access level: "user", "team", or "public"
children Collection read Form elements collection

client

The client associated with the current document:

Property Type Access Description
id number read Unique identifier
name string read/write Client name
addressLine1 string read/write Street address line 1
addressLine2 string read/write Street address line 2
city string read/write City
state string read/write State/Province
zipCode string read/write ZIP/Postal code
country string read/write Country
tel1 string read/write Primary phone
tel2 string read/write Secondary phone
tel3 string read/write Tertiary phone

Document

Factory Object

The Document object provides methods for creating and querying documents (estimates, invoices, jobs, projects).

Document.create(type)

Creates a new document of the specified type.

ParameterTypeDescription
type string "estimate" or "invoice"

Example

// Name is auto-generated as an incrementing number
var doc = Document.create('estimate');
Navigate.to('estimate/' + doc.id);

Document.get(id)

Retrieves a document by its ID. When called with no arguments, returns the document from the current page.

ParameterTypeRequiredDescription
id number No The document ID. If omitted, returns the active document from the current page.

Example

// Get the active document (current page)
var doc = Document.get();

// Get a specific document by ID
var doc = Document.get(12345);
doc.items.push({ name: "New Item", price: 100 });
doc.save();

Document.where(criteria)

Finds all documents matching the specified criteria. Returns an array.

ParameterTypeDescription
criteria object Search criteria: {id, name, typeId}

Example

// Find all estimates
var estimates = Document.where({ typeId: 'estimate' });
console.log('Found ' + estimates.length + ' estimates');

// Find documents by name (partial match)
var docs = Document.where({ name: 'Kitchen' });

Document.findWhere(criteria)

Finds the first document matching the criteria. Returns a single document or null.

Example

// Find document by ID
var doc = Document.findWhere({ id: 12345 });
if (doc) {
  console.log('Found: ' + doc.name);
}

// Find by name
var doc = Document.findWhere({ name: 'My Project' });

document.save()

Saves changes to the document. Call this after modifying properties or adding items.

Example

document.name = "Updated Project Name";
document.items.push({
  name: "New Item",
  price: 100
});
document.save();

document.delete()

Permanently deletes the document.

Warning: This action cannot be undone. The document will be permanently removed.

Example

var doc = Document.findWhere({ name: 'Old Project' });
if (doc) {
  doc.delete();
}

Document.print(id)

Downloads the document as a PDF file. The PDF is generated and sent to the user's device.

ParameterTypeRequiredDescription
id number Yes The document ID to print

Example

// Download the current document as PDF
Document.print(document.id);

// Download a specific estimate as PDF
Document.print(12345);

document.items.push(item)

Adds a new item to the document.

PropertyTypeRequiredDescription
namestringYesItem name
quantitynumberNoSimple quantity without units (e.g., 2 doors, 3 windows)
pricenumberNoUnit price
descriptionstringNoDescription
unitQuantitynumberNoQuantity with unit conversion (use with unitCategory and unit)
unitCategorystringNoUnit category: length, area, volume, weight, time, money
unitstringNoUnit code (ft, m, ft2, m2, h, etc.)

Examples

// Load a document and add items
var doc = Document.get(12345);

// Simple item with quantity
doc.items.push({
  name: "Door Installation",
  quantity: 2,
  price: 150.00
});

// Item with unit conversion
doc.items.push({
  name: "Flooring",
  unitQuantity: 450,
  unitCategory: 'area',
  unit: 'ft2',
  price: 8.50
});

// Labor with time units
doc.items.push({
  name: "Labor",
  unitQuantity: 8,
  unitCategory: 'time',
  unit: 'h',
  price: 75.00
});

doc.save();

template.items.push(item)

Adds a new item to the current template. Use this within a template's onChange script.

Example (in template onChange script)

// Calculate hours based on form inputs
let hours = template.quantity.value * 2;

// Add labor item to the template
template.items.push({
  name: "Labor",
  unitQuantity: hours,
  unitCategory: 'time',
  unit: 'h',
  price: 75.00
});

template.items.remove(identifier)

Removes an item from the template by index or element ID.

ParameterTypeDescription
identifiernumber | stringA numeric index (0-based) or a string element ID

Example

// Remove the first item
template.items.remove(0);

// Remove by element ID
template.items.remove("12345");

template.items.splice(start, deleteCount)

Removes multiple items starting at the given index. Works like JavaScript's Array.splice().

ParameterTypeDescription
startnumberIndex to start removing from (supports negative values to count from end)
deleteCountnumberNumber of items to remove

Example

// Remove items at index 2 and 3
template.items.splice(2, 2);

// Remove the last item
template.items.splice(-1, 1);

template.items.clear()

Removes all items from the template. Useful when recalculating line items on each form change.

Example

// Clear all existing items before recalculating
template.items.clear();

// Add fresh items based on current form values
template.items.push({
  name: "Labor",
  quantity: template.hours.value,
  price: 75.00
});

Template

Factory Object

The Template object provides methods for creating and querying templates.

Template.create()

Creates a new empty template.

Example

var template = Template.create();
template.name = "My New Template";
template.save();
Navigate.to('template/' + template.id);

Template.where(criteria)

Finds all templates matching the criteria. Returns an array.

Example

var templates = Template.where({ name: 'Kitchen' });
console.log('Found ' + templates.length + ' templates');

Template.findWhere(criteria)

Finds the first template matching the criteria.

Example

var template = Template.findWhere({ id: 456 });
if (template) {
  console.log('Found: ' + template.name);
}

Template.search(selector)

Searches templates by name. Returns objects that can be added to documents.

Return PropertyDescription
idItem ID
documentIdTemplate document ID
nameTemplate name
descriptionTemplate description

Example

var results = Template.search("Kitchen");
if (results.length > 0) {
  // Add template to current document
  document.items.push(results[0]);
  document.save();
}

template.save() / template.delete()

Save changes or delete the template. Works the same as document methods.

Example

template.name = "Updated Template";
template.children.push({
  type: 'text',
  name: 'Customer Notes'
});
template.save();

template.accessRight

Controls who can see and use this template. Only applicable to templates (not documents like estimates or invoices).

ValueDescription
"user" Private - only you can see and use this template (same as "private")
"team" Team - all team members in your organization can see and use this template
"public" Public - visible to everyone (requires special permissions)
Note: The accessRight property is only available for templates. Documents (estimates, invoices) do not have access rights - they are always private to the owner.

Examples

// Check current access level
console.log(template.accessRight); // "user", "team", or "public"

// Share template with team
template.accessRight = "team";

// Make template private
template.accessRight = "user";
// or
template.accessRight = "private";

// Find and update a template's access right
var tpl = Template.findWhere({ name: "Kitchen Estimate" });
if (tpl) {
  tpl.accessRight = "team";
  console.log("Template shared with team");
}

Client

Factory Object

The Client object provides methods for creating and querying clients.

Client.create()

Creates a new client.

Example

var newClient = Client.create();
newClient.name = "John Smith";
newClient.tel1 = "555-123-4567";
newClient.addressLine1 = "123 Main St";
newClient.city = "Springfield";
newClient.state = "IL";
newClient.zipCode = "62701";

Client.where(criteria)

Finds all clients matching the criteria. Returns an array.

Example

var clients = Client.where({ city: 'Springfield' });
console.log('Found ' + clients.length + ' clients in Springfield');

Client.findWhere(criteria)

Finds the first client matching the criteria.

Example

var client = Client.findWhere({ id: 789 });
if (client) {
  console.log('Found: ' + client.name);
  console.log('Phone: ' + client.tel1);
}

Client.search(filter)

Searches clients using progressive matching across name, email, phone, and address.

Search Strategy

  1. Exact Name Match - Full text in client names
  2. Exact Field Match - Full text in email, phone, address
  3. Partial Name Match - Each word in names
  4. Partial Field Match - Each word in other fields

Examples

// Search by name
var clients = Client.search("John Smith");

// Search by phone
var clients = Client.search("555-1234");

// Search by city
var clients = Client.search("Springfield");

Units

Utility Object

Convert values between different units of measurement.

Available Categories & Units

length m, ft, in, cm, mm, yd
area m2, ft2, in2, yd2
volume l, gal, ml, fl oz
weight kg, lb, oz, g
time h, min, s

Units.fromTo(value, from, to, category)

Converts a value from one unit to another.

Example

// Convert meters to feet
var feet = Units.fromTo(1, 'm', 'ft', 'length');
console.log(feet); // 3.28084

// Convert square meters to square feet
var sqft = Units.fromTo(10, 'm2', 'ft2', 'area');
console.log(sqft); // 107.639

Units.format(options)

Converts and formats a value with decimal precision.

OptionTypeDescription
valuenumberValue to convert
fromstringSource unit
tostringTarget unit
categorystringUnit category
decimalsnumberDecimal places (optional)

Example

var result = Units.format({
  value: 42,
  from: "ft",
  to: "m",
  category: "length",
  decimals: 2
});
console.log(result); // "12.80"

console

Utility Object

Standard console object for logging and displaying messages from your scripts.

console.log(...args)

Outputs one or more values to the console output only.

Example

console.log("Hello World");
console.log("Value:", 42);
console.log("Client:", client.name, "ID:", client.id);

console.error(...args)

Logs an error message to the console and displays it on the form element with red styling. Use this to report critical issues that prevent proper calculation.

Example

if (items.length === 0) {
  console.error("No items found! Please add at least one item.");
}

if (squareFeet <= 0) {
  console.error("Invalid square footage: " + squareFeet);
}

console.warn(...args)

Logs a warning message to the console and displays it on the form element with yellow styling. Use this to report non-critical issues or unusual values.

Example

if (!client) {
  console.warn("No client selected - using default rates");
}

if (quantity > 1000) {
  console.warn("Large quantity detected: " + quantity + " units");
}

console.info(...args)

Logs an informational message to the console and displays it on the form element with blue styling. Use this to provide helpful information to the user.

Example

console.info("Using seasonal pricing rates");
console.info("Calculation based on " + rooms + " rooms");

JSON

Utility Object

Parse and stringify JSON data.

JSON.stringify(value, replacer, space)

Converts a JavaScript object to a JSON string.

ParameterTypeDescription
valueanyValue to convert
replacerfunction/arrayOptional filter (usually null)
spacenumber/stringIndentation (2 for pretty print)

Example

var data = { name: "Test", value: 42 };

// Compact
var json = JSON.stringify(data);
// '{"name":"Test","value":42}'

// Pretty printed
var pretty = JSON.stringify(data, null, 2);
// {
//   "name": "Test",
//   "value": 42
// }

JSON.parse(text)

Parses a JSON string into a JavaScript object.

Example

var json = '{"name":"Test","value":42}';
var obj = JSON.parse(json);

console.log(obj.name);  // "Test"
console.log(obj.value); // 42