English
English
English
English
Some of what SalesDash needs lives in a spreadsheet that someone edits by hand: commission rates per agent, the products of the month, next quarter's goals, the bonuses a manager hands out. You don't have to copy those into the admin. An Apps Script attached to the sheet can send it to SalesDash every time someone edits it.
Every script of this kind has the same shape: read the sheet, turn it into the request body SalesDash expects, send it, and say loudly when that failed. Only the middle step depends on what the sheet sets.
| The sheet holds | It sets | Endpoint | Key |
|---|---|---|---|
| A list a processor reads while it handles data: rates, product codes, date ranges | A processor constant | PUT /source-processors/{id}/constants/{name} | A REST API key |
| Targets per team or per agent | A goal | POST /goal or POST /agent-goal | A REST API key |
| Things that happened, one per row: a bonus, a manually reported deal | An activity | The Activity webhook of a webhooks provider | That provider's API key |
Pick a constant when the sheet describes how to value data that arrives from somewhere else. A commission sheet is the typical example: a rate per agent and proposition, which the processor applies to each sale as it comes in. Pick activities when every row is something to count.
A REST API key comes from Organization > API keys (see Getting a key). The webhooks provider shows its own key and its Activity webhook URL in the admin.
Open the sheet, choose Extensions > Apps Script, and start from this skeleton. Only buildRequests changes between the three cases below.
const SPREADSHEET_ID = '…' // from the sheet's URL: /spreadsheets/d/{this part}/edit
const SHEET_NAME = 'Sheet1'
const HANDLER_NAME = 'syncToSalesDash'
function syncToSalesDash() {
// Two quick edits start two runs. The lock makes the second wait for the first,
// so they cannot finish in the wrong order.
const lock = LockService.getScriptLock()
lock.waitLock(30000)
try {
const rows = SpreadsheetApp.openById(SPREADSHEET_ID)
.getSheetByName(SHEET_NAME)
.getDataRange()
.getValues()
const requests = buildRequests(rows)
const failures = []
UrlFetchApp.fetchAll(requests).forEach((response, i) => {
console.log(requests[i].url, response.getResponseCode(), response.getContentText())
if (response.getResponseCode() >= 300) {
failures.push(requests[i].url + ' → ' + response.getResponseCode())
}
})
if (failures.length > 0) {
throw new Error('SalesDash refused ' + failures.length + ' request(s): ' + failures.join(', '))
}
} finally {
lock.releaseLock()
}
}
function request(url, method, body) {
return {
url: url,
method: method,
contentType: 'application/json',
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + PropertiesService.getScriptProperties().getProperty('API_KEY'),
},
payload: JSON.stringify(body),
muteHttpExceptions: true,
}
}
function formatDate(date) {
return Utilities.formatDate(date, 'Europe/Amsterdam', 'yyyy-MM-dd')
}
function installTrigger() {
ScriptApp.getProjectTriggers()
.filter(trigger => trigger.getHandlerFunction() === HANDLER_NAME)
.forEach(trigger => ScriptApp.deleteTrigger(trigger))
ScriptApp.newTrigger(HANDLER_NAME)
.forSpreadsheet(SPREADSHEET_ID)
.onEdit()
.create()
}Then, once:
API_KEY with the key from the table above. Keep it out of the code: anyone who can see the script can see the code.syncToSalesDash by hand from the editor and approve the permissions it asks for. The log shows each request and its response, and a 200 or 201 means SalesDash stored it.installTrigger. From now on every edit sends the sheet.When a push fails, the run shows as failed under Executions in the Apps Script editor, and Google emails the script's owner about it.
The sheet becomes one value, sent whole every time. The value is replaced, not merged, so a removed row really disappears.
const CONSTANT_URL = 'https://yourcompany.salesdash-app.com/integrations/api/v1/source-processors/12/constants/commission_rates'
// Row 1 holds agent ids from column B on. From row 2, column A is a proposition
// and each agent column holds that agent's rate for it.
function buildRequests(rows) {
const agentIds = rows[0]
const value = []
for (let col = 1; col < agentIds.length; col++) {
if (String(agentIds[col]).trim() === '') continue
const rates = []
for (let row = 1; row < rows.length; row++) {
const proposition = String(rows[row][0]).trim()
const amount = rows[row][col]
if (proposition && amount !== '' && isFinite(Number(amount))) {
rates.push({ proposition: proposition, amount: Number(amount) })
}
}
value.push({ agent_id: String(agentIds[col]).trim(), rates: rates })
}
return [request(CONSTANT_URL, 'put', { value: value })]
}The edit modal of the source shows the exact URL under each constant. One processor fed by two sources has two links, each with its own value. Return one request per link to keep both up to date.
Shape the value the way the processor's spec reads it. The spec loops over the list and compares fields, so the field names here (agent_id, rates, proposition, amount) are whatever the spec expects. Agree on them before you write either side.
Each row is one team's target. Rows with the same goal name become one goal with several teams.
const GOAL_URL = 'https://yourcompany.salesdash-app.com/integrations/api/v1/goal'
// Columns: goal name, metric id, from, to, team id, value.
function buildRequests(rows) {
const goals = {}
rows.slice(1)
.filter(row => row[0] && row[2] instanceof Date && row[3] instanceof Date)
.forEach(row => {
const name = String(row[0]).trim()
goals[name] = goals[name] || {
name: name,
metric_id: Number(row[1]),
active_from: formatDate(row[2]),
active_to: formatDate(row[3]),
team_goals: [],
}
goals[name].team_goals.push({ team_id: Number(row[4]), value: Number(row[5]) })
})
return Object.values(goals).map(goal => request(GOAL_URL, 'post', goal))
}The goal name is what SalesDash matches on, so renaming a goal in the sheet creates a new goal and leaves the old one where it was. Read Get the unit right first before the first push: a team currency goal is in euros, a personal one in cents.
For personal goals, send one POST /agent-goal per row with agent_id, metric_id, value and one period (week, month, quarter or year).
Each row is one activity. The Activity webhook takes one activity per request, and fetchAll sends them side by side.
const ACTIVITY_URL = '…' // the Activity webhook URL shown on your webhooks provider
// Columns: reference, agent id, agent name, date, amount.
function buildRequests(rows) {
return rows.slice(1)
.filter(row => row[0] && row[1] && row[3] instanceof Date)
.map(row => request(ACTIVITY_URL, 'post', {
id: 'bonus | ' + String(row[0]).trim(),
type: 'Bonus',
agent_id: String(row[1]).trim(),
agent_name: String(row[2]).trim(),
moment: formatDate(row[3]),
value: Number(row[4]),
}))
}Give every row an id that stays with it: a reference typed in the sheet, never the row number. Sorting the sheet or inserting a row moves row numbers, and the next push then rewrites the wrong activities.
Removing a row does not remove its activity. The next push simply doesn't mention it. Either keep the row and change its type, for example to Bonus - withdrawn, so a metric counting Bonus stops counting it, or send that id to the provider's Activity delete webhook.
A sheet with hundreds of rows sends hundreds of requests on every edit. For a sheet that only grows, send just the edited rows: the trigger passes the edit to your function as e, and e.range.getRow() and e.range.getNumRows() tell you which rows changed. Keep a version that sends everything for running by hand.
onEdit runs on every edit too, but it is not allowed to call other services, so its request never leaves the sheet. installTrigger creates the right kind.IMPORTRANGE or another script fires no edit trigger. If the sheet is filled that way, add a time-driven trigger as well, for example ScriptApp.newTrigger(HANDLER_NAME).timeBased().everyHours(1).create().toISOString(). A date cell arrives as a Date at midnight in the sheet's timezone, and toISOString() converts it to UTC first, which in Amsterdam is the evening before. formatDate in the skeleton avoids that."12,50", which Number() reads as NaN. Skip what isn't a number rather than sending null, and trim every id and name you send.UrlFetchApp as it is. It is synchronous, so async and await add nothing, and an async callback inside forEach hides its errors from the run.