SDK & Scripting Reference
Build powerful automations with GetCost's JavaScript scripting engine. Customize templates, automate workflows, and extend functionality.
Global Objects
Core ConceptThe SDK provides several global objects that are available in your scripts depending on the context.
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
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.
| Property | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Item name |
quantity | number | No | Simple quantity without units (e.g., 2 doors, 3 windows) |
price | number | No | Unit price |
description | string | No | Description |
unitQuantity | number | No | Quantity with unit conversion (use with unitCategory and unit) |
unitCategory | string | No | Unit category: length, area, volume, weight, time, money |
unit | string | No | Unit 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.
| Parameter | Type | Description |
|---|---|---|
identifier | number | string | A 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().
| Parameter | Type | Description |
|---|---|---|
start | number | Index to start removing from (supports negative values to count from end) |
deleteCount | number | Number 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 Property | Description |
|---|---|
id | Item ID |
documentId | Template document ID |
name | Template name |
description | Template 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).
| Value | Description |
|---|---|
"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) |
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
- Exact Name Match - Full text in client names
- Exact Field Match - Full text in email, phone, address
- Partial Name Match - Each word in names
- 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");
Items
Utility ObjectThe Items object provides methods for searching, retrieving, and managing products/items in your catalog.
Items.search(selector)
Search for products/items in your catalog by name.
Example
var item = Items.search("Lumber");
if (item) {
console.log(item.name + ': $' + item.price);
}
Items.where(criteria)
Find items matching criteria. Returns a list of item objects (at most 200, most recently
modified first). Templates are listed too: each result's type is
"item" or "template".
When more than 200 match, 200 are returned and the script output gets a warning saying more
exist - so 200 results is not the total. Read the next page with skip. When
deleting, query again without skip instead: deleted items drop out and the rest
move up.
| Criteria | Type | Description |
|---|---|---|
id | number | Find by item ID |
name | string | Find by name (partial match) |
tags | string | Find by tag (partial match) |
type | string | "item" for catalog items only (templates excluded), "template" for templates only |
skip | number | Number of items to skip, for the next page: 200, 400... |
Examples
// List items (up to 200)
var allItems = Items.where({});
console.log('Items listed: ' + allItems.length);
// Find items by name
var lumber = Items.where({name: 'Lumber'});
// Catalog items only, no templates
var catalogOnly = Items.where({type: 'item'});
// Count every item, page by page
var total = 0, page;
do {
page = Items.where({skip: total});
total += page.length;
} while (page.length === 200);
console.log('Total items: ' + total);
// Delete all catalog items, keeping templates. Deleted items drop out of the
// next query, so query again until none are left - past the 200 cap.
var items;
while ((items = Items.where({type: 'item'})).length > 0) {
for (var i = 0; i < items.length; i++) {
Items.delete(items[i].id);
}
}
Items.findWhere(criteria)
Find the first item matching criteria. Same options as where() but returns a single item or null.
Example
var item = Items.findWhere({name: 'Premium Lumber'});
if (item) {
console.log(item.name + ': $' + item.price);
}
Items.get(id)
Get an item from the global product catalog by ID. Returns the item with all properties including category information.
Example
var item = Items.get(12345);
if (item) {
console.log('Name: ' + item.name);
console.log('Price: $' + item.price);
console.log('Category ID: ' + item.categoryId);
console.log('Attribute Group ID: ' + item.attributeGroupId);
console.log('Category Path: ' + item.categoryPath.join(' > '));
}
Items.set(id, options)
Update an existing item in the global product catalog. Only the item owner can edit.
| Option | Type | Description |
|---|---|---|
name | string | Item name |
description | string | Item description |
price | number | Unit price |
unitCategory | string | Unit category |
unit | string | Unit code |
unitQuantity | number | Unit quantity |
accessRight | string | "user", "team", or "public" |
categoryId | number|null | Category ID. Set to null to clear. |
attributeGroupId | number|null | Attribute group ID within a category. Set to null to clear. |
Example
var item = Items.set(12345, {
price: 29.99,
categoryId: 100,
attributeGroupId: 200
});
console.log('Updated: ' + item.name);
Items.create(options)
Create a new item in the global product catalog.
Example
var item = Items.create({
name: 'Custom Material',
description: 'High quality material',
price: 15.00,
unitCategory: 'length',
unit: 'ft'
});
console.log('Created item ID: ' + item.id);
Items.delete(id)
Delete an item from the global product catalog. Only the owner can delete.
Example
var result = Items.delete(12345);
console.log('Deleted: ' + result.name);
Item Properties
All Items methods return an object with the following properties:
| Property | Type | Description |
|---|---|---|
id | number | Item/product ID |
documentId | number | Template ID (if from template) |
name | string | Item name |
description | string | Item description |
price | number | Item price |
unitcategory | string | Unit category |
unit | string | Unit code |
unitquantity | number | Unit quantity |
accessRight | number | Access level (0=user, 1=team, 2=public) |
categoryId | number|null | Category ID |
attributeGroupId | number|null | Attribute group ID within the category |
categoryPath | string[] | Array of category names from root to item's category |
ItemCategories.get() to retrieve full category details
including the complete path from root product. See ItemCategories API.
Units
Utility ObjectConvert values between different units of measurement.
Available Categories & Units
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.
| Option | Type | Description |
|---|---|---|
value | number | Value to convert |
from | string | Source unit |
to | string | Target unit |
category | string | Unit category |
decimals | number | Decimal places (optional) |
Example
var result = Units.format({
value: 42,
from: "ft",
to: "m",
category: "length",
decimals: 2
});
console.log(result); // "12.80"
console
Utility ObjectStandard 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 ObjectParse and stringify JSON data.
JSON.stringify(value, replacer, space)
Converts a JavaScript object to a JSON string.
| Parameter | Type | Description |
|---|---|---|
value | any | Value to convert |
replacer | function/array | Optional filter (usually null) |
space | number/string | Indentation (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