How to sync google sheets database with google contacts - google-apps-script

I have a google sheets database with contacts
here is an example of my database
I need to sync this contacts to my googlee contacts with a google apps script
If there is a new contact to upload it
If there is an existing contact that changed any of his data information to update it in google contacts
Any help on this pelease ?
--
Update:
so far I got this script working
function myFunction() {
// Sheet Variables Below
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheet = ss.getSheetByName('xx')
var headerRows = 1;
var MaxRow = sheet.getLastRow();
var dataRange = sheet.getDataRange();
var data = dataRange.getValues(); // Read all data
data.splice(0, headerRows); // Remove header rows
function addContact() {
for (var i = 0; i < data.length; i++) {
var row = data[i];
var firstName = row[1];
var lastName = row[2];
var email = row[3];
var phone = row[4];
var group = row[5];
var atiende = row[6];
var address1 = row[7];
var address2 = row[8];
var address3 = row[9]
var notes = row[10];
var customfields = row[11];
var status = row[12];
var contactid = row[13];
var contact = ContactsApp.createContact(firstName, lastName, email);
contact.addPhone(ContactsApp.Field.MOBILE_PHONE, phone);
contact.addAddress(ContactsApp.Field.HOME_ADDRESS, address1);
contact.setNotes(address2 + ' ' + address3)
contact.addCompany(atiende)
var group = ContactsApp.getContactGroup("System Group: My Contacts");
group.addContact(contact);
}
}
addContact();
}
I have changed the data structure to this
this works in order to upload all the contacts to google contacts
But I need now to check if the contact exist by phone number, and if exists update it, if there is no changes to skip it, other way im having duplicates in google contacts
I believe its important to mention than this is a database generated automatically, is not something that I change the data manually

You could update contacts when you add a new row to yr ss using the event object
warning: I'm an amateur tho enthusiastic gscripter so be careful using any advice I give
function newContact(e) {
var sht = e.source.getActiveSheet();
var row = e.range.getRow();
var drng = sht.getRange(row, 2, 1, 6).getValues();
// drng is a single row 2D array
// adjust indexes to suit
var first = drng[0][0];
var surname = drng[0][1];
var phone = drng[0][2];
var email = drng[0][3];
var consentDate = drng[0][5];
var grp = 'group-name';
//create contact
var contact = ContactsApp.createContact(first, surname, email);
var contactID = contact.getId();
//add info via bug workaround ie getting the new contact via contactID
contact = ContactsApp.getContactById(contactID);
contact.addPhone('mobile', phone);
//update contact
var group = ContactsApp.getContactGroup(grp);
contact = contact.addToGroup(group);
}

Related

Google Apps Script : Get row number matching value

I'm need some assistance in my problem.
I'm currently working on a script that works like this :
Send form
Lookup the value in table
Get the row number to use in another function
I have searched for the solution but mostly use logger to display value, I need the value as local variable to be used in other function.
Here is my current code up until the point I try to get row number :
function autoFillGoogleDocFromForm(e) {
//e.values is an array of form values
var Timestamp = e.values[0];
var Nama = e.values[1];
var Prinsipal = e.values[2];
var Email = e.values[3];
var Site = e.values[4];
var Mobil = e.values[5];
var Jumlah = e.values[6];
var ETD = e.values[7];
var ETA = e.values[8];
var Keterangan = e.values[9];
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Master Email Site');
var data = sheet.getDataRange().getValues();
var RowCabang = Site
for(var i = 0; i<data.length;i++){
if(data[i][0] == Site){ //[0] because column A
return i+1;
}
}
var EmailCol = 2;
var EmailDest = sheet.getRange(RowCabang, EmailCol).getValue();
With this script, the trigger is completed but it doesnt capture the row number as var to be used.
Thank you for your assistance.
Try this pattern:
let RowCabang;
data.some((row, index) => {
if (row[0] === Site) {
RowCabang = index + 1;
return true;
}
});

update google contact with marked sheet using google app scripts

I'm trying to update my Google contacts from a sheet. I want to search column I of the sheet to check for 'pending'. If a row is pending, I want to take the values in column G, H, and E of that row and add it to that contact's Note.
Here's what I've got so far. Currently stuck on how to get the row of a contact marked 'pending'.
function test(){
var ss = SpreadsheetApp.getActiveSheet();
var data = ss.getDataRange().getValues(); // read all data in the sheet
for(n=9;n<data.length;++n){ // iterate row by row and examine data in column I
if(data[n][0].toString().match('pending')){
var row = ???
var name = ss.getRange(row, 1).getValue();
var contacts = ContactsApp.getContactsByName(name);
for (var i in contacts) {
var donate = ss.getRange(row, 7).getValue();
var pickup = ss.getRange(row, 8).getValue();
var item = ss.getRange(row, 5).getValue();
contacts[i].setNotes(donate + '\n\n' + item + '\n\n' + pickup + '\n\n');}
ss.getRange('9**row**').setValue('done');
}
}
}
This should do, haven't tested it though. Let me know if the code does not work.
function test()
{
var ss = SpreadsheetApp.openById(<SPREADSHEET_ID>).getSheetByName("Sheet1");
var lastRow = ss.getLastRow();
var data = ss.getRange("I1:I"+lastRow).getValues(); // read all data in the sheet
for(var n=0;n<data.length;n++)
{ // iterate row by row and examine data in column I
if(data[n] == 'pending')
{
//var row = ???
var name = ss.getRange("A"+n).getValue();
var contacts = ContactsApp.getContactsByName(name);
for (var i in contacts)
{
var donate = ss.getRange("G"+n).getValue();
var pickup = ss.getRange("H"+n).getValue();
var item = ss.getRange("E"+n).getValue();
contacts[i].setNotes(donate + '\n\n' + item + '\n\n' + pickup + '\n\n');}
ss.getRange('9**row**').setValue('done');
}
}
}
Instead of using var ss = SpreadsheetApp.getActiveSheet(); you should consider using var ss = SpreadsheetApp.openSheetById(<SPREADSHEET_ID>).getSheetByName(<SHEET_NAME>);

How to fix the issue mail merge issue

I am trying to create an approval flow using sheet mail merge with approval buttons in the mail . Mail could generate when the user submits the HTML form.
Below script is not working I have attached the script with sample sheet.
I am not able to identify the exact issue, please help me to fix or identify
Sample Sheet
var REQUESTS_STATE_COLUMN = 32;
var STATE_APPROVERS_EMAILED = "EMAILED_Response Pending";
var STATE_APPROVED = "Approved";
var STATE_DENIED = "Rejected";
function sendEmail(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("A2:AH2");
var data = dataRange.getValues();
for (i in data) {
var rowData = data[i];
var email = e.namedValues["Email Address"];
var emailAddress = rowData[30];
var submiterEmail = rowData[1];
var ProjectName = rowData[2];
var SrDesign = "Sr. Design Architect Services";
var PerHourRate = rowData[6];
var NumberOfHours = rowData[7];
var TotalRate = rowData[8];
var Contact = "Contact Centre Expert";
var PerHourRate2 = rowData[10];
var NumberOfHours2 = rowData[11];
var NTotalRate2 = rowData[12];
var NJrDesign = "Jr. Design Architect";
var PerHourRate3 = rowData[14];
var NumberOfHours3 = rowData[15];
var TotalRate3 = rowData[16];
var Outsourced = "Outsourced Technical Support Resource";
var PerHourRate4 = rowData[18];
var NumberOfHours4 = rowData[19];
var TotalRate4 = rowData[20];
var Supplier = "Supplier Management";
var PerHourRate5 = rowData[22];
var NumberOfHours5 = rowData[23];
var TotalRate5 = rowData[24];
var Project = "Project Management & Execution";
var PerHourRate6 = rowData[26];
var NumberOfHours6 = rowData[27];
var TotalRate6 = rowData[28];
var UserAccount = rowData[28];
var GrandTotalRate = rowData[29];
var seq = e.values[1];
var url = ScriptApp.getService().getUrl();
var sheet = SpreadsheetApp.openById('1i5x0oqpCDgOZO2Nbly4SpNkWpLbTXJhT6pPOfQ7NuEc').getSheetByName("Sheet1");
var cellval = range.getCell(row,1).getValue();
var options = '?approval=%APPROVE%&reply=%EMAIL%'
.replace("%EMAIL%",e.namedValues["User Email Address"])
var approve = url+options.replace("%APPROVE%","Approved")+'&row='+data+'&cellval='+cellval;
var reject = url+options.replace("%APPROVE%","Rejected")+'&row='+data+'&cellval='+cellval;
var subject = 'Technology Charges for '+ProjectName+'';
var html = '<p style="font-family:Verdana; fontsize=9px">Hello Recipient,<br/><br/><br/><br/>Referance No: '+cellval+'<br/><a href='+ approve +'> <b>approve </b></a><a href='+ reject +'> <b>Reject</b></a><br/>'
MailApp.sendEmail({
to: emailAddress,
subject: subject,
htmlBody: html,
});
//Add a state in the form spreadsheet with APPROVERS_EMAILED state
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
sheet.getRange(lastRow, REQUESTS_STATE_COLUMN+1).setValue(STATE_APPROVERS_EMAILED);
}
}
function doGet(e){
var answer = (e.parameter.approval === 'Approved') ? 'Yes -Approved!' : 'No-Rejected ';
var cellval = e.parameter.cellval;
var email = e.parameter.reply;
var sheet = SpreadsheetApp.openById("1i5x0oqpCDgOZO2Nbly4SpNkWpLbTXJhT6pPOfQ7NuEc").getSheetByName("Sheet1");
var data = sheet.getDataRange().getValues();
var headers = data[0];
var approvalCol = headers.indexOf("Approval") + 1;
if (0 === approvalCol) throw new Error ("Must add Approval column.");
// Record approval or rejection in spreadsheet
var row = ArrayLib.indexOf(data, 0, cellval);
if (row < 0) throw new Error ("Request not available."); // Throw error if request was not found
sheet.getRange(row+1, approvalCol).setValue(e.parameter.approval);
// Display response to approver
var app = UiApp.createApplication();
app.add(app.createHTML('<h2>Thank you..! Your response has been recorded'+' saying: '+ answer + '</h2>'))
return app
}
The getCell requires integer value for row and column but instead you are passing the entire row (rowData). You need to replace the line 45 to the below line.
var cellval = dataRange.getCell(i+1, 1).getValue()

Copy rows from one sheet to another

I need to create a master sheet for our managers that only include activity happening in their areas (I have a script for this that does what I need). These sheets are populated from my master sheet (and are not in the same workbook).
I need to have rows copy to the applicable sheet when there is a new submission. My code below dumps them all to one sheet and I'm not sure why. I'm assuming I don't have the right condition but how do you say "move rows to this sheet when it's this manager"? I thought calling the sheet ID by row would be enough, but I guess not.
Would I then have to do an if else statement for every manager? That will get tedious since I have about 80 managers.
Below is my current code. Any help or advice is appreciated!
function moveRows(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName("Form Responses 1");
var data = sh.getDataRange().getValues();
// Grab the Headers
var headers = sh.getRange(1,1,1,sh.getLastColumn()).getValues();
var nameCol = headers[0].indexOf('Enter Your Name');
var candCol = headers[0].indexOf('Choose Candidate');
var typeCol = headers[0].indexOf('Merged Experience');
var docCol = headers[0].indexOf('Document Link');
var timeCol = headers[0].indexOf('Timestamp');
var subjectCol = headers[0].indexOf('Choose the Content Area');
var ratingsCol = headers[0].indexOf('Ratings Summary');
var accessCol = headers[0].indexOf('Access');
var activityCol = headers[0].indexOf('Copied to Activity Sheet');
var masterCol = headers[0].indexOf('Master Activity Sheet');
var target = [];
// Loop over the values line by line
for (var i = 0; i < data.length; i++) {
var row = data[i];
var name = row[nameCol];
var activity = row[activityCol];
var master = row[masterCol];
var candidate = row[candCol];
var type = row[typeCol];
var subject = row[subjectCol];
var ratings = row[ratingsCol];
var access = row[accessCol];
var guide = row[docCol];
var time = row[timeCol];
if (activity == "") { // if condition is true copy the whole row to target
target.push([time,name,candidate,subject,type,guide,ratings]);
Logger.log(target);
var ss2 = SpreadsheetApp.openById(master);
var sh2 = ss2.getSheetByName("Sheet1");
sh2.getDataRange().offset(sh2.getLastRow(), 0, target.length, target[0].length).setValues(target);
}
}
}
Note: I have a bunch of different scripts that move rows from one tab to another, but I couldn't find anything where I move it across multiple workbooks.
What you can do is to have an array with for each manager the sheet where to copy the data.
var managerSheet = {
"manager1":"SheetAzerty",
"manager2":"SheetQwerty"
};
to select the sheet just do :
var manager = "manager1"; //This is the value you retrieve
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(managerSheet[manager]);
Stéphane

Create a Contact Group via Google Spreadsheet

I am trying to create an email distribution list from a Google form. I then want to place the individuals in a particular contact group. Here is the code I've compiled thus far. Please help. Thank you in advance.
function addContact() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 3;
var numRows = 10; // I want the rows to be infinite
var dataRange = sheet.getRange(startRow, 2, numRows, 10)
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var firstName = row[1];
var lastName = row[2];
var emailAdd = row[3];
}
// The code below creates a new contact and adds it to the "Work Friends" contact group
var contact = ContactsApp.createContact(firstName, lastName, emailAdd);
var group = ContactsApp.getContactGroup('Work Friends');
group.addContact(contact);
}
You were close, just needed some tweaking. See comments in-line, explaining the changes.
function addContact() {
var sheet = SpreadsheetApp.getActiveSheet();
// var startRow = 3; // This implies you have two header rows...
var headerRows = 2; // Number of header rows to skip
// var numRows = 10; // I want the rows to be infinite (so use getDataRange)
var dataRange = sheet.getDataRange(); // Range containing all non-blank rows & cols
var data = dataRange.getValues(); // Read all data
data.splice(0,headerRows); // Remove header rows
for (i =0; i<data.length; i++) { // Avoid using for..in with arrays
var row = data[i];
var firstName = row[1];
var lastName = row[2];
var emailAdd = row[3];
// Do this IN the loop vvv
// The code below creates a new contact and adds it to the "Work Friends" contact group
var contact = ContactsApp.createContact(firstName, lastName, emailAdd);
var group = ContactsApp.getContactGroup('Work Friends');
debugger; // Pause if running in debugger, to examine state
group.addContact(contact);
}
}