// ===========================================================================
// ===========================================================================
// CSV import
// ===========================================================================
// ===========================================================================
$(document).on('knack-scene-render.scene_XXX', function(event, view, record) {
//Import progress window functions - a super super ugly status display window
$("
Import progress Window
").css({
"position": "fixed",
"top": "20%",
"left": "60%",
"width": "40%",
"height": "90%",
"background-color": "rgba(255,255,0,.7)",
"z-index": 10000,
"vertical-align": "top",
"text-align": "right",
"color": "#000",
"font-size": "10px",
}).appendTo("#kn-scene_344");
function updateStatusInfo(myText){ //a function that updates the table display thing above
$("#statusOverlay > tbody > tr > td").append(" "+myText);
};
//In my example, I had to link all imported records to the currently open "Projects" details page:
var filetext
var knackProjectID //the knack record identifier for this page's project
//this is a "details" view from which I am extracting the unique front-facing project code, in order to look it up and get the knack back-end record ID
var projectCode = $("#view_831 > div.kn-details-column.first > div > div > table > tbody > tr.field_70 > td > span").text()
console.log(projectCode);
//All of our projects have different donors too. Budgetlines are connected to a project and to a donor. Projects and budgetlines are not connected directly.
//However, I can still make a details view to show all the donors associated with all the budget lines associated with the projects.
//I had to be sure the user didn't try to import a new donor, so this variable will help keep track of that:
var listOfDonors = [[],[]];
var currentProjectCurrencyID = ""
var x = {} //global counter
var existingBudgetLines //all existing budget lines
var scenarios
var initialCurrencyConversionRate //divide by this value to convert from donor currency to USD
var PPcategories
updateStatusInfo("Looking up project record");
// api to get the project record ID from the project code
var api_url = 'https://api.knack.com/v1/scenes/scene_186/views/view_889/records' //Projects table
userToken = Knack.getUserToken()
// preparing filters
var filters = [
{
field: 'field_70',
operator: 'is',
value: projectCode //find this Project Code record
}
]
// add to URL
api_url += '?filters=' + encodeURIComponent(JSON.stringify(filters));
Knack.showSpinner();
$.ajax({
url: api_url
, type: 'GET'
, headers: {
'X-Knack-Application-Id': '56fb8b0fad25a3be79b5054a'
, "X-Knack-REST-API-KEY": 'knack'
, "Authorization": userToken //userToken is a public variable I set on each page load
}
, success: function(data) { //once you successflly get the record
console.log(data)
if (data.records.length != 1) {
alert("Fatal error! Searched for project code " + projectCode + "which should be unique (1 result). Actually got " + data.length + "results. Is there a duplicate project code?!")
} else {
knackProjectID = data.records["0"].id
currentProjectCurrencyID = data.records["0"].field_922_raw["0"].id //Projects can be in different currencies, so are connected to currencies object.
console.log("Current project currency ID:") //the API call returns the connection ID (not field text) of the currencies.
console.log(currentProjectCurrencyID);
initialCurrencyConversionRate = data.records["0"].field_932_raw; //I have to convert these rates to USD as well, though
console.log("initial Currency Conversion Rate:")
console.log(initialCurrencyConversionRate)
if (initialCurrencyConversionRate == "" || initialCurrencyConversionRate == 0){ //if not entered, assume 1
updateStatusInfo(" No initial currency conversion rate set. Assuming donor contract currency is USD. ");
initialCurrencyConversionRate = 1
alert("No initial currency conversion rate has been set for this project. To work out default procurement scenarios, import will assume donor contract currency is USD. If this is incorrect, please first go back to the previous page and specify the donor contract currency.")
}
console.log("Knack Project ID:")
console.log(knackProjectID);
findExistingBudgetLines();
updateStatusInfo("Retrieved project record.");
}
}
, error: function (request, status, error) {
handleAjaxError(request, status, error);
}
});
function findExistingBudgetLines(){
var budgetLinesFromDetailsView = $("#view_831 > div.kn-details-column.first > div > div > table > tbody > tr.field_82 > td > span").text() //this is a details view showing all budget lines
existingBudgetLines = budgetLinesFromDetailsView.split(',').map(function(item) { //function take off whitespace at start/end and split by , character
return item.trim();
});
console.log("Existing budget lines:")
console.log(existingBudgetLines);
if (existingBudgetLines.length > 1) { // a few friendly notifications
updateStatusInfo("Some budget lines have already been entered for this project. These will be skipped during the import process.")
} else if (existingBudgetLines.length == 1 && existingBudgetLines[0] != "ACT") {
updateStatusInfo("There is already a budget line added to this project (other than the default 'ACT' line). Please ensure the CSV file you want to upload does not have duplicates of lines already on this system.")
} else {
updateStatusInfo("Done.");
}
updateStatusInfo("Looking up Procurement Scenario Limits"); //we have to set a "default procurement scenario" field based on the value of the line, in USD
lookupProcurementScenarioLimits();
}
function lookupProcurementScenarioLimits(){ //looks up procurement scenario limits. e.g < 200USD = scenario "A" etc
// api
var api_url = 'https://api.knack.com/v1/scenes/scene_186/views/view_987/records?sort_field=field_899&sort_order=asc' //Procurement Limits table
userToken = Knack.getUserToken();
Knack.showSpinner();
$.ajax({
url: api_url
, type: 'GET'
, headers: {
'X-Knack-Application-Id': '56fb8b0fad25a3be79b5054a'
, "X-Knack-REST-API-KEY": 'knack'
, "Authorization": userToken
}
, success: function(data) { //once you successflly get the record
scenarios = data //set variable
console.log("Scenarios:")
console.log(scenarios);
addFileBox();
}
, error: function (request, status, error) {
handleAjaxError(request, status, error);
}
});
}
function addFileBox(){
$('#view_831').append('
Please select a CSV file for import:
');
$('#view_831').append(''); //add an input box
Knack.hideSpinner()
document.getElementById('myFileBox').addEventListener('change', function(e) { //once a file has been selected, load it up
console.log("Called fileChanged function");
var file = myFileBox.files[0];
console.log(file);
var textType = /.+(\.csv)$/ ;
console.log(file.type)
$("#myImportButton").remove();
if (file.name.match(textType)) { //check for .csv file extension
var reader = new FileReader();
reader.readAsText(file); //load/read this as a text file
reader.onload = function(e) { //once loaded, do this
fileText = reader.result;
processData(fileText);
console.log("Currency conversion rate as of addFileBox function:")
console.log(initialCurrencyConversionRate)
}
} else {
alert("File not supported! Only files with a .csv extension can be uploaded here.")
}
});
};
// Here I display the CSV file to the user but with my own "custom" headings, to make sure everything is "matching up". Then I prompt the user to continue.
function processData(fileText) {
Knack.showSpinner();
$('#view_831 > table.table-data-omset').remove() //this gets rid of the display table, in the case that the user changed the file.
var allTextLines = fileText.split(/\r\n|\n/); //split the CSV file in to rows
var headers = allTextLines[0].split(','); //split again by comma
//NOTE: THIS WORKS FOR LEGACY CSV FILES WHERE THE COMMAS IS REALLY THE DELIMITER
//EXCEL CSV FILES TAKE A DIFFERENT FORMAT, each row as follows:
//"Field1","Field2","Field3"
//Modify the above code to suit. I was importing from a program which did just strictly delimit by comma only.
console.log("Headers:")
console.log(headers)
var lines = [];
for (var i=1; i 1) {
var number = i +1;
alert("Please check row " + number + " carefully and ensure there is no comma (,) present in any of the CSV cells. Otherwise this row will not be imported.")
};
}
}
console.log(lines);
console.log(lines.length);
console.log(lines[0].length);
$('#view_831').append('
') //draw a table
var tableOmset = $('table.table-data-omset');
var tbodyTableOmset = tableOmset.find('tbody');
var trTableOmset = '';
//add custom headers
trTableOmset += '
' ;
trTableOmset += '
'+ " x " +'
';
for(var b=0; b
'+ "Custom header 1" +'
';
}
else if (b==2){
trTableOmset += '
'+ "DONOR CODE" +'
';
}
else if (b==3){
trTableOmset += '
'+ "BUDGET LINE (LAST THREE LETTERS)" +'
';
}
else if (b==6){
trTableOmset += '
'+ "LINE DESCRIPTION" +'
';
}
else if (b==10){
trTableOmset += '
'+ "VALUE (donor currency)" +'
';
}
else {
trTableOmset += '
x
';
}
}
trTableOmset += '
' ;
// add headers from CSV
trTableOmset += '
' ;
trTableOmset += '
'+ "1" +'
'; //number first column
for(var b=0; b 40){
headers[b]= 'x';
}
trTableOmset += '
'+ headers[b] +'
';
}
trTableOmset += '
' ;
//add data, row by row
for(var a=0; a' ;
trTableOmset += '
'+ currentRow +'
'; //label the row
for(var b=0; b 80){ //Some of my fields had very long text that I didn't need, so I replaced with X
lines[a][b]= 'x';
}
trTableOmset += '
'+ lines[a][b] +'
'; //print
}
trTableOmset += '' ;
} else { //if a[3] was just blank
currentRow = a + 2 ; //corresponding row of the excel spreadsheet
trTableOmset += '
' ;
trTableOmset += '
'+ currentRow +'
';
trTableOmset += '
Row in CSV is header
'; //just add a message in that first cell
for(var b=1; b'+ lines[a][b] +'';
}
}
}
tbodyTableOmset.append(trTableOmset);
var donorField = 2 //One of the columns was my "donor" field. I need to check all donors in the CSV already exist, before importing.
checkDonorCodesExist(lines, donorField)
};
function checkDonorCodesExist(lines, b) {
Knack.showSpinner();
var thisDonor;
x = 0
for (var a = 0; a ') //add button
$('#myImportButton').hide(); //hide it
for (a = 0; a