Added two new talkspace scripts

This commit is contained in:
Norm Rasmussen
2023-05-08 12:12:31 -04:00
parent 18a266746b
commit 29fee835f4
8 changed files with 520 additions and 24 deletions

View File

@ -9,3 +9,4 @@ recast = "9LISLpq7Ebqot3Xrggn5twKWZ"
mizuno = "stXNF84HWL8aCGeRjHEo2rJ1U"
sps = "VNDXh8K4tLYJ-Nvp78bo6w"
anthology = "BwDUDT3mM6xzubFOgrPZNfL53"
talkspace_1099 = "jpfQoIc2i5S6iq4saFjBOEkbt"

View File

@ -0,0 +1,41 @@
import requests
import Apikeys
import csv
apiKey = Apikeys.talkspace_1099
baseUrlemail = "https://api.northpass.com/v2/people?filter[email][eq]="
import_list = "/Users/normrasmussen/Downloads/Deactivate Providers - 5.1.23 - Sheet1.csv"
def getfromEmail(baseUrlemail, apiKey, import_list):
with open(import_list, newline='') as csvfile:
file = csv.reader(csvfile, delimiter=' ')
for email in file:
email = str(email).strip("['']")
url = baseUrlemail + f"{email}"
headers = {
"accept": "*/*",
"x-api-key": apiKey,
"content-type": "application/json",
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
response = response.json()
for data in response["data"]:
uuid = data["id"]
deactivate(email, uuid, apiKey)
else:
print("Another Error!")
def deactivate(email, uuid, apiKey):
print(f"Deactivating user {email} with uuid {uuid}.")
url = f"https://api.northpass.com/v2/people/{uuid}/deactivations"
headers = {"accept": "application/json","x-api-key": apiKey}
response = requests.post(url, headers=headers)
if response.status_code == 404 or response.status_code == 403:
print(f"Error {response.status_code} with uuid {uuid}")
else:
print("Successfully deactivated!")
if __name__ == "__main__":
getfromEmail(baseUrlemail, apiKey, import_list)

View File

@ -0,0 +1,61 @@
import requests
import Apikeys
import csv
apikey = Apikeys.talkspace_1099
url_email = "https://api.northpass.com/v2/people?filter[email][eq]="
import_list = "/Users/normrasmussen/Downloads/Compliance Payment - April.csv"
def getfromEmail(url_emil, apikey, import_list):
with open(import_list, newline='') as csvfile:
file = csv.reader(csvfile, delimiter=',')
for items in file:
email = items[0]
url = url_email + f"{email}"
headers = {
"accept": "*/*",
"x-api-key": apikey,
"content-type": "application/json",
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
response = response.json()
for data in response["data"]:
uuid = data["id"]
items.append(uuid)
add_multi_prop(items)
else:
print("Another Error!")
def add_multi_prop(items):
email = items[0]
role = items[1]
id_num = items[2]
paid = items[3].lower()
# paid_bool = bool("TRUE")
uuid = items[4]
url = "https://api.northpass.com/v2/properties/people/bulk"
payload = {"data": [
{
"type": "person_properties",
"attributes": {"properties": {
"paid": paid,
"role_type": role,
"user_id": id_num
}},
"id": uuid
}
]}
headers = {
"accept": "application/json",
"content-type": "application/json",
"X-Api-Key": apikey}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 404 or response.status_code == 403:
print(f"Error {response.status_code} with user {email}")
else:
print(f"Successfully Added props for {email}!")
if __name__ == "__main__":
getfromEmail(url_email, apikey, import_list)

View File

@ -1,5 +1,19 @@
const sheet = SpreadsheetApp.getActiveSheet();
const apiKey = 'stXNF84HWL8aCGeRjHEo2rJ1U';
//import {LongRun} from "../LongRun";
//let data: string[];
function execute() {
const params = [];
params.push(3); // How many times the process should be executed
params.push(60); // How long does it take to process one case? (in seconds)
params.push(240); // Maximum acceptable run time in seconds (less than 6 minutes, of course)
params.push(1); // How many minutes later the next trigger will be activated
LongRun.instance.setParameters('getUuids', params);
LongRunTask();
}
const sheet = SpreadsheetApp.getActiveSheet();
const apiKey = 'stXNF84HWL8aCGeRjHEo2rJ1U';
function getUuids() {
var sheet = SpreadsheetApp.getActiveSheet();

View File

@ -0,0 +1,308 @@
// Compiled using ts2gas 3.6.5 (TypeScript 4.3.2)
var exports = exports || {};
var module = module || { exports: exports };
Object.defineProperty(exports, "__esModule", { value: true });
exports.executeLongRun = exports.LongRun = void 0;
//import Properties = GoogleAppsScript.Properties.Properties;
/**
* Long-Running Support
*/
var LongRun = /** @class */ (function () {
/**
* Private constructor
* @private
*/
function LongRun() {
/** start time map */
this.startTimeMap = {};
}
Object.defineProperty(LongRun, "instance", {
/**
* Returns singleton instance.
*/
get: function () {
if (!this._instance) {
this._instance = new LongRun();
}
return this._instance;
},
enumerable: false,
configurable: true
});
/**
* Returns if function is running now.
* @param funcName
*/
LongRun.prototype.isRunning = function (funcName) {
// get spreadsheet properties
var properties = PropertiesService.getScriptProperties();
var running = properties.getProperty(LongRun.PREFIX_RUNNING + funcName);
return !(running == null || running === '');
};
/**
* Sets the function is running
* @param funcName
* @param running
*/
LongRun.prototype.setRunning = function (funcName, running) {
var properties = PropertiesService.getScriptProperties();
var key = LongRun.PREFIX_RUNNING + funcName;
if (running) {
properties.setProperty(key, "running");
}
else {
properties.deleteProperty(key);
}
};
/**
* Sets max execution seconds
* @param seconds
*/
LongRun.prototype.setMaxExecutionSeconds = function (seconds) {
LongRun.RUNNING_MAX_SECONDS = seconds;
};
/**
* Sets the trigger's delay minutes
* @param minutes
*/
LongRun.prototype.setTriggerDelayMinutes = function (minutes) {
LongRun.RUNNING_DELAY_MINUTES = minutes;
};
/**
* Returns the function parameters
* @param funcName
*/
LongRun.prototype.getParameters = function (funcName) {
var properties = PropertiesService.getScriptProperties();
var parameters = properties.getProperty(LongRun.PREFIX_OPTION + funcName);
if (parameters != null) {
return parameters.split(',');
}
else {
return [];
}
};
/**
* Sets the function parameters.
* @param funcName
* @param parameters
*/
LongRun.prototype.setParameters = function (funcName, parameters) {
var properties = PropertiesService.getScriptProperties();
if (parameters != null) {
properties.setProperty(LongRun.PREFIX_OPTION + funcName, parameters.join(','));
}
else {
properties.deleteProperty(LongRun.PREFIX_OPTION + funcName);
}
};
/**
* Starts or Resumes Long-Run process.
* @param funcName
* @returns start index ( 0 for the first time )
*/
LongRun.prototype.startOrResume = function (funcName) {
// save start time
this.startTimeMap[funcName] = new Date().getTime();
// get properties of spreadsheet
var properties = PropertiesService.getScriptProperties();
// set running-flag
this.setRunning(funcName, true);
// if the trigger exists, delete it.
this.deleteTrigger(LongRun.PREFIX_TRIGGER_KEY + funcName);
// get start index
var startPos = parseInt(properties.getProperty(LongRun.PREFIX_START_POS + funcName));
if (!startPos) {
return 0;
}
else {
return startPos;
}
};
/**
* Determines whether the process should be suspended.
* If it should be suspended, the next trigger will be registered.
* @param funcName
* @param nextIndex - start position when resuming
* @return true - it should be suspended
*/
LongRun.prototype.checkShouldSuspend = function (funcName, nextIndex) {
var startTime = this.startTimeMap[funcName];
var diff = (new Date().getTime() - startTime) / 1000;
// If it's past the specified time, suspend the process
if (diff >= LongRun.RUNNING_MAX_SECONDS) {
// register the next trigger and set running-flag off
this.registerNextTrigger(funcName, nextIndex);
return true;
}
else {
return false;
}
};
/**
* Resets Long-Running variables
* @param funcName
*/
LongRun.prototype.reset = function (funcName) {
// delete trigger
this.deleteTrigger(LongRun.PREFIX_TRIGGER_KEY + funcName);
// delete spreadsheet properties
var properties = PropertiesService.getScriptProperties();
properties.deleteProperty(LongRun.PREFIX_START_POS + funcName);
properties.deleteProperty(LongRun.PREFIX_OPTION + funcName);
properties.deleteProperty(LongRun.PREFIX_RUNNING + funcName);
properties.deleteProperty(LongRun.PREFIX_TRIGGER_KEY + funcName);
};
/**
* Resets Long-Running variables if there is no next trigger.
* Returns whether the command has finished or not.
* @param funcName
*/
LongRun.prototype.end = function (funcName) {
var ret = false;
if (!this.existsNextTrigger(funcName)) {
this.reset(funcName);
ret = true;
}
return ret;
};
/**
* Returns if there is next trigger.
* @param funcName
*/
LongRun.prototype.existsNextTrigger = function (funcName) {
var triggerId = PropertiesService.getScriptProperties().getProperty(LongRun.PREFIX_TRIGGER_KEY + funcName);
return triggerId != null;
};
/**
* register the next trigger and set running-flag off
* @param funcName
* @param nextIndex - start position when resuming
*/
LongRun.prototype.registerNextTrigger = function (funcName, nextIndex) {
// get spreadsheet properties
var properties = PropertiesService.getScriptProperties();
properties.setProperty(LongRun.PREFIX_START_POS + funcName, String(nextIndex)); // save next start position
this.setTrigger(LongRun.PREFIX_TRIGGER_KEY + funcName, funcName); // set trigger
// turn off running-flag
properties.deleteProperty(LongRun.PREFIX_RUNNING + funcName);
};
/**
* Deletes the trigger
* @param triggerKey
*/
LongRun.prototype.deleteTrigger = function (triggerKey) {
var triggerId = PropertiesService.getScriptProperties().getProperty(triggerKey);
if (!triggerId)
return;
ScriptApp.getProjectTriggers().filter(function (trigger) {
return trigger.getUniqueId() == triggerId;
})
.forEach(function (trigger) {
ScriptApp.deleteTrigger(trigger);
});
PropertiesService.getScriptProperties().deleteProperty(triggerKey);
};
/**
* Sets a trigger
* @param triggerKey
* @param funcName
*/
LongRun.prototype.setTrigger = function (triggerKey, funcName) {
this.deleteTrigger(triggerKey); // delete if exists.
var dt = new Date();
dt.setMinutes(dt.getMinutes() + LongRun.RUNNING_DELAY_MINUTES); // will execute after the specified time
var triggerId = ScriptApp.newTrigger(funcName).timeBased().at(dt).create().getUniqueId();
// save the trigger id to delete the trigger later.
PropertiesService.getScriptProperties().setProperty(triggerKey, triggerId);
};
// constants
LongRun.PREFIX_RUNNING = "running_";
LongRun.PREFIX_TRIGGER_KEY = "trigger_";
LongRun.PREFIX_START_POS = "start_";
LongRun.PREFIX_OPTION = "option_";
LongRun.RUNNING_MAX_SECONDS = 4 * 60;
LongRun.RUNNING_DELAY_MINUTES = 1;
LongRun.EXECUTE_LONGRUN_FUNCNAME = "_executeLongRun";
return LongRun;
}());
exports.LongRun = LongRun;
/**
* A function allows you to easily execute long-run task using the LongRun class.
*
* @param mainFuncName - Name of the function to be executed each time.
* @param loopCount - Number of times to execute the main function.
* @param params - Parameters passed to each function (string[]). (optional)
* @param initializerName - Name of the first function to be executed on first or restart. (optional)
* @param finalizerName - Name of the function to be called on interruption or when all processing is complete. (optional)
*
* The definition of each function to be passed should be as follows.
* - Main function: function [function name](index: number, params: string[]) {...}
* - Initializer: function [function name](startIndex: number, params: string[]) {...}
* - Finalizer: function [function name](isFinished: boolean, params: string[]) {...}
*
* Note that it is not possible to use executeLongRun() to execute different long-time processes simultaneously.
*/
function executeLongRun(mainFuncName, loopCount, params, initializerName, finalizerName) {
if (params === void 0) { params = null; }
if (initializerName === void 0) { initializerName = null; }
if (finalizerName === void 0) { finalizerName = null; }
var longRunParams = [];
longRunParams.push(mainFuncName);
longRunParams.push(String(loopCount));
longRunParams.push(initializerName === null ? '' : initializerName);
longRunParams.push(finalizerName === null ? '' : finalizerName);
if (params != null && params.length > 0) {
longRunParams.push(params.join(','));
}
LongRun.instance.setParameters(LongRun.EXECUTE_LONGRUN_FUNCNAME, longRunParams);
_executeLongRun();
}
exports.executeLongRun = executeLongRun;
/**
* The main body of executeLongRun
*/
function _executeLongRun() {
var longRun = LongRun.instance;
// get parameters
var longRunParams = longRun.getParameters(LongRun.EXECUTE_LONGRUN_FUNCNAME);
var mainFuncName = longRunParams[0];
var loopCount = parseInt(longRunParams[1]);
var initializerName = longRunParams[2];
var finalizerName = longRunParams[3];
var params = [];
for (var i = 4; i < longRunParams.length; i++) {
params.push('"' + longRunParams[i] + '"');
}
var paramsLiteral = '[' + params.join(',') + ']';
var startIndex = longRun.startOrResume(LongRun.EXECUTE_LONGRUN_FUNCNAME);
try {
// *** call initializer ***
if (initializerName != null && initializerName.length > 0) {
eval(initializerName + '(' + startIndex + ',' + paramsLiteral + ')');
}
// execute the iterative process.
for (var i = startIndex; i < loopCount; i++) {
// Each time before executing a process, you need to check if it should be stopped or not.
if (longRun.checkShouldSuspend(LongRun.EXECUTE_LONGRUN_FUNCNAME, i)) {
// if checkShouldSuspend() returns true, the next trigger has been set
// and you should get out of the loop.
console.log('*** The process has been suspended. ***');
break;
}
// *** call main process ***
eval(mainFuncName + '(' + i + ',' + paramsLiteral + ')');
}
}
catch (e) {
console.log(e.message);
}
finally {
// you must always call end() to reset the long-running variables if there is no next trigger.
var finished = longRun.end(LongRun.EXECUTE_LONGRUN_FUNCNAME);
// *** call finalizer ***
if (finalizerName != null && finalizerName.length > 0) {
eval(finalizerName + '(' + finished + ',' + paramsLiteral + ')');
}
}
}

View File

@ -0,0 +1,82 @@
//const sheet = SpreadsheetApp.getActiveSheet();
//const apiKey = 'stXNF84HWL8aCGeRjHEo2rJ1U';
function getUuids() {
var sheet = SpreadsheetApp.getActiveSheet();
var numRows = sheet.getLastRow()-1; // Number of rows to process
var dataRange = sheet.getRange(3, 3, numRows, 1); // Column C
var values = dataRange.getValues();
writeHeadings();
for (email in values){
var row = values[email];
var email = row[0]
var api_url = 'https://api.northpass.com/v2/people/?filter[email][eq]='+email;
const settings = {
async: true,
crossDomain: true,
method: 'GET',
headers: {
accept: 'application/json',
'X-Api-Key': apiKey
}
};
const sendMsg = UrlFetchApp.fetch(api_url, settings);
var uuidResponse = sendMsg.getContentText();
var parsedata = JSON.parse(uuidResponse);
try {
var uuid = parsedata["data"][0]["id"];
if (email != "") {
findRow(email, uuid);
}
}
catch(ex) {
Logger.log(ex)
continue
}
finally {
}
};
};
function findRow(email, uuid){
var sheetRow = SpreadsheetApp.getActiveSpreadsheet();
var data = sheetRow.getDataRange().getValues();
for(var i = 0; i<data.length;i++){
if(data[i][2] == email){ //[1] because column B
// Logger.log((i+1))
var row = i+1;
propstoSheet(uuid, row);
}
}
}
function propstoSheet(uuid, row) {
var uuid_url = 'https://api.northpass.com/v2/properties/people/'+uuid;
const settings = {
async: true,
crossDomain: true,
url: uuid_url,
method: 'GET',
headers: {
accept: 'application/json',
'X-Api-Key': apiKey,
}
};
const sendMsg = UrlFetchApp.fetch(uuid_url, settings);
var txtResponse = sendMsg.getContentText();
var parseProps = JSON.parse(txtResponse);
var user_id = parseProps["data"]["attributes"]["properties"]["account_number"];
if (user_id != 0) {
// Write the Data to each row and column
sheet.getRange(row, 6).setValue(user_id);
} else {
}
}
function writeHeadings() {
// Write the new Column Headings
sheet.getRange(1, 6).setValue("PGA Number");
}

View File

@ -5,26 +5,15 @@ Campaign = customfield_10120
SDR = customfield_10122
Start Date = customfield_10015
Users:
Travis Nardin = 5d9cb42c0265ca0db955b965
Dan Peski = 603318815ddf020069969cad
Norm Rasmussen = 6092af20d353800068863d15
Michael Valido = 61fbf60cd8d7cf006a90941c
Jon Newfield = 6092af212c2f6c0068ec92c4
Isabel Katz = 620145241fec260068c107e5
Charles McGovern = 5eaaf1c4021ae30ba8fcb184
Nick Zuppe = 60eddda64257a90070aeebef
Doug Goldsmith = 61294a4845f753006951a590
Nick Appleby = 6183eab7892c420072f9c437
Quba Williams-Wilfong = 62101fe4e41f76006a6f6510
Prior to making this publicly available, I added a commented list of users & their account numbers.
Without accounts: Adan, Drew
*/
function myFunction() {
var URL = "https://northpass.atlassian.net/rest/api/3/issue/";
var token = "2NrKYv22TLWnxTo7EhU3633E";
var user = "nrasmussen@northpass.com";
var URL = "https://your_company.atlassian.net/rest/api/3/issue/";
var token = "api_toke_goes_here";
var user = "user@company.com";
var UserCredentials = Utilities.base64Encode(user + ":" + token);
// Setting up data range and empty arrays
@ -48,15 +37,15 @@ function myFunction() {
let list = [sdr, name, rawDate, bookingDate, meetingDate, company, channel, result, campaign, info];
let sdrDict = {
"Mike" :
"61fbf60cd8d7cf006a90941c",
"account_num_goes_here",
"Nick" :
"60eddda64257a90070aeebef",
"account_num_goes_here",
"Appleby" :
"6183eab7892c420072f9c437",
"Doug" :
"61294a4845f753006951a590",
"account_num_goes_here",
"Doug" :
"account_num_goes_here",
"Quba" :
"62101fe4e41f76006a6f6510",
"account_num_goes_here",
};
if (list.includes("Norm")) {
var data = {
@ -116,4 +105,4 @@ function myFunction() {
//Logger.log(respCode);
}
}
};
};