SURVEY Component

This is the image caption

The block diagram of SURVEY component

Warning

Update the function names

Function createNewBSurvey

createNewBSurvey(year)

The function creates a new beneficairy survey, updates the existing one, uploads/updates the location file

Arguments
  • year (string) – current year

This is the image caption

The block diagram of SURVEY component

Warning

Update the function names

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
function createNewBSurvey(Year) {

    if (Year < 2017 || Year == null) { return; }
    var mainfolderid = createFolder(0, key["MAINFOLDER"]);
    YearFolder = createFolder(mainfolderid, "ALLFILES" + Year);
    TEMPLATEFOLDER = createFolder(YearFolder, "TEMPLATE" + Year);
    BSURVEYFOLDER = createFolder(YearFolder, "BSURVEY" + Year);
    CANALYSISFOLDER = createFolder(YearFolder, "COUNTRY_ANALYSIS" + Year);
    DATABRIDGEFOLDER = createFolder(YearFolder, "DATABRIDGE" + Year);

    { /* if benefeciary survey form doesn't exist, create and upload it*/

        { /*Check existing surveys*/
            var url = 'https://kobocat.unhcr.org/api/v1/forms';
            var option = {
                "method": "get",
                "headers": {
                    "Authorization": "Token " + key["APITOKEN2"],
                }
            };

            try { var json = UrlFetchApp.fetch(url, option); } catch (e) { var error = e; Logger.log(error.message); }
            var jsonData = JSON.parse(json.getContentText());

            var r = 0,
                rr = 0,
                pr = 0;

            for (i = 0; i < jsonData.length; i++) {
                /*Real beneficiary survey exists*/
                if (jsonData[i]["title"].indexOf(Year) > -1 && jsonData[i]["title"].indexOf("TRAINING (DEMO)") == -1 && jsonData[i]["title"].indexOf("Beneficiary") > -1) {
                    r = 1; 
                }
                /*Demo beneficiary survey exists*/
                if (jsonData[i]["title"].indexOf(Year) > -1 && jsonData[i]["title"].indexOf("TRAINING (DEMO)") > -1 && jsonData[i]["title"].indexOf("Beneficiary") > -1) {
                    rr = 1; 
                }
                 /*Real partner survey exists*/
                if (jsonData[i]["title"].indexOf(Year) > -1 && jsonData[i]["title"].indexOf("Partner") > -1) {
                    pr = 1; 
                }
            }
        }

        if (r == 0) {
            var xslbsurvey = createFile(key["XSLFORMFPOLDERID"], "CUSTOM_" + key["SECTOR"].toUpperCase() + "_BENEFICIARY_SURVEY.xlsx");
            saveForm(xslbsurvey, Year + " CUSTOMISED - " + key["SECTOR"] + " Beneficiary Survey", Year);
            updateLog("CUSTOMISED - Beneficiary (REAL) Survey created : " + Year);
        }

        if (rr == 0) {
            var xslbsurveyT = createFile(key["XSLFORMFPOLDERID"], "CUSTOM_" + key["SECTOR"].toUpperCase() + "_BENEFICIARY_SURVEY_T.xlsx");
            saveForm(xslbsurveyT, Year + " TRAINING (DEMO) : CUSTOMISED - " + key["SECTOR"] + " Beneficiary Survey", Year);
            updateLog("CUSTOMISED - Beneficiary (DEMO) Survey created : " + Year);
        }

        if (pr == 0) {
            var xslpsurvey = createFile(key["XSLFORMFPOLDERID"], "CUSTOM_" + key["SECTOR"].toUpperCase() + "_PARTNER_SURVEY.xlsx");
            saveForm(xslpsurvey, Year + " CUSTOMISED - " + key["SECTOR"] + " Partner Survey", Year);
            updateLog("CUSTOMISED - Partner Survey created : " + Year);
        }

    }
    { /*upload CSV "locations"*/
        { /*For CSV "locations": Check existing surveys to obtain ID for just created survey above*/
            var url = 'https://kobocat.unhcr.org/api/v1/forms';
            var option = {
                "method": "get",
                "headers": {
                    "Authorization": "Token " + key["APITOKEN2"],
                }
            };

            try { var json = UrlFetchApp.fetch(url, option); } catch (e) { var error = e; Logger.log(error.message); }
            var jsonData = JSON.parse(json.getContentText());

            var r = 0,
                rr = 0,
                pr = 0;
            var realformid,
                demoformid,
                partnerformid;
            for (i = 0; i < jsonData.length; i++) {
                if (jsonData[i]["title"].indexOf(Year) > -1 && jsonData[i]["title"].indexOf("TRAINING (DEMO)") == -1 && jsonData[i]["title"].indexOf("Beneficiary") > -1) {
                    r = 1;
                    realformid = jsonData[i]["formid"];
                }

                if (jsonData[i]["title"].indexOf(Year) > -1 && jsonData[i]["title"].indexOf("TRAINING (DEMO)") > -1 && jsonData[i]["title"].indexOf("Beneficiary") > -1) {
                    rr = 1;
                    demoformid = jsonData[i]["formid"];
                }

                if (jsonData[i]["title"].indexOf(Year) > -1 && jsonData[i]["title"].indexOf("Partner") > -1) {
                    pr = 1;
                    partnerformid = jsonData[i]["formid"];
                }
            }
        }

        var idSS = createFile(BSURVEYFOLDER, "locations");

        /*GETTING ORIGIAL CSV LOCATION SHEET*/
        var ss1 = SpreadsheetApp.openById(idSS);
        var sheet = ss1.getSheetByName("Sheet1");

        /*COPYING THE KEY LIST*/
        var scvlocations = createFile(key["OTHERFOLDERID"], "Locations");
        var ss2 = SpreadsheetApp.openById(scvlocations);
        var sheet2 = ss2.getSheetByName("Sheet1");

        var copy = sheet2.getRange(1, 1, sheet2.getLastRow(), sheet2.getLastColumn()).getValues();
        sheet.getRange(1, 1, sheet2.getLastRow(), sheet2.getLastColumn()).setValues(copy);

        /*REGISTERING URL*/
        var csv3 = "CSVURL3" + Year;
        var locationurl = DriveApp.getFileById(idSS).getUrl();
        keyinputs[csv3] = locationurl;
        key[csv3] = locationurl;

        if (r == 1) {
            try { CSVDELETE(realformid, "locations.csv"); } catch (e) { }
            /*Uploading METAFILES*/
            try { createCsvMetaFile(idSS, realformid, "locations.csv"); } catch (e) { }
        }

        if (rr == 1) {
            try { CSVDELETE(demoformid, "locations.csv"); } catch (e) { }
            /*Uploading METAFILES*/
            try { createCsvMetaFile(idSS, demoformid, "locations.csv"); } catch (e) { }
        }

        if (pr == 1) {
            try { CSVDELETE(partnerformid, "locations.csv"); } catch (e) { }
            /*Uploading METAFILES*/
            try { createCsvMetaFile(idSS, partnerformid, "locations.csv"); } catch (e) { }

        }

        updateLog("Locations CSV updated : " + Year);
    }
    { /*The registration of URL*/
        var newid = createFile(BSURVEYFOLDER, Year + " CUSTOMISED - " + key["SECTOR"] + " Beneficiary Survey");
        var newid2 = createFile(BSURVEYFOLDER, Year + " TRAINING (DEMO) : CUSTOMISED - " + key["SECTOR"] + " Beneficiary Survey");
        var newid3 = createFile(BSURVEYFOLDER, Year + " CUSTOMISED - " + key["SECTOR"] + " Partner Survey");

        var newurl = DriveApp.getFileById(newid).getUrl();
        var newurl2 = DriveApp.getFileById(newid2).getUrl();
        var newurl2 = DriveApp.getFileById(newid3).getUrl();
        var kf = 'XSLF' + realformid;
        var kf2 = 'XSLF' + demoformid;
        var kf3 = 'XSLF' + partnerformid;

        keyinputs[kf] = newurl;
        keyinputs[kf2] = newurl2;
        keyinputs[kf3] = newurl2;
        key[kf] = newurl;
        key[kf2] = newurl2;
        key[kf3] = newurl2;
    }

Function saveForm

saveForm(Bfileid, Bname, BYear)

The function saves a newly constructing xsl form on spreadsheet

Arguments
  • Bfileid (type) – ID of the form

  • Bname (string) – Name of the form

  • BYear (string) – Year of the form

This is the image caption

The block diagram of saveForm function

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function saveForm(Bfileid, BName, BYear) {
    /*XSLFORM*/
    var ss = SpreadsheetApp.openById(Bfileid);
    var survey = ss.getSheetByName("survey");
    var choices = ss.getSheetByName("choices");
    var settings = ss.getSheetByName("settings");

    /*IDString with random number*/
    var IDString = "AUTO" + BYear + Math.floor(Math.random() * 1000000);

    /*Changing the year on XSL form*/
    var tempdata = survey.getRange(1, 1, survey.getLastRow(), survey.getLastColumn()).getValues();
    tempdata[findRowByName(tempdata, "name", "MonitoringYear")][tempdata[0].indexOf("calculation")] = BYear;
    survey.getRange(1, 1, survey.getLastRow(), survey.getLastColumn()).setValues(tempdata);

    /*Changing the NAMES / ID_STRING on XSL FORM*/
    var tempdata2 = settings.getRange(1, 1, settings.getLastRow(), settings.getLastColumn()).getValues();
    tempdata2[1][tempdata2[0].indexOf("title")] = BName;
    tempdata2[1][tempdata2[0].indexOf("id_string")] = IDString;
    settings.getRange(1, 1, settings.getLastRow(), settings.getLastColumn()).setValues(tempdata2);

    /*Creating a temporarily file*/ 
    var idSS = SpreadsheetApp.create(BName).getId();
    var fileSS = DriveApp.getFileById(idSS);
    var sss = SpreadsheetApp.openById(idSS);

    /*Copying to temporary file*/
    var nwheet = survey.copyTo(sss).setName("survey");
    var nwheet = choices.copyTo(sss).setName("choices");
    var nwheet = settings.copyTo(sss).setName("settings");

    /*Converting to Excel*/
    var url = sss.getUrl();
    url = url.replace(/edit$/, '');
    var url_ext = url + 'export?exportFormat=xlsx';
    var token = ScriptApp.getOAuthToken();
    var params = { method: "get", headers: { 'Authorization': 'Bearer ' + token } };
    try { var blob = UrlFetchApp.fetch(url_ext, params).getBlob(); } catch (e) { var error = e; Logger.log(error.message); }
  
    /*Sending to  KOBO*/
    var r = uploadNewForm(blob, IDString);

    /*Deleting the old file*/
    var oldfile = DriveApp.getFileById(createFile(BSURVEYFOLDER, BName));
    oldfile.setTrashed(true);

    /*Moving to the folder*/
    dest_folder = DriveApp.getFolderById(BSURVEYFOLDER);
    var fid5 = dest_folder.addFile(fileSS).getId();

    /*Deleting the temporarily sheet*/
    DriveApp.getRootFolder().removeFile(fileSS);
}

Function uploadNewForm

uploadNewForm(b, IDString)

The function uploads a new XLS FORM to KOBOTOLBOX (Automatic process)

Arguments
  • b (type) – blod

  • IDString (string) – id_string

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function uploadNewForm(b, IDString) {
    var boundary = "labnol";

    var requestBody = Utilities.newBlob(
        "--" + boundary + "\r\n" +
        "Content-Disposition: form-data; name=\"xls_file\"; filename=\"" + IDString + ".xls\"\r\n\r\n").getBytes()
        .concat(b.getBytes())
        .concat(Utilities.newBlob("\r\n--" + boundary + "--\r\n").getBytes());

    Logger.log(requestBody);

    var options = {
        "method": "post",
        "contentType": "multipart/form-data; boundary=" + boundary,
        "payload": requestBody,
        'headers': {
             'Authorization': 'Token ' + key["APITOKEN2"]
        }
    };

    try { var response = UrlFetchApp.fetch("https://kobocat.unhcr.org/api/v1/forms", options); } catch (e) { var error = e; Logger.log(error.message); }
    Logger.log(response);
    return response;
}

Function updateFormCreateBlob

updateFormCreateBlob(name, fyear, FID, pkey)

The function manually updates the xls form to create blob

Arguments
  • name (string) – name of the form

  • fyear (string) – form year

  • FID (string) – id of the form

  • pkey (Object) – the list of key properties and their values

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
function updateFormCreateBlob(name, fyear, FID, pkey) {
    if (pkey != null) { key = pkey };
 
    var mainfolderid = createFolder(0, key["MAINFOLDER"]);
    YearFolder = createFolder(mainfolderid, "ALLFILES" + fyear);
    BSURVEYFOLDER = createFolder(YearFolder, "BSURVEY" + fyear);

    var fileid = getFile(BSURVEYFOLDER, name);
    if (fileid == null) {

        Browser.msgBox("Cannot find the file. Do you want to recover the xls form for this survey form Kobo?", Browser.Buttons.YES_NO);
        if (r == "no") { return; }

        {/*Recovering file from Kobo*/
            var url = 'https://kobocat.unhcr.org/api/v1/forms/' + FID + "/form.xls";

            var option = {
                "method": "get",
                "headers": {
                    "Authorization": "Token " + key["APITOKEN2"]
                }
            };

            try { var excelFile = UrlFetchApp.fetch(url, option).getBlob(); } catch (e) { var error = e; Logger.log(error.message); return; }
            var uploadParams = {
                method: 'post',
                contentType: 'application/vnd.ms-excel', /* works for both .xls and .xlsx files*/
                contentLength: excelFile.getBytes().length,
                headers: { 'Authorization': 'Bearer ' + ScriptApp.getOAuthToken() },
                payload: excelFile.getBytes()
            };

            /* Upload file to Drive root folder and convert to Sheets*/
            var uploadResponse = UrlFetchApp.fetch('https://www.googleapis.com/upload/drive/v2/files/?uploadType=media&convert=true', uploadParams);

            /* Parse upload&convert response data (need this to be able to get id of converted sheet)*/
            var fileDataResponse = JSON.parse(uploadResponse.getContentText());

            /* Create payload (body) data for updating converted file's name and parent folder(s)*/
            var payloadData = {
                title: name,
                parents: []
            };
            payloadData.parents.push({ id: BSURVEYFOLDER });

            /*Parameters for Drive API File Update request (see https://developers.google.com/drive/v2/reference/files/update)*/
            var updateParams = {
                method: 'put',
                headers: { 'Authorization': 'Bearer ' + ScriptApp.getOAuthToken() },
                contentType: 'application/json',
                payload: JSON.stringify(payloadData)
            };

            /* Update metadata (filename and parent folder(s)) of converted sheet*/
            UrlFetchApp.fetch('https://www.googleapis.com/drive/v2/files/' + fileDataResponse.id, updateParams);
        }

         /*Registration of URL*/
        var newid = getFile(BSURVEYFOLDER, name + ".xlsx");
        var newurl = DriveApp.getFileById(newid).getUrl();
        var kf = 'XSLF' + FID;
        keyinputs[kf] = newurl;
        key[kf] = newurl;

        Browser.msgBox("Recovering the xls form from Kobo completed.");
        return;
    }

    var result = Browser.msgBox("ARE YOU SURE TO UPDATE " + name + " for year " + fyear + " (" + FID + ")??", Browser.Buttons.YES_NO);
    if (result == "no") {
        return;
    }

    var sss = SpreadsheetApp.openById(fileid);
    var sssheet = sss.getSheetByName("settings");
    var tempdata = sssheet.getRange(1, 1, sssheet.getLastRow(), sssheet.getLastColumn()).getValues();
    var IDString = tempdata[1][tempdata[0].indexOf("id_string")];

    //Excel  
    var url = sss.getUrl();
    url = url.replace(/edit$/, '');
    var url_ext = url + 'export?exportFormat=xlsx';
    var token = ScriptApp.getOAuthToken();
    var params = { method: "get", headers: { 'Authorization': 'Bearer ' + token } };
    try { var blob = UrlFetchApp.fetch(url_ext, params).getBlob(); } catch (e) { var error = e; Logger.log(error.message); }
  
    var r = updateForm(blob, IDString, FID);

    if (r == 1) { updateLog("Kobo XSL Form updated : " + fyear + ":" + name); }
    if (pkey != null) { return (keyinputs); }
    return r;
}

Function updateForm

updateForm(b, IDString, FID)

The function updates the xls form

Arguments
  • b (string) – blob

  • IDString (string) – id_string

  • FID (string) – id of the form

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function updateForm(b, IDString, FID) {
    var boundary = "labnol";

    var requestBody = Utilities.newBlob(
        "--" + boundary + "\r\n" +
        "Content-Disposition: form-data; name=\"xls_file\"; filename=\"" + IDString + ".xls\"\r\n\r\n").getBytes()
        .concat(b.getBytes())
        .concat(Utilities.newBlob("\r\n--" + boundary + "--\r\n").getBytes());

    Logger.log(requestBody);

    var options = {
        "method": "patch",
        "contentType": "multipart/form-data; boundary=" + boundary,
        "payload": requestBody,
        'headers': {
            'Authorization': 'Token ' + key["APITOKEN2"]
        }
    };

    try {
        var response = UrlFetchApp.fetch("https://kobocat.unhcr.org/api/v1/forms/" + FID, options);
    } catch (e) { var error = e; Logger.log(error.message); return 2; }
    return 1;
}

Function updateManuallyLocationFile

This is the image caption

The block diagram of updateManuallyLocationFile function

updateManuallyLocationFile(Year, pkey)

The function updates the location file (manually)

Arguments
  • Year (string) – current year

  • pkey (Object) – the list of key properties and their values

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
    function updateManuallyLocationFile(Year, pkey) {
        if (pkey != null) { key = pkey };
        if (Year < 2017 || Year == null) { return; }

        var mainfolderid = createFolder(0, key["MAINFOLDER"]);
        YearFolder = createFolder(mainfolderid, "ALLFILES" + Year);
        TEMPLATEFOLDER = createFolder(YearFolder, "TEMPLATE" + Year);
        BSURVEYFOLDER = createFolder(YearFolder, "BSURVEY" + Year);
        var idSS = getFile(BSURVEYFOLDER, "locations");
        var RECOVERY;

        if (idSS == null) {
            Browser.msgBox("Cannot find the file. Do you want to recover the xls form for this survey form Kobo?", Browser.Buttons.YES_NO);
            if (r == "no") { return; }
            var RECOVERY = "Yes";
        }

        var url = 'https://kobocat.unhcr.org/api/v1/forms';
        var option = {
            "method": "get",
            "headers": {
                "Authorization": "Token " + key["APITOKEN2"],
            }
        };

        try { var json = UrlFetchApp.fetch(url, option); } catch (e) { var error = e; Logger.log(error.message); }
        var jsonData = JSON.parse(json.getContentText());

        var r = 0,
            rr = 0,
            pr = 0;
        var realformid,
            demoformid,
            partnerformid;

        for (i = 0; i < jsonData.length; i++) {
            if (jsonData[i]["title"].indexOf(Year) > -1 && jsonData[i]["title"].indexOf("TRAINING (DEMO)") == -1 && jsonData[i]["title"].indexOf("Beneficiary") > -1) {
                r = 1;
                realformid = jsonData[i]["formid"];
            }

            if (jsonData[i]["title"].indexOf(Year) > -1 && jsonData[i]["title"].indexOf("TRAINING (DEMO)") > -1 && jsonData[i]["title"].indexOf("Beneficiary") > -1) {
                rr = 1;
                demoformid = jsonData[i]["formid"];
            }

            if (jsonData[i]["title"].indexOf(Year) > -1 && jsonData[i]["title"].indexOf("Partner") > -1) {
                pr = 1;
                partnerformid = jsonData[i]["formid"];
            }
        }

        /*IF THERE IS NO SURVEY READY.*/
        if (realformid == null) { Browser.msgBox("The beneficiary survey cannot be found in Kobo for " + Year); return 2; };

        /*TO RECOVER THE FILE IN CASE LOCATION FILE CANNOT BE FOUND IN LOCAL DRIVE BUT EXISTS IN KOBO*/
        if (RECOVERY == "Yes") {


            {/*RECOVERING FILE FROM KOBO*/

                /*GETMETA FILE AND ID FROM KOBO*/
                var url = 'https://kobocat.unhcr.org/api/v1/metadata';
                var option = {
                    "method": "get",
                    "headers": {
                        "Authorization": "Token " + key["APITOKEN2"] 
                    }
                };

                try { var json = UrlFetchApp.fetch(url, option); } catch (e) { var error = e; Logger.log(error.message); }
                var meta = JSON.parse(json.getContentText());

                var metaid;
                for (m = 0; m < meta.length; m++) {
                    if (meta[m]["xform"] == realformid && meta[m]["data_value"] == "locations.csv") { metaid = meta[m]["id"]; break; }
                }

                metaid = metaid + ".csv";
                var url = 'https://kobocat.unhcr.org/api/v1/metadata/' + metaid;

                var option = {
                    "method": "get",
                    "headers": {
                        "Authorization": "Token " + key["APITOKEN2"]
                    }
                };

                try { var locationFile = UrlFetchApp.fetch(url, option).getBlob(); } catch (e) { var error = e; Logger.log(error.message); return; }

                var uploadParams = {
                    method: 'post',
                    contentType: 'text/csv', 
                    contentLength: locationFile.getBytes().length,
                    headers: { 'Authorization': 'Bearer ' + ScriptApp.getOAuthToken() },
                    payload: locationFile.getBytes()
                };

                /* Upload file to Drive root folder and convert to Sheets*/
                var uploadResponse = UrlFetchApp.fetch('https://www.googleapis.com/upload/drive/v2/files/?uploadType=media&convert=true', uploadParams);

                /* Parse upload&convert response data (need this to be able to get id of converted sheet)*/
                var fileDataResponse = JSON.parse(uploadResponse.getContentText());

                /* Create payload (body) data for updating converted file's name and parent folder(s)*/
                var payloadData = {
                    title: "locations",
                    parents: []
                };
                payloadData.parents.push({ id: BSURVEYFOLDER });

                /*Parameters for Drive API File Update request (see https://developers.google.com/drive/v2/reference/files/update)*/
                var updateParams = {
                    method: 'put',
                    headers: { 'Authorization': 'Bearer ' + ScriptApp.getOAuthToken() },
                    contentType: 'application/json',
                    payload: JSON.stringify(payloadData)
                };

                /* Update metadata (filename and parent folder(s)) of converted sheet*/
                UrlFetchApp.fetch('https://www.googleapis.com/drive/v2/files/' + fileDataResponse.id, updateParams);
            }

            /*REGISTERING URL*/
            var newid = getFile(BSURVEYFOLDER, "locations.csv");
            var newurl = DriveApp.getFileById(newid).getUrl();
            var kf = "CSVURL3" + Year;
            keyinputs[kf] = newurl;
            key[kf] = newurl;

            Browser.msgBox("Recovering the locations file from Kobo completed.");
            if (pkey != null) { return (keyinputs); }
            return 2;
        }


        if (r == 1) {
            try { CSVDELETE(realformid, "locations.csv"); } catch (e) { }
            try { createCsvMetaFile(idSS, realformid, "locations.csv"); } catch (e) { }/*UPLOADING METAFILES*/
        }

        if (rr == 1) {
            try { CSVDELETE(demoformid, "locations.csv"); } catch (e) { }
            try { createCsvMetaFile(idSS, demoformid, "locations.csv"); } catch (e) { }/*UPLOADING METAFILES*/
        }

        if (pr == 1) {
            try { CSVDELETE(partnerformid, "locations.csv"); } catch (e) { }
            try { createCsvMetaFile(idSS, partnerformid, "locations.csv"); } catch (e) { }/*UPLOADING METAFILES*/

        }

        updateLog("Locations CSV updated : " + Year);

        /*REGISTER URL*/
        var csv3 = "CSVURL3" + Year;
        var locationurl = DriveApp.getFileById(idSS).getUrl();
        keyinputs[csv3] = locationurl;
        key[csv3] = locationurl;
        if (pkey != null) { return (keyinputs); }
        return 1;
    }

Function refreshBsurvey

refreshBsurvey(pkey)

The function refreshes the beneficiary survey

Arguments
  • pkey (Object) – the list of key properties and their values

1
2
3
4
5
6
function refreshBsurvey(pkey) {
    key = pkey;
    var bsurvey = ss.getSheetByName("BSURVEY");
    /*KOBO_FORM_LIST was replaced [17-06-2019]*/
    extractKoboForms(key["APITOKEN2"], bsurvey);
}