Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //add-on menu
- function onOpen() {
- SpreadsheetApp.getUi()
- .createMenu("Contacts")
- .addItem('Turn ON Form Submit', 'onFormSubmits')
- .addItem('Turn OFF Form Submit', 'offFormSubmits')
- .addSeparator()
- .addItem('Authorize first time', 'authorize')
- .addSeparator()
- .addItem('Contact', 'showContact')
- .addToUi();
- }
- function authorize() {
- showAlert("Successfully authorized!")
- }
- //on edit and on form submit triggers
- function onFormSubmits() {
- offFormSubmits(true)
- ScriptApp.newTrigger("onFormSubmit")
- .forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
- .onFormSubmit()
- .create();
- showAlert("Successfully turned ON Service");
- }
- function offFormSubmits(silent) {
- deleteTriggers(true, "onFormSubmit");
- if(!silent) showAlert("Successfully turned OFF Service");
- }
- function deleteTriggers(silent, handlerFunction) {
- var triggers = ScriptApp.getProjectTriggers();
- if(handlerFunction) {
- for(var i = 0; i < triggers.length; i++) {
- if(triggers[i].getHandlerFunction() == handlerFunction) {
- ScriptApp.deleteTrigger(triggers[i]);
- }
- }
- } else {
- for(var i = 0; i < triggers.length; i++) {
- ScriptApp.deleteTrigger(triggers[i]);
- }
- if(!silent) showAlert("All Schedules deleted");
- }
- }
- //alert
- function showAlert(msg) {
- var ui = SpreadsheetApp.getUi();
- var result = ui.alert(' ', msg + "", ui.ButtonSet.OK);
- }
- //contact
- function showContact() {
- showAlert('This add-on/script was developed by landing.hk. xx@xx.com');
- }
- //simple key pair JSON
- function getColumnNamedValues(values) {
- var obj = {}
- for(var i = 1; i < values.length; i++) {
- if(values[i][0]) {
- obj[values[i][0]] = values[i][1];
- }
- }
- return obj;
- }
- function getIdFromUrl(url) {
- return url.match(/[-\w]{25,}/)[0];
- }
- function getHeadersAsJSON(values) {
- var obj = {}
- var headers = values[0]
- for(var i = 0; i < headers.length; i++) {
- if(headers[i]) {
- obj[headers[i]] = i;
- }
- }
- return obj;
- }
- function getContactGroups() {
- var pageSize = 1000;
- var pageToken = undefined;
- var groups = [];
- const contactGroups = {};
- do {
- var contactGroupsList = People.ContactGroups.list({
- pageSize: pageSize,
- pageToken: pageToken
- });
- groups = groups.concat(contactGroupsList.contactGroups)
- pageToken = contactGroupsList["nextPageToken"]
- } while(contactGroupsList["nextPageToken"]);
- return groups;
- }
- function onFormSubmit(e) {
- Logger.log(JSON.stringify(e));
- var e = {
- "authMode": "FULL",
- "namedValues": {
- "Size": ["Size1"],
- "Phone no": ["66071058"],
- "quantity": ["10"],
- "Paid verification": [""],
- "Timestamp": ["12/05/2023 16:53:12"],
- "Item": ["TEST1"]
- },
- "range": {
- "columnEnd": 7,
- "columnStart": 1,
- "rowEnd": 24,
- "rowStart": 24
- },
- "source": {},
- "triggerUid": "6918381830689003333",
- "values": ["12/05/2023 16:53:12", "66071058", "TEST1", "Size1", "10", ""]
- }
- try {
- if(e.range.columnStart == e.range.columnEnd) return;
- var ss = SpreadsheetApp.getActiveSpreadsheet();
- var settings = getColumnNamedValues(ss.getSheetByName("SETTINGS")
- .getDataRange()
- .getValues())
- var sheet = ss.getSheetByName(settings["SHEETNAME_DEFAULT"]);
- var headerObj = getHeadersAsJSON(sheet.getRange("1:1")
- .getDisplayValues());
- var values = sheet.getRange(e.range.rowStart + ":" + e.range.rowStart)
- .getValues();
- var lookup = getContactGroups();
- x = values[0][headerObj[settings["LANDINGPAGE"]]]?.toString()
- if(x) {
- var found = false;
- for(var k = 0; k < lookup.length; k++) {
- if(lookup[k].formattedName == x) {
- contactGroupResourceName = (lookup[k].resourceName);
- found = true;
- break;
- }
- }
- if(!found) {
- var newGroup = People.ContactGroups.create({
- "contactGroup": {
- "name": x
- }
- });
- contactGroupResourceName = (newGroup.resourceName);
- }
- console.log(`${values[0][headerObj[settings["NAME"]]]?.toString()}`)
- //make a false call
- People.People.searchContacts({
- "query": `${values[0][headerObj[settings["NAME"]]]?.toString()}`,
- "readMask": "userDefined",
- "sources": [
- "READ_SOURCE_TYPE_CONTACT"
- ]
- });
- Utilities.sleep(2000); //induce some sleep
- //make a second call so that cache is refreshed, this is a google bug and we make a workaround
- var search = People.People.searchContacts({
- "query": `${values[0][headerObj[settings["NAME"]]]?.toString()}`,
- "readMask": "userDefined",
- "sources": [
- "READ_SOURCE_TYPE_CONTACT"
- ]
- })
- console.log(search)
- var exitsingUserDefinedPairs = search.results[0].person.userDefined.map(ud => {
- return {
- "key": ud.key,
- "value": ud.value
- }
- })
- foundContactResource = search?.results?.[0].person.resourceName;
- console.log(foundContactResource)
- if(foundContactResource) {
- People.People.deleteContact(foundContactResource.toString())
- }
- console.log("Hello")
- var person = {
- "organizations": [{
- "name": `${values[0][headerObj[settings["LANDINGPAGE"]]]?.toString()}` || " "
- }],
- "names": [{
- "givenName": `${values[0][headerObj[settings["NAME"]]]?.toString()}` || " ",
- "familyName": `${values[0][headerObj[settings["NUMBER"]]]?.toString()}` || " ",
- }],
- "phoneNumbers": [{
- "type": "home",
- "value": values[0][headerObj[settings["PHONE"]]]?.toString() || " "
- }],
- "urls": [{
- "type": "WhatsApp",
- "value": values[0][headerObj[settings["WAME"]]]?.toString() || " "
- }],
- "userDefined": [{
- "key": "Campaign",
- "value": values[0][headerObj[settings["CAMPAIGN"]]]?.toString() || " "
- },
- {
- "key": "Join Date",
- "value": values[0][headerObj[settings["JOIN"]]]?.toString() || " "
- }
- ].concat(exitsingUserDefinedPairs),
- "memberships": [{
- "contactGroupMembership": {
- "contactGroupResourceName": contactGroupResourceName
- }
- }],
- }
- }
- var contactResource = People.People.createContact(person);
- console.log(JSON.stringify(contactResource))
- sheet.getRange(e.range.rowStart, headerObj["Status_S2C"] + 1)
- .setNote(contactResource.resourceName)
- .setValue(`Ok [${settings["CAMPAIGN"]}]`)
- .setBackground("#cfe2f3")
- } catch (error) {
- console.log(error)
- sheet.getRange(e.range.rowStart, headerObj["Status_S2C"] + 1)
- .setNote(error)
- .setValue(`Failed [${settings["CAMPAIGN"]}]`)
- .setBackground("#e6b8af")
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement