Skip to content

Commit

Permalink
Merge pull request #51 from vanessanmd/media-tags-automation
Browse files Browse the repository at this point in the history
 feature: apps script automation to import/export gtm tags
  • Loading branch information
glima91 authored Nov 7, 2023
2 parents 2b01485 + a297c34 commit e4b33b7
Show file tree
Hide file tree
Showing 8 changed files with 407 additions and 0 deletions.
132 changes: 132 additions & 0 deletions script-automation/accessGTM.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
function formatRaw() {
console.log("Inicio formatRaw")
let sheet = SpreadsheetApp.getActiveSpreadsheet()
let rawSheet = sheet.getSheetByName("Raw");
rawSheet.clear();
rawSheet
.getRange(1, 1, 1, 12)
.setValues([["account_id", "container_id", "firing_trigger_id", "workspace_id", "tag_name", "tracking_id", "tag_id","tag_type","exclude", "media_name", "media_event", "parameter"]])
.setBackground("#007494")
.setFontColor("#ffffff")
.setFontWeight("bold");
console.log("Fim formatRaw")
}

function accessGTM(inputData) {
console.log("Inicio accessGTM")
//Acessar dados de entrada
let accounts = inputData.account;
let containers = inputData.container;
let workspaces = inputData.workspace;

//Acessar o container e listar as tags
let version_path = `accounts/${accounts}/containers/${containers}/workspaces/${workspaces}`
try{
var list_tags = TagManager.Accounts.Containers.Workspaces.Tags.list(version_path).tag;
}catch(err){
throw new Error('Invalid input data: Check account, container and workspace data')
}
var tracking_id = '';
var reduced_tags = [];
var tracking_id_list = [];
var exclude_list = [];
var media_name_list = [];
var media_event_list = [];

//tracking_id
//Percorrer as tags e verificar se o tracking_id existe, e se não houver, vamos setar como "Não existe"
for (var i=0 ; i < list_tags.length; i++ ){
var tag_monitoringMetadata = (list_tags[i].monitoringMetadata);
//Tracking_id
if(tag_monitoringMetadata == undefined || tag_monitoringMetadata.map == undefined){
tracking_id = undefined
}else{
tracking_id = tag_monitoringMetadata.map.find(({ key }) => {
return key === "tracking_id"
});
}

if(tracking_id == undefined){
tracking_id_list.push('Não existe');
}else{
tracking_id_list.push(tracking_id.value);
}

//exclude
if(tag_monitoringMetadata == undefined || tag_monitoringMetadata.map == undefined){
exclude = undefined
}else{
exclude = tag_monitoringMetadata.map.find(({ key }) => {
return key === "exclude"
});
}
if(exclude == undefined){
exclude_list.push(true); //true
}else{
exclude_list.push(exclude.value); //false
}

//media_name
if(tag_monitoringMetadata == undefined || tag_monitoringMetadata.map == undefined){
media_name = undefined
}else{
media_name = tag_monitoringMetadata.map.find(({ key }) => {
return key === "media_name"
});
}
if(media_name == undefined){
media_name_list.push('Não existe');
}else{
media_name_list.push(media_name.value);
}

//media_event
if(tag_monitoringMetadata == undefined || tag_monitoringMetadata.map == undefined){
media_event = undefined
}else{
media_event = tag_monitoringMetadata.map.find(({ key }) => {
return key === "media_event"
});
}
if(media_event == undefined){
media_event_list.push('Não existe');
}else{
media_event_list.push(media_event.value);
}


//Tratar as tags
var reduced_array = [
list_tags[i].accountId,
list_tags[i].containerId,
[list_tags[i].firingTriggerId].toString(),
list_tags[i].workspaceId,
list_tags[i].name,
tracking_id_list[i],
list_tags[i].tagId,
list_tags[i].type,
exclude_list[i],
media_name_list[i],
media_event_list[i],
JSON.stringify(list_tags[i])
]
reduced_tags.push(reduced_array)

//Inserir dados das tags na planilha
let sheet = SpreadsheetApp.getActiveSpreadsheet()
let rawSheet = sheet.getSheetByName("Raw");
let length_list = String(reduced_tags.length + 1);
rawSheet.getRange('A2'+':'+'L'+ length_list).setValues(reduced_tags);

//Inserir o checkbox na coluna Exclude
let excludeRule = SpreadsheetApp.newDataValidation().requireCheckbox().build();
let colExclude = rawSheet.getRange('I2'+':'+'I'+ length_list);
colExclude.setDataValidation(excludeRule);
}

console.log("Fim accessGTM")
}




67 changes: 67 additions & 0 deletions script-automation/check.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/* Create and formats the clean tab */
function formatClean() {
console.log("Inicio formatClean")
let sheet = SpreadsheetApp.getActiveSpreadsheet()
let cleanSheet = sheet.getSheetByName("Clean");
cleanSheet.clear();

cleanSheet
.getRange(1, 1, 1, 12)
.setValues([["account_id", "container_id", "firing_trigger_id", "workspace_id", "tag_name", "tracking_id", "tag_id","tag_type","exclude", "media_name", "media_event", "parameter"]])
.setBackground("#007494")
.setFontColor("#ffffff")
.setFontWeight("bold");
console.log("Fim formatClean")
}

/* Check the values in EXCLUDE */
function checkValue() {
console.log("Inicio checkValue")
let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Raw")
let lastRow = sheet.getLastRow()
let values = sheet.getRange('I2'+':'+'I'+ lastRow).getValues()
let valuesArray = [];

for (let i = 0; i < values.length; i++) {
if (values[i][0] == false) {
valuesArray.push(i+2)
}
}
console.log(valuesArray)
console.log("Fim checkValue")
return valuesArray
};


/* get the lines that contain the value */

function getRow(value) {
console.log("inicio getRow")
let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Raw");
let onlyMediaTags = []

for (let i = 0; i < value.length; i++) {
let values = sheet.getRange(value[i], 1, 1, 12).getValues();
//let values = sheet.getRange(value[i], 1, 1, sheet.getLastColumn()).getValues();
onlyMediaTags.push(values)
}
console.log("fim getRow")
console.log(onlyMediaTags)
return { onlyMediaTags }

}


/* Insert the lines in the CLEAN tab */

function insertClean(array) {
console.log("insert clear")

for (let i = 0; i < array.length; i++) {
let sheet = SpreadsheetApp.getActive().getSheetByName("Clean");
let lastRow = sheet.getLastRow();
let range = sheet.getRange(lastRow + 1, 1, 1, 12);
range.setValues([...array[i].slice(0, 12)]);
}
}

22 changes: 22 additions & 0 deletions script-automation/inputData.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*** Adicionar valores de entrada contidas na aba Dados de Entrada
*/
function inputData(){
let sheet = SpreadsheetApp.getActiveSpreadsheet();
let inputDataSheetPt = sheet.getSheetByName("Input PT").getRange('E2:E4').getValues().flat()
let inputDataSheetEn = sheet.getSheetByName("Input EN").getRange('E2:E4').getValues().flat()
let inputData = ''

if (inputDataSheetPt.includes('') != true){
inputData = inputDataSheetPt
} else if(inputDataSheetEn.includes('') != true){
inputData = inputDataSheetEn
}

let DATA = {
'account' : (inputData[0]),
'container' : (inputData[1]),
'workspace' : (inputData[2])
}
return (DATA)
}

18 changes: 18 additions & 0 deletions script-automation/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
function getAllTags() {
formatRaw();
let input = inputData();
accessGTM(input);
validationRawSheet()
}

function getMediaTags() {
formatClean();
let get = getRow(checkValue())
insertClean(get.onlyMediaTags)
}

function sentMediaTags(){
let input = inputData();
let workspaceId = createWorkspace(input)
updateTags(workspaceId,input)
}
21 changes: 21 additions & 0 deletions script-automation/menu.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
function onInstall(e) {
onOpen(e);
}

function onOpen(e) {
createMenu();
}

function createMenu() {
let ui = SpreadsheetApp.getUi()
ui.createMenu("Menu de Ações")
.addSubMenu(ui.createMenu('Dados Brutos')
.addItem("Acessar todas as tags", "getAllTags")
.addItem("Selecionar tags de mídia", "getMediaTags"))
.addSeparator()
.addSubMenu(ui.createMenu('Dados Limpos')
.addItem("Validar tags de mídia", "validationCleanSheet")
.addItem("Criar Workspace e enviar tags para GTM", "sentMediaTags"))
.addToUi();
}

20 changes: 20 additions & 0 deletions script-automation/protectSheet.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

function onOpen(){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
let rawSheet = sheet.getSheetByName("Raw");
let cleanSheet = sheet.getSheetByName("Clean");
var rawProtection = rawSheet.protect().setWarningOnly(true);
var cleanProtection = cleanSheet.protect().setWarningOnly(true);
var rawUnprotected = rawSheet.getRange('I2:I');
var trackingIdUnprotected = cleanSheet.getRange('F2:F');
var mediaNameUnprotected = cleanSheet.getRange('J2:J');
var mediaEventUnprotected = cleanSheet.getRange('K2:K');
rawProtection.setUnprotectedRanges([rawUnprotected]);
cleanProtection.setUnprotectedRanges([trackingIdUnprotected,mediaNameUnprotected,mediaEventUnprotected]);
}






90 changes: 90 additions & 0 deletions script-automation/sentToGTM.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/* Create a new Worlspace */
function createWorkspace(inputData) {
console.log("Inicio createWorkspace")
//Acessar dados de entrada
let accounts = inputData.account;
let containers = inputData.container;

const date = new Date();
var timestamp = date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate() + ", " + date.getHours() + "h" + date.getMinutes() + "m" + date.getSeconds() + "s";

var container_path = `accounts/${accounts}/containers/${containers}`
const workspace = TagManager.Accounts.Containers.Workspaces.create(
{'name': 'Media Quality ' + timestamp, 'description': 'Atualização das tags de mídia'},
container_path);
console.log("Fim createWorkspace")
return workspace
}


/* Update and sent all media tags to GTM */
function updateTags(createWorkspace, inputData){
console.log("Inicio updateTags")
let sheet = SpreadsheetApp.getActiveSpreadsheet();
let cleanSheet = sheet.getSheetByName("Clean");
let tag_name = cleanSheet.getRange('E2:E').getValues();
let tracking_id = cleanSheet.getRange('F2:F').getValues();
let tag_id = cleanSheet.getRange('G2:G').getValues();
let tag_type = cleanSheet.getRange('H2:H').getValues();
let exclude = cleanSheet.getRange('I2:I').getValues();
let media_name = cleanSheet.getRange('J2:J').getValues();
let media_event = cleanSheet.getRange('K2:K').getValues();
let parameter = cleanSheet.getRange('L2:L').getValues();
let lastRow = cleanSheet.getLastRow()-1;
let workspace_id = createWorkspace.workspaceId
let accounts = inputData.account;
let containers = inputData.container;

for(let i=0; i<lastRow; i++){
let firing_trigger_id = (JSON.parse(parameter[i])['firingTriggerId']).toString().replace('.',',').split(",");
let tag_firing_option = JSON.parse(parameter[i])["tagFiringOption"];
let parent_folder_id = JSON.parse(parameter[i])["parentFolderId"];
let paused = JSON.parse(parameter[i])["paused"];
let setup_tag = JSON.parse(parameter[i])["setupTag"];
let fingerprint = JSON.parse(parameter[i])["fingerprint"];
let consent_settings = JSON.parse(parameter[i])["consentSettings"];

let container_path = `accounts/${accounts}/containers/${containers}/workspaces/${workspace_id}/tags/${tag_id[i][0]}`
//let container_path = `accounts/${accounts}/containers/${containers}/workspaces/1000195/tags/${tag_id[i][0]}`

const tag = TagManager.Accounts.Containers.Workspaces.Tags.update(
{
'name': tag_name[i][0],
'liveOnly': false,
'type': tag_type[i][0],
'parameter': JSON.parse(parameter[i][0])["parameter"],
'monitoringMetadata':
{'map':
[
{'value': String(exclude[i][0]), 'type':'template','key':'exclude'},
{'type':'template', 'value': (tracking_id[i][0]).toString(), 'key':'tracking_id'},
{'type':'template','value': media_event[i][0], 'key':'media_event'},
{'value': media_name[i][0], 'type':'template','key':'media_name'}
],
'type':'map'},
'firingTriggerId': firing_trigger_id == ''? null:firing_trigger_id,
'tagFiringOption':tag_firing_option,
'monitoringMetadataTagNameKey': 'name',
'parentFolderId': parent_folder_id,
'paused': paused == ''? false:paused,
'setupTag': setup_tag==''? null:setup_tag,
'fingerprint': String(fingerprint),
'consentSettings': consent_settings == ''? null:consent_settings

},
container_path);

}
console.log("Fim updateTags")

//Exibir pop-up
var ui = SpreadsheetApp.getUi();
var response = ui.alert('Workspace criado: \n' + '\n'+ createWorkspace.name);
// Process the user's response.
if (response == ui.Button.YES) {
Logger.log('The user clicked "Yes."');
} else {
Logger.log('The user clicked "No" or the close button in the dialog\'s title bar.');
}
}

Loading

0 comments on commit e4b33b7

Please sign in to comment.