Skip to content

Instantly share code, notes, and snippets.

@nwaughachukwuma
Last active February 9, 2025 15:42
Show Gist options
  • Save nwaughachukwuma/4af423a60c955a7e19c4d857d8b8cacf to your computer and use it in GitHub Desktop.
Save nwaughachukwuma/4af423a60c955a7e19c4d857d8b8cacf to your computer and use it in GitHub Desktop.
/**
* This function is called from an onEdit trigger which passes a parameter to it
* The aim is to get the row where a change is made and update the cloud functions
* endpoint with it
*/
function updateCustomer(param) {
// cloud functions HTTP on request URL
var url = 'https://project_location-project_id.cloudfunctions.net/updateCustomer';
var oauthToken = ScriptApp.getOAuthToken(); // get the user's OAuth token
// get active spread sheet
var sheet = SpreadsheetApp.getActiveSheet();
// get the row and column where the change occured
const rowNum = parseInt(param.range.getRow());
const colNum = parseInt(param.range.getColumn());
var customerId = sheet.getRange(rowNum, 1).getValue(); // getthe cell value
var productId = sheet.getRange(rowNum, 2); // get the cell value
var orderId = sheet.getRange(rowNum, 3).getValue(); // get the cell value
var operation = param.value; // get the edited/change value on the column of interest
var systemMessage = '';
// perform some validations
const acceptableValue = ['pending', 'approved', 'declined'];
if (acceptableValue.indexOf(operation) < 0) {
systemMessage = 'wrong validation value type. Use one of pending|approved|declined'
Logger.log(systemMessage);
return;
}
const data = {
customerId,
productId,
orderId,
operation,
oauthToken, // 1. add the oauth token to the payload
activeUser: param.user // 2. this here is important as it adds the userinfo.email scope to the token
}
var options = {
'method' : 'post',
'contentType': 'application/json',
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)
};
// send the request and parse the response message.
try {
const response = UrlFetchApp.fetch(url, options);
Logger.log('Response Code: ' + response.getResponseCode());
if(response.getResponseCode() === 200) {
// alert admin of success
var message = response.getContentText();
systemMessage = JSON.parse(message).message;
Logger.log(systemMessage);
// you can even write the result to cell of your choice
return sheet.getRange(rowNum, 6).setValue(systemMessage).setFontColor('green');
}
throw new Error( response.getContentText() );
} catch (err) {
// return cell value to the old value
const rewriteResultCell = sheet.getRange(rowNum, colNum);
if (colNum === 11) {
rewriteResultCell.setValue(param.oldValue);
}
Logger.log('Response Error: ' + err);
const errorMessage = 'Cannot perform operation'
// you can write the error to cell of your choice
return sheet.getRange(rowNum, 6).setValue(errorMessage).setFontColor('red');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment