Julie Lewis
Julie Lewis

Reputation: 11

App Script to check if contact exists always returns contact does NOT exist

I am trying to check if a contact exists (by comparing first and last names) to avoid creating duplicate contacts. If it doesn't exist, I want to create the contact. When I run the code, I do not get an error. However, it states that the contact doesn't exist and creates it, even though the contact does exist. It is not able to find the contact and/or correctly compare it. Please help me find my error.

function checkAndCreateContactsFromSpreadsheet() {

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Contacts'); // Your sheet name
  var data = sheet.getDataRange().getValues(); // Get all data from the sheet

  for (var i = 1; i < data.length; i++) { // Skip header row
    var firstName = data[i][1];
    var lastName = data[i][0];
    var email = data[i][12];

  if (firstName && lastName) {
     var contact = findContactByName(firstName, lastName); // Check if contact exists by name
     
     if (contact) {
       Logger.log('Contact exists: ' + contact.names[0].displayName);
     } else {
       Logger.log('Contact does not exist. Creating new contact...');
      createContact(firstName, lastName, email); // Create contact if it doesn't exist
      }
   }
  }
}


function findContactByName(firstName, lastName) {
 
  try {
  
    const response = People.People.get('people/me', {personFields: 'names'});

    var connections = response.connections || [];
    for (var i = 0; i < connections.length; i++) {
      var person = connections[i];
      if (person.names) {
        // Check if the first name and last name match
        for (var j = 0; j < person.names.length; j++) {
          var fullName = person.names[j].displayName.split(' ');
          if (fullName[0].toLowerCase() === firstName.toLowerCase() && fullName[1].toLowerCase() === lastName.toLowerCase()) {
            return person; // Return contact if first and last name match
            
          }
        }
      }
    }
    return null; // Return null if no contact matches
  } catch (e) {
    Logger.log('Error finding contact: ' + e.message);
    return null;
  }
}

function createContact(firstName, lastName, email) {
  try {
    var newContact = {
      names: [{ givenName: firstName, familyName: lastName }],
      emailAddresses: [{ value: email }]
    };

    // Create the new contact using People API
    var createdContact = People.People.createContact(newContact);
    Logger.log('Created new contact: ' + createdContact.names[0].displayName);
  } catch (e) {
    Logger.log('Error creating contact: ' + e.message);
  }
}

Upvotes: 0

Views: 18

Answers (0)

Related Questions