'));
},
success: function (data) {
$('#support').modal('hide'); // hide support modal at transaction page
$('#sent').modal('show').delay(3000).fadeOut(450);
setTimeout(function() {
$('#sent').modal('hide');
}, 3450);
$('#ticketform input[name="support_subject"]').val('');
$('#support_message').val('');
$('#message').html('
Your support ticket was succesfully created and a confirmation message was sent to the e-mail address ' + email + ' .
');
}
});
}
});
}
function setYear() {
var selectedYear = getSelectedYear();
$('#selectedYear').html(selectedYear);
// build list of selectable years
var thisYear = new Date().getFullYear();
var year = 2011;
while (thisYear >= year) {
$('#years').append('
' + thisYear + '');
thisYear--;
}
// enable selection of year from selectable years
$('#yearSelector li').on('click', function(){
selectedYear = $(this).text();
$('#selectedYear').html(selectedYear);
sessionStorage.setItem('selectedYearAccounting', JSON.stringify(selectedYear));
});
}
function getSelectedYear() {
// set selected year from session
var selectedYear = JSON.parse(sessionStorage.getItem('selectedYearAccounting'));
if (selectedYear == null) {
selectedYear = new Date().getFullYear();
}
return parseInt(selectedYear);
}
function showCredits() {
$.getJSONCache(baseurl + creditsmethod, function (data) {
var credits_available = data.message.response.credits_available;
var remaining_days = data.message.response.remaining_days;
if (
(credits_available != null && typeof credits_available != 'undefined') &&
(remaining_days != null && typeof remaining_days != 'undefined')
) {
var creditsoverview = credits_available + ' Estimated use: ' + remaining_days + ' days remaining';
if (remaining_days <= 7) {
creditsoverview += 'Order credits now!';
}
creditsoverview += ' Click here to order additional credits. Click here to download the current price list';
} else {
creditsoverview = 'TEST MODE You can buy and use credits once you\'ve signed and returned our agreements. Please contact Support for more info';
}
$('span#creditsoverview').html(creditsoverview);
});
}
/* Gets JSON and caches for a certain amount of time */
$.getJSONCache = function (url, success, force, minutes) {
if(typeof minutes === "undefined" || parseInt(minutes) === 0) {
minutes = 1;
}
// check datastorage in cache and retrieve data from there
var data = JSON.parse(sessionStorage.getItem(B64.encode(url+'-data')));
var timeout = JSON.parse(sessionStorage.getItem(B64.encode(url+'-timeout')));
if(typeof force != "undefined") {
data = null;
}
// check data & timeout
if(data !== null && timeout !== null) {
timeout = new Date(timeout);
var now = new Date();
if(now < timeout) {
return success(data);
}
}
// save timeout to storage
var timeout = new Date();
timeout.setMinutes(timeout.getMinutes()+minutes);
sessionStorage.setItem(B64.encode(url+'-timeout'), JSON.stringify(timeout));
// put it in cache and reference the success-function to pass the data on to getJSONAuth
function cache(data) {
// save data to storage
sessionStorage.setItem(B64.encode(url+'-data'), JSON.stringify(data));
success(data);
}
return $.getJSONAuth(url, cache);
}
$.clearFromCache = function(url) {
sessionStorage.removeItem(B64.encode(url+'-data'));
}
/* Redefined PUT JSON function with authentication */
$.putJSONAuth = function (url, data, success, error, authentication, jsonp) {
if(typeof jsonp === "undefined") {
jsonp = false;
}
if (error == undefined) {
error = function (xhr, ajaxOptions, thrownError) {
document.location = 'index.php';
}
}
var ajax = $.ajax({
cache: false,
url: url,
type: 'PUT',
dataType: jsonp ? 'jsonp' : 'json',
jsonp: jsonp ? "callback" : undefined,
data: data,
beforeSend: function (xhr) {
if(typeof authentication === "undefined") {
// try to get it from sessionstorage
authentication = sessionStorage.getItem("authentication");
// or try to get it from localstorage
if(authentication === null) {
authentication = localStorage.getItem("authentication");
// got it from localstorage, now add it to sessionstorage
sessionStorage.setItem("authentication", authentication);
}
}
if(authentication === null) {
document.location = 'login.php';
}
xhr.setRequestHeader("Authorization", "Basic " + authentication);
},
statusCode: {
401: function() {
document.location = 'login.php';
},
404: function() {
data = 'not found';
},
500: function() {
alert('An error occured; the request could not be processed');
}
},
xhrFields: {
withCredentials: true
},
crossDomain: true
}).done(success).fail(error);
}
/* Redefined GET JSON function with authentication */
$.getJSONAuth = function (url, success, error, authentication, jsonp) {
if(typeof jsonp === "undefined") {
jsonp = false;
}
if (error == undefined) {
error = function (xhr, ajaxOptions, thrownError) {
document.location = 'index.php';
}
}
var ajax = $.ajax({
cache: false,
url: url,
type: 'GET',
dataType: jsonp ? 'jsonp' : 'json',
jsonp: jsonp ? "callback" : undefined,
beforeSend: function (xhr) {
if(typeof authentication === "undefined") {
// try to get it from sessionstorage
authentication = sessionStorage.getItem("authentication");
// or try to get it from localstorage
if(authentication === null) {
authentication = localStorage.getItem("authentication");
// got it from localstorage, now add it to sessionstorage
sessionStorage.setItem("authentication", authentication);
}
}
if(authentication === null) {
document.location = 'login.php';
}
xhr.setRequestHeader("Authorization", "Basic " + authentication);
},
statusCode: {
401: function() {
document.location = 'login.php';
},
404: function() {
data = 'not found';
},
500: function() {
alert('An error occured; the request could not be processed');
}
},
xhrFields: {
withCredentials: true
},
crossDomain: true
}).done(success).fail(error);
}
// Base64 enc
/*
Copyright Vassilis Petroulias [DRDigit]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var B64 = {
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
lookup: null,
ie: /MSIE /.test(navigator.userAgent),
ieo: /MSIE [67]/.test(navigator.userAgent),
encode: function (s) {
var buffer = B64.toUtf8(s),
position = -1,
len = buffer.length,
nan1, nan2, enc = [, , , ];
if (B64.ie) {
var result = [];
while (++position < len) {
nan1 = buffer[position + 1], nan2 = buffer[position + 2];
enc[0] = buffer[position] >> 2;
enc[1] = ((buffer[position] & 3) << 4) | (buffer[++position] >> 4);
if (isNaN(nan1)) enc[2] = enc[3] = 64;
else {
enc[2] = ((buffer[position] & 15) << 2) | (buffer[++position] >> 6);
enc[3] = (isNaN(nan2)) ? 64 : buffer[position] & 63;
}
result.push(B64.alphabet[enc[0]], B64.alphabet[enc[1]], B64.alphabet[enc[2]], B64.alphabet[enc[3]]);
}
return result.join('');
} else {
result = '';
while (++position < len) {
nan1 = buffer[position + 1], nan2 = buffer[position + 2];
enc[0] = buffer[position] >> 2;
enc[1] = ((buffer[position] & 3) << 4) | (buffer[++position] >> 4);
if (isNaN(nan1)) enc[2] = enc[3] = 64;
else {
enc[2] = ((buffer[position] & 15) << 2) | (buffer[++position] >> 6);
enc[3] = (isNaN(nan2)) ? 64 : buffer[position] & 63;
}
result += B64.alphabet[enc[0]] + B64.alphabet[enc[1]] + B64.alphabet[enc[2]] + B64.alphabet[enc[3]];
}
return result;
}
},
decode: function (s) {
var buffer = B64.fromUtf8(s),
position = 0,
len = buffer.length;
if (B64.ieo) {
result = [];
while (position < len) {
if (buffer[position] < 128) result.push(String.fromCharCode(buffer[position++]));
else if (buffer[position] > 191 && buffer[position] < 224) result.push(String.fromCharCode(((buffer[position++] & 31) << 6) | (buffer[position++] & 63)));
else result.push(String.fromCharCode(((buffer[position++] & 15) << 12) | ((buffer[position++] & 63) << 6) | (buffer[position++] & 63)));
}
return result.join('');
} else {
result = '';
while (position < len) {
if (buffer[position] < 128) result += String.fromCharCode(buffer[position++]);
else if (buffer[position] > 191 && buffer[position] < 224) result += String.fromCharCode(((buffer[position++] & 31) << 6) | (buffer[position++] & 63));
else result += String.fromCharCode(((buffer[position++] & 15) << 12) | ((buffer[position++] & 63) << 6) | (buffer[position++] & 63));
}
return result;
}
},
toUtf8: function (s) {
var position = -1,
len = s.length,
chr, buffer = [];
if (/^[\x00-\x7f]*$/.test(s)) while (++position < len)
buffer.push(s.charCodeAt(position));
else while (++position < len) {
chr = s.charCodeAt(position);
if (chr < 128) buffer.push(chr);
else if (chr < 2048) buffer.push((chr >> 6) | 192, (chr & 63) | 128);
else buffer.push((chr >> 12) | 224, ((chr >> 6) & 63) | 128, (chr & 63) | 128);
}
return buffer;
},
fromUtf8: function (s) {
var position = -1,
len, buffer = [],
enc = [, , , ];
if (!B64.lookup) {
len = B64.alphabet.length;
B64.lookup = {};
while (++position < len)
B64.lookup[B64.alphabet[position]] = position;
position = -1;
}
len = s.length;
while (position < len) {
enc[0] = B64.lookup[s.charAt(++position)];
enc[1] = B64.lookup[s.charAt(++position)];
buffer.push((enc[0] << 2) | (enc[1] >> 4));
enc[2] = B64.lookup[s.charAt(++position)];
if (enc[2] == 64) break;
buffer.push(((enc[1] & 15) << 4) | (enc[2] >> 2));
enc[3] = B64.lookup[s.charAt(++position)];
if (enc[3] == 64) break;
buffer.push(((enc[2] & 3) << 6) | enc[3]);
}
return buffer;
}
};
function downloadInvoice() {
// add download button
$('.download').click(function(e) {
e.preventDefault();
// try to get authentication from sessionstorage
var authentication = sessionStorage.getItem("authentication");
// or try to get it from localstorage
if (authentication === null) {
authentication = localStorage.getItem("authentication");
}
var invoice = $(this).data('invoice');
// create form
var form = $('');
form.append('');
form.append('');
$(this).after(form);
// submit and remove form
form.submit();
form.remove();
});
}/* Page */
function Page(success) {
"use strict";
if(typeof success === "undefined") {
success = function () {};
}
this.success = success;
this.contract = null;
this.initialize = function () {
// get contract info
var op = this;
$.getJSONCache(baseurl + infomethod, function (data) {
op.contract = data.message.response;
if (data.message.response.disabled !== undefined && data.message.response.disabled === 1) {
$('div#contract_disabled').show();
}
// set name in navbar
$('#navbar-contractname').text(op.contract.contractname);
// now run success function
op.success();
});
// accountdropdown; production accounts before demo accounts
$.getJSONCache(baseurl + accountsmethod, function (data) {
// create arrays
var productionaccountsmanualmode = [];
var demoaccountsmanualmode = [];
var productionaccountstransactions = [];
var demoaccountstransactions = [];
var productionaccountsstoredfiles = [];
var demoaccountsstoredfiles = [];
var productionaccountsbatcher = [];
var demoaccountsbatcher = [];
var productionaccountsdecoder = [];
var demoaccountsdecoder = [];
// iterate, fill arrays
$.each(data.message.response, function (i, val) {
var manualmodeaccounts = $('
');
// fill the transaction-arrays
if (val.Demo !== '1') {
productionaccountsmanualmode.push(manualmodeaccounts);
productionaccountstransactions.push(transactionaccounts);
} else {
demoaccountsmanualmode.push(manualmodeaccounts);
demoaccountstransactions.push(transactionaccounts);
}
// when there is a FTPUploadUser, fill the storedfiles-arrays
if (val.FTPuploadUser) {
$('#storedfilesmenuitem').parent().removeClass('hidden');
if (val.Demo !== '1') {
productionaccountsstoredfiles.push(storedfilesaccounts);
} else {
demoaccountsstoredfiles.push(storedfilesaccounts);
}
}
// when accounts have access to Batcher, fill array
if (val.Batcher === '1') {
if (val.Demo !== '1') {
productionaccountsbatcher.push(batcheraccounts);
} else {
demoaccountsbatcher.push(batcheraccounts);
}
}
// when accounts have access to Decoder, fill array
if (val.Decoder === '1') {
if (val.Demo !== '1') {
productionaccountsdecoder.push(decoderaccounts);
} else {
demoaccountsdecoder.push(decoderaccounts);
}
}
});
// add items for dropdown menu for Transactions
for (var i = 0; i < productionaccountstransactions.length > 0; i++) {
$('#navbar-accountdropdown').append(productionaccountstransactions[i]);
}
if(productionaccountstransactions.length > 0 && demoaccountstransactions.length > 0) {
$('#navbar-accountdropdown').append('');
}
for (var i = 0; i < demoaccountstransactions.length > 0; i++) {
$('#navbar-accountdropdown').append(demoaccountstransactions[i]);
}
// add items for dropdown menu for manual mode
for (var i = 0; i < productionaccountsmanualmode.length > 0; i++) {
$('#navbar-manualmodedropdown').append(productionaccountsmanualmode[i]);
}
if(productionaccountsmanualmode.length > 0 && demoaccountsmanualmode.length > 0) {
$('#navbar-manualmodedropdown').append('');
}
for (var i = 0; i < demoaccountsmanualmode.length > 0; i++) {
$('#navbar-manualmodedropdown').append(demoaccountsmanualmode[i]);
}
// do the same for Stored Files
for (var i = 0; i < productionaccountsstoredfiles.length > 0; i++) {
$('#navbar-storedfilesdropdown').append(productionaccountsstoredfiles[i]);
}
if(productionaccountsstoredfiles.length > 0 && demoaccountsstoredfiles.length > 0) {
$('#navbar-storedfilesdropdown').append('');
}
for (var i = 0; i < demoaccountsstoredfiles.length > 0; i++) {
$('#navbar-storedfilesdropdown').append(demoaccountsstoredfiles[i]);
}
// and don't let us forget the batcher
if(productionaccountsbatcher.length > 0 || demoaccountsbatcher.length > 0) {
$('#batcher').show();
}
for (var i = 0; i < productionaccountsbatcher.length > 0; i++) {
$('#navbar-batchesdropdown').append(productionaccountsbatcher[i]);
}
if(productionaccountsbatcher.length > 0 && demoaccountsbatcher.length > 0) {
$('#navbar-batchesdropdown').append('');
}
for (var i = 0; i < demoaccountsbatcher.length > 0; i++) {
$('#navbar-batchesdropdown').append(demoaccountsbatcher[i]);
}
// or the decoder
if(productionaccountsdecoder.length > 0 || demoaccountsdecoder.length > 0) {
$('#decoder').show();
}
for (var i = 0; i < productionaccountsdecoder.length > 0; i++) {
$('#navbar-decoderdropdown').append(productionaccountsdecoder[i]);
}
if(productionaccountsdecoder.length > 0 && demoaccountsdecoder.length > 0) {
$('#navbar-decoderdropdown').append('');
}
for (var i = 0; i < demoaccountsdecoder.length > 0; i++) {
$('#navbar-decoderdropdown').append(demoaccountsdecoder[i]);
}
});
// logout
$('#logout').click(function () {
localStorage.clear();
sessionStorage.clear();
document.location = 'login.php';
});
$('button[data-href]').click(function(){
document.location = $(this).data('href');
});
}
this.initialize();
}
// Contract
function Contract() {
"use strict";
this.info = null;
this.credits = null;
this.accounts = null;
this.showCredits = function (refresh) {
$.getJSONCache(baseurl + creditsmethod, function (data) {
var credits_available = data.message.response.credits_available
var remaining_days = data.message.response.remaining_days;
if (credits_available !== null) {
// display creditsavailable and estimateduse
$('#creditsinfo .creditsavailable').text(credits_available);
var ordernow = '';
if (remaining_days !== null) {
var estimated_use = $('#creditsinfo .estimateduse');
estimated_use.text(remaining_days + ' days remaining');
if (remaining_days <= 7) {
var order = ' Order credits now!';
estimated_use.append(order);
}
}
} else {
// or remove the headers
$('#creditsinfo .header_creditsavailable').text('');
$('#creditsinfo .header_estimateduse').text('');
}
}, refresh);
}
this.showInfo = function () {
$.getJSONCache(baseurl + infomethod, function (data) {
$('#contractinfo .contactname').text(data.message.response.contactname);
$('#contractinfo .contractname').text(data.message.response.contractname);
$('#contractinfo .contactmail').text(data.message.response.contactmail);
var agreement = $('#contractinfo .agreement');
if (!data.message.response.hasproductionaccounts) {
agreement.html('TEST MODE NO SIGNED AGREEMENTS RECEIVED! For commercial use, an agreement is required. Please contact Support for more info');
} else if (data.message.response.contractsigneddate !== null) {
var contractsigneddate = new Date(data.message.response.contractsigneddate);
agreement.text('Signed agreements ' + contractsigneddate.getDate() + '-' + (contractsigneddate.getMonth() + 1) + '-' + contractsigneddate.getFullYear());
} else {
agreement.remove();
}
});
}
this.showNewsContent = function(refresh) {
$.getJSONCache(baseurl + newscontentmethod, function (data) {
$('#news-content').html(data.message.response.news);
$('#hints-content').html(data.message.response.hints);
$('#important-content').html(data.message.response.important);
$('#newsletters-content').html(data.message.response.newsletters);
}, refresh);
}
this.displayWarning = function() {
var warning_agreement = $('#warning_agreement');
$.getJSONCache(baseurl + infomethod, function (data) {
if (data.message.response.hasproductionaccounts) {
warning_agreement.remove();
} else {
// display warning in Credits block
warning_agreement.text('You\'re using a free version of BooXtream which can only be used for test and implementation purposes. Any commercial and production usage is prohibited.');
}
});
}
this.initialize = function () {
var oPage = new Page();
this.showInfo();
this.showNewsContent();
this.showCredits();
this.displayWarning();
var op = this;
$('#refresh_credits_news').click(function () {
$(this).animateRotate(360, 500);
op.showCredits(true);
op.showNewsContent(true);
});
}
this.initialize();
}
// Login
function Login() {
"use strict";
var op = this;
this.login = function() {
var authentication = B64.encode($('input[name="accountname"]').val()+':'+$('input[name="accesskey"]').val());
$.getJSONAuth(baseurl + infomethod,
function (data) {
// set authentication to sessionstorage
sessionStorage.setItem("authentication", authentication);
// or if checkbox checked: set it to localstorage
if ($('input[name="rememberme"]').is(':checked')) {
localStorage.setItem("authentication", authentication);
}
$.post('session.php', data.message.response, function () {
document.location = 'index.php';
});
},
function (data) {
// error function (401)
$('#alert').slideDown('slow');
setTimeout(function () {
$('#alert').slideUp('slow');
}, 5000);
},
authentication
);
//return false;
}
this.initialize = function () {
$('#loginform').prepend($('
Oh snap!
Seems something is wrong with your credentials. Please try again.
').hide());
// inlogname and... enter
$('#accountname').keydown(function (e){
if(e.keyCode == 13){
op.login();
}
})
// password and... enter
$('#accesskey').keydown(function (e){
if(e.keyCode == 13){
op.login();
}
})
// use login-button
$('#login').click(function (e) {
op.login();
});
}
this.initialize();
}
function Transactions() {
"use strict";
this.Accounts = [];
this.pages = undefined;
this.page = undefined;
this._ignoreHashChange = false;
this.name = null; // AccountName (from accounts table)
this.accountname = null; // LoginName (from accounts table)
this.accountkey = null; // AuthenticationKey (from accounts table)
this.activesearch = false;
this.retrievetransactions = transactionsmethod;
this.limit = localStorage.getItem("transactionslimit");
if (this.limit == null) {
this.limit = 100;
}
this.displayTransactions = function (transactions, total, credits_available, remaining_days) {
this.pages = Math.ceil(total / this.limit);
// show transactions
$('#transactions-tbody').children('.datarow').remove();
if (credits_available !== null) {
$('#credits_available').text('Available credits: ' + credits_available);
}
if (remaining_days !== null) {
$('#estimated_use').text('Estimated use: ' + remaining_days + ' days remaining');
if (remaining_days <= 7) {
var order = ' Order credits now!';
$('#estimated_use').append(order);
}
}
var op = this;
$.each(transactions, function (i, val) {
var status = '';
if(val.Status === 'failed' || val.Failed === '1') {
status += ' ';
} else if (val.Status === 'processing') {
status += ' ';
} else {
status += ' ';
if (val.DeliveryPlatform === '1') {
status += op.getStatusHTML(val.DeliveryStatus, val.ExpireDate, val.TotalDownloads, val.DownloadLimit);
} else {
status += ' ';
}
}
if(val.Stored == 1) {
status += ' ';
}
// end with a non-breaking space to force the browser to assume the correct line-height
// status += ' ';
var filename = val.OriginalFilename.replace(/"/g,'"');
filename = getCellHTML('Master file', filename, 50, false); /* 24 */
var reference = getCellHTML('Reference', val.ReferenceID, 30);
var customeremailaddress = getCellHTML('Customer Email Address', val.CustomerEmailAddress, 25);
var customername = getCellHTML('Customer Name', val.CustomerName, 25);
var datetime = '';
var tr = $('
').addClass('datarow');
tr.append($('
' + datetime + '
'));
tr.append($('
' + status +'
'));
tr.append($('
' + reference + '
'));
tr.append($('
' + customeremailaddress + '
'));
tr.append($('
' + customername + '
'));
tr.append($('
' + filename + '
'));
// add click to datarow, goes to transaction
tr.click(function () {
window.location = 'transaction.php?account=' + op.accountname + '&uid=' + val.UID;
});
$('#transactions-tbody').append(tr);
});
// add tooltips
$('tr.datarow [data-toggle~="tooltip"]').tooltip();
// add popovers
$('tr.datarow [data-toggle~="popover"]').popover({
placement: 'top',
html: true,
trigger: 'hover'
});
}
// creates content for status cell
this.getStatusHTML = function (deliverystatus, expiredate, totaldownloads, downloadlimit) {
var content = 'Expires on ' + formatDisplayUTCDate(new Date(expiredate)).split(' ')[0] + ' (UTC) ' + totaldownloads + ' out of ' + downloadlimit + ' downloads.';
if(deliverystatus === 'expired' || deliverystatus === 'limitreached') {
return ' ';
}
return ' ';
}
this.getPage = function (pagenumber, search) {
startSpinner('#spinner');
this.page = parseInt(pagenumber);
// calculate offset based on number of transactions per page (limit)
var offset = (this.page - 1) * this.limit;
// show selected limit; the default number of rows
$('select.limit option[value="' + this.limit + '"]').attr('selected', 'selected');
// build transaction url
var url = baseurl + 'account/' + this.accountkey + '/' + this.retrievetransactions + '?offset=' + offset + '&limit=' + this.limit;
if(search !== undefined) {
url += '&search=' + search;
this.activesearch = search;
} else if (this.activesearch != false) {
url += '&search=' + this.activesearch;
}
// get and display transactions
var op = this;
$.getJSONAuth(url, function (data) {
op.name = data.message.account.AccountName;
if(typeof data.message !== undefined) {
if(data.message.total > 0) {
op.displayTransactions(data.message.response, data.message.total, data.message.credits_available, data.message.remaining_days);
op.displayPagination();
}
if(typeof search !== 'undefined' && parseInt(data.message.total) === 0) {
$('#searchmessage').html($('
').hide());
$('#alert').slideDown('slow');
setTimeout(function () {
$('#alert').slideUp('slow', function () { $(this).remove(); });
}, 5000);
}
$('#accountname').html(data.message.account.AccountName + (data.message.account.Demo === '1' ? ' (test account)' : ' (production account)'));
}
stopSpinner('#spinner');
});
}
this.initButtons = function() {
var op = this;
// display the right buttons
if (op.type == 'errors') {
$('.errortransactions').removeClass('btn-default').addClass('btn-primary');
$('#downloadTransactionsCSV').addClass('hidden');
} else {
$('.alltransactions').removeClass('btn-default').addClass('btn-primary');
$('#downloadTransactionsCSV').removeClass('hidden');
}
$('.transactiontypebutton').click(function() {
if($(this).hasClass('errortransactions')) {
op.type = 'errors';
$('.alltransactions').removeClass('btn-primary').addClass('btn-default');
$('.errortransactions').removeClass('btn-default').addClass('btn-primary');
op.retrievetransactions = failedtransactionsmethod;
op.sURL.parameters.type = 'errors';
$('#downloadTransactionsCSV').addClass('hidden');
} else {
op.type = 'all';
$('.errortransactions').removeClass('btn-primary').addClass('btn-default');
$('.alltransactions').removeClass('btn-default').addClass('btn-primary');
op.retrievetransactions = transactionsmethod;
op.sURL.parameters.type = 'all';
$('#downloadTransactionsCSV').removeClass('hidden');
}
op.sURL.parameters.page = 1;
var url = getURL(op.sURL);
history.pushState(null,null,url);
op.getPage(1);
});
// change limit
$('select.limit').change(function() {
op.limit = $(this).find('option:selected').text();
localStorage.setItem("transactionslimit", op.limit);
op.page = 1;
op.getPage(1);
});
$('#downloadTransactionsCSV').click(function (e) {
var datefrom = new Date(new Date().getFullYear(), 0, 1);
var dateuntil = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() -1);
// datefrom might lie 730 days further in the past
var mindatefrom = new Date(datefrom.getTime() - (730 * 24 * 60 * 60 * 1000));
$('#datepicker_datefrom').datepicker('setDate', datefrom)
.datepicker('option', 'maxDate', dateuntil)
.datepicker('option', 'minDate', mindatefrom)
.datepicker('option', 'dateFormat', 'yy-mm-dd')
.addClass('placeholder_layout');
$('#datepicker_dateuntil').datepicker('setDate', dateuntil)
.datepicker('option', 'maxDate', dateuntil)
.datepicker('option', 'minDate', mindatefrom)
.datepicker('option', 'dateFormat', 'yy-mm-dd')
.addClass('placeholder_layout');
});
// add functionality for downloadbutton
$('a#downloadTransactionsCSVButton').click(function(event) {
event.preventDefault();
// get dates from modal
var datefrom = new Date(Date.parse($('#datepicker_datefrom').datepicker('getDate')));
var dateuntil = new Date(Date.parse($('#datepicker_dateuntil').datepicker('getDate')));
if (datefrom > dateuntil) {
var message = 'Start date should be before end date.';
$('#exporterror').html(message).removeClass('hidden');
} else {
$('#exporterror').html('').addClass('hidden');
$('#downloadTransactionsCSVModal').modal('hide');
// try to get authentication from sessionstorage
var authentication = sessionStorage.getItem("authentication");
// or try to get it from localstorage
if (authentication === null) {
authentication = localStorage.getItem("authentication");
}
// convert dates from Epoch to yyyy-mm-dd (including leading zero's)
datefrom = datefrom.getFullYear() + '-' + ('0' + (datefrom.getMonth() + 1)).slice(-2) + '-' + ('0' + datefrom.getDate()).slice(-2);
dateuntil = dateuntil.getFullYear() + '-' + ('0' + (dateuntil.getMonth() + 1)).slice(-2) + '-' + ('0' + dateuntil.getDate()).slice(-2);
// create form
var form = $('');
form.append('');
form.append('');
form.append('');
form.append('');
form.append('');
form.append('');
$(this).after(form);
// submit and remove form
form.submit();
form.remove();
}
});
}
// functionality for the search bar
this.initSearch = function (search) {
var op = this;
$('#resetbutton').click(function() {
$('#resetbutton').addClass('hidden');
op.activesearch = false;
op.sURL.parameters.search = undefined;
op.sURL.parameters.page = 1;
// create url for pushState
var url = getURL(op.sURL);
history.pushState(null,null,url);
op.getPage(1);
});
$('#searchinput').keyup(function(){
if($(this).val().length > 0) {
$('#resetbutton').removeClass('hidden');
} else {
$('#resetbutton').addClass('hidden');
}
});
$('#search').on('submit', function () {
if($('#searchinput').val().length > 0) {
$('#resetbutton').removeClass('hidden');
} else {
$('#resetbutton').addClass('hidden');
}
var search = $(this).children('.input-group').children('input[name="search"]').val();
op.getPage(1,search);
op.sURL.parameters.search = search;
op.sURL.parameters.page = 1;
// create url for pushState
var url = getURL(op.sURL);
history.pushState(null,null,url);
return false;
});
/*
var livesearch = undefined;
$('#search input[name="search"]').on('keyup', function () {
var search = $('#search').children('.form-group').children('input[name="search"]').val();
clearTimeout(livesearch);
console.log(search.length);
if(search.length > 3) {
livesearch = setTimeout(function () {
op.getPage(1,search);
}, 1000);
}
});
*/
}
this.initPagination = initPagination;
this.displayPagination = displayPagination;
this.initialize = function () {
// initialize page
var oPage = new Page();
// get key first
this.sURL = urlObject();
var accountname = this.sURL.parameters.account;
this.accountname = accountname;
this.type = this.sURL.parameters.type;
if (this.type == 'errors') {
this.retrievetransactions = failedtransactionsmethod;
}
var op = this;
$( '#datepicker_datefrom' ).datepicker();
$( '#datepicker_dateuntil' ).datepicker();
$.getJSONCache(baseurl + accountsmethod, function (data) {
op.accountkey = data.message.response;
$.each(data.message.response, function (i,val) {
op.Accounts[val.LoginName] = val.AuthenticationKey;
});
op.accountkey = op.Accounts[accountname];
// see if url has search parameter
var search = undefined;
if(typeof op.sURL.parameters.search !== "undefined") {
$('#resetbutton').removeClass('hidden');
$('#searchinput').val(op.sURL.parameters.search);
search = op.sURL.parameters.search;
}
// get page
op.page = 1;
if(typeof op.sURL.parameters.page !== "undefined") {
op.page = op.sURL.parameters.page;
}
op.getPage(op.page,search);
});
// initialize the rest
this.initButtons();
this.initSearch();
this.initPagination();
// handle back-button
$(window).bind("popstate", function change(e) {
if(!this._ignoreHashChange) {
// we need to reset the urlObject
op.sURL = new urlObject();
var search = undefined;
if(typeof op.sURL.parameters.search !== "undefined") {
$('#resetbutton').removeClass('hidden');
$('#searchinput').val(op.sURL.parameters.search);
search = op.sURL.parameters.search;
} else {
op.activesearch = false;
if($('#searchinput').val() !== '') {
$('#search').get(0).reset();
}
}
// get page
op.page = 1;
if(typeof op.sURL.parameters.page !== "undefined") {
op.page = op.sURL.parameters.page;
}
op.getPage(op.page,search);
}
});
// catch transactions csv error
var fromdate = localStorage.getItem('fromdate');
var untildate = localStorage.getItem('untildate');
var message = localStorage.getItem('message');
if (fromdate && untildate && message) {
localStorage.removeItem('fromdate');
localStorage.removeItem('untildate');
localStorage.removeItem('message');
$('#downloadTransactionsCSV').click();
$('#datepicker_datefrom').datepicker('setDate', fromdate);
$('#datepicker_dateuntil').datepicker('setDate', untildate);
$('#exporterror').html(message).removeClass('hidden');
}
}
this.initialize();
}
// Transaction
function Transaction() {
"use strict";
this.Accounts = [];
this.accountkey = null;
this.uid = null;
this.transaction = null;
this.account = null;
this.oPage = null;
var op = this;
this.getTransaction = function () {
var op = this;
$.getJSONCache(baseurl + 'account/' + this.accountkey + '/' + transactionmethod + '?uid=' + this.uid, function (data) {
op.addItems(data.message.response);
$('#accountname').html(data.message.account.AccountName + (data.message.account.Demo === '1' ? ' (test account)' : ' (production account)'));
op.transaction = data.message.response;
op.account = data.message.account;
});
}
this.emptyTransaction = function () {
$('#etransaction').empty();
$('#tech').empty();
$('#errormessages').empty();
$('#identification').empty();
$('#watermarks').empty();
$('#platform').empty();
$('#direct').empty();
}
this.addItems = function (transaction) {
this.addGroup = function (id, title, border = true) {
$('#' + id).append('
' + title + '
').append('
').removeClass('hidden');
if (border) {
$('#' + id).append($(''));
}
return $('#' + id + ' dl');
}
// transaction
var eltransaction = this.addGroup('etransaction', ' Ebook');
var identification = this.addGroup('identification', ' Identification');
this.addItem(eltransaction,'Master file', transaction.OriginalFilename);
if (transaction.Stored === '1') {
this.addItem(eltransaction, 'Stored file', 'Yes');
} else {
this.addItem(eltransaction, 'Stored file', 'No');
}
if (transaction.Source === 'dashboard') {
this.addItem(eltransaction, 'Source', 'Dashboard');
} else {
this.addItem(eltransaction, 'Source', 'API');
}
var d = new Date(transaction.DateTime);
var localdate = formatLocalISODate(d);
var utcdate = formatDisplayUTCDate(d);
var datetime = '';
this.addItem(eltransaction,'Date / Time (UTC)', datetime);
this.addItem(eltransaction, 'Language', transaction.LanguageCode + ' / ' + languages[transaction.LanguageCode]);
this.addItem(identification,'UID', transaction.UID);
this.addItem(identification,'Reference', transaction.ReferenceID);
if (transaction.CustomerName != null) {
this.addItem(identification,'Customer Name',transaction.CustomerName);
}
if (transaction.CustomerEmailAddress != null) {
this.addItem(identification,'Customer Email',transaction.CustomerEmailAddress);
}
// Watermarks
if(transaction.ExLibris != null || transaction.ExLibrisFile != null || transaction.ChapterFooter != null || transaction.Disclaimer != null || transaction.ShowDate != null) {
var watermarks = this.addGroup('watermarks', ' Watermarks');
if (transaction.ExLibris != null) {
this.addItem(watermarks,'Ex Libris', transaction.ExLibris == 1 ? 'Yes' : 'No');
}
if (transaction.ExLibrisFile != null) {
this.addItem(watermarks,'Ex Libris File', transaction.ExLibrisFile);
}
if (transaction.ChapterFooter != null) {
this.addItem(watermarks,'Chapter Footer', transaction.ChapterFooter == 1 ? 'Yes' : 'No');
}
if (transaction.Disclaimer != null) {
this.addItem(watermarks,'Disclaimer', transaction.Disclaimer == 1 ? 'Yes' : 'No');
}
if (transaction.ShowDate != null) {
this.addItem(watermarks, 'Show Date', transaction.ShowDate == 1 ? 'Yes' : 'No');
}
}
// BooXtream Platform
// determine if ebook was created with platform or direct stream
if (transaction.DeliveryPlatform != null && transaction.DeliveryPlatform === '1') {
var platform = this.addGroup('platform', ' Download links');
var editButton = $('').addClass('btn btn-primary pull-right').attr('id', 'editavailability-button').text('Edit availability'); //
// disable editButton 730 days after transaction.DateTime or when the request failed
var dateLimit = new Date(transaction.DateTime);
dateLimit.setDate(dateLimit.getDate() + 730);
var currentDate = new Date();
if (currentDate > dateLimit) {
editButton = $('').addClass('btn btn-primary pull-right').attr('disabled', 'disabled').text('Cannot reactivate transactions older than 730 days');
} else if (transaction.Status != null && transaction.Status === 'failed') {
editButton = $('').addClass('btn btn-primary pull-right').attr('disabled', 'disabled').text('Cannot reactivate transactions with an error.');
}
$('#platform').prepend(editButton);
var d = new Date(Date.UTC(transaction.ExpireDate.substr(0,4), (transaction.ExpireDate.substr(5,2) - 1), transaction.ExpireDate.substr(8,2), 0, 0, 0));
// format dates
var utcdate = formatDisplayUTCDate(d);
var localdate = formatLocalISODate(d);
var expirydate = '';
// show expiry date and number of downloads, including renewButton and resetButton
this.addItem(platform, 'Expiry Date (UTC)', '
' + expirydate +'
');
this.addItem(platform, 'Remaining downloads', (transaction.DownloadLimit - transaction.TotalDownloads) + ' (of ' + transaction.DownloadLimit + ')');
// evaluate Status and DeliveryStatus
// transaction.Status can be: processing, completed, failed
// transaction.DeliveryStatus (with transaction.DeliveryPlatform) can be: ok, limitreached, expired
var status = '';
if (transaction.Status != null) {
if (transaction.Status === 'failed') {
status += ' Error';
} else if (transaction.Status === 'processing') {
status += ' Processing';
} else {
switch (transaction.DeliveryStatus) {
case 'ok':
status += ' Available for download';
break;
case 'expired':
status += ' Unavailable: Expiry date reached';
break;
case 'limitreached':
status += ' Unavailable: Download limit reached';
break;
}
}
this.addItem(platform, 'Status', status);
platform.append($(' '));
}
// Download links
// @todo: geef credentials mee, zodat geen inlogscherm
if (transaction.DownloadLinks != null) {
var downloadlinks = '
';
$.each(transaction.DownloadLinks, function (i, val) {
downloadlinks += val + ' ';
});
downloadlinks += '
';
// append it all
platform.append($(downloadlinks));
platform.append($(''));
}
// check for downloads; add downloads
if (transaction.Downloads.length > 0) {
platform.append($('
Download history
'));
var table = $('
').addClass('table table-condensed');
platform.append(table);
var th = $('
');
th.append($('
Date / Time (UTC)
'));
th.append($('
IP Address
'));
th.append($('
Type
'));
table.append(th);
$.each(transaction.Downloads, function (i, val) {
// in the past, val.DownloadType was not always specified, but we don't want to show 'null'
var type = '';
if (val.DownloadType != null) {
type = val.DownloadType;
}
var d = new Date(val.DateTime);
var utcdate = formatDisplayUTCDate(d);
var localdate = formatLocalISODate(d);
var tr = $('
');
tr.append('
');
tr.append('
' + val.IpAddress + '
');
tr.append('
' + type + '
');
table.append(tr);
});
}
// activate modal on edit-button
$('#editavailability-button').click(function (e) {
// names of the months for error message text, to avoid date formatting (20-08-2021, 08/20/2021, etc)
const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
// calculate days between dates: translate dates to miliseconds, and miliseconds to number of days
// be aware: the dates have local timezones, but that should not matter for the difference in days
var transactiondate = new Date(transaction.DateTime);
transactiondate.setHours(0,0,0,0);
var expirydate = new Date(transaction.ExpireDate);
expirydate.setHours(0,0,0,0);
var today = new Date();
today.setHours(0, 0, 0, 0);
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
// calculate numbers for datepicker explanation text
var expiry_from_transaction_date = Math.round((expirydate.getTime() - transactiondate.getTime()) / (24 * 60 * 60 * 1000));
if (expiry_from_transaction_date > 1) {
expiry_from_transaction_date = expiry_from_transaction_date + ' days';
} else {
expiry_from_transaction_date = expiry_from_transaction_date + ' day';
}
var explanation = 'Expired ' + expiry_from_transaction_date + ' from transaction date.';
if (expirydate > today) {
var expiry_from_today = Math.round((expirydate.getTime() - today.getTime()) / (24 * 60 * 60 * 1000));
if (expiry_from_today > 1) {
expiry_from_today = expiry_from_today + ' days';
} else {
expiry_from_today = expiry_from_today + ' day';
}
explanation = 'Expires ' + expiry_from_transaction_date + ' from transaction date, ' + expiry_from_today + ' from today.';
}
// get maximum ExpiryDate for DatePicker (730 days after transaction date)
var maxdate = new Date(transactiondate.getTime() + (730 * 24 * 60 * 60 * 1000));
// get error message text
var errormessage = 'Please insert a date between tomorrow and ' + maxdate. getDate() + ' ' + monthNames[maxdate.getMonth()] + ' ' + maxdate. getFullYear();
// get number of downloads as minimum downloadlimit; use it when the form is submitted
var number_of_downloads = 0;
if (typeof transaction.Downloads !== 'undefined') {
number_of_downloads = transaction.Downloads.length;
}
// set the transaction date for calculation of a new explanation text, set the downloadlimit for calculating the final downloadlimit after submit
$('#editavailabilityform').data('transactiondate', transactiondate).data('number_of_downloads', number_of_downloads);
// set datepicker at expiry date; available dates: all dates from today until max expiry date
$('#datepicker').datepicker('setDate', expirydate)
.datepicker('option', 'minDate', tomorrow)
.datepicker('option', 'maxDate', maxdate)
.datepicker('option', 'dateFormat', 'yy-mm-dd')
.addClass('placeholder_layout');
$('#datepicker_explanation').html(explanation);
$('#datepicker_errormessage').html(errormessage);
var remaining = transaction.DownloadLimit - transaction.Downloads.length;
if (remaining < 0) {
remaining = 0;
}
$('#new_downloadlimit').val('').attr('placeholder', 'Remaining downloads: '+remaining);
$('#editavailabilitymodal .modal-body .alert').remove();
$('#editavailabilitymodal .modal-footer .submit').show();
$('#editavailabilitymodal .modal-footer .dismiss').text('Cancel');
$('#editavailabilitymodal').modal();
});
} else {
var direct = this.addGroup('direct', ' BooXtream Direct');
if (transaction.Status === 'failed') {
var status = ' Error';
} else if (transaction.Status === 'processing') {
var status = ' Processing';
} else {
// if ebook was created with direct stream, by default status = ok
if (transaction.Epub != null) {
this.addItem(direct, 'Generated', 'epub');
} else {
if (transaction.Mobi != null) {
this.addItem(direct, 'Generated', 'mobi');
}
}
var status = ' OK';
}
this.addItem(direct, 'Status', status);
}
// Technical details (only if there is a plugin callback url)
if (transaction.CallbackUrl != null) {
var tech = this.addGroup('tech', ' Technical details');
this.addItem(tech, 'Callback Url', transaction.CallbackUrl);
}
if (transaction.Errors && transaction.Errors.length > 0) {
var errors = this.addGroup('errormessages', '
Errors', false);
var table = $('
').addClass('table table-condensed').attr('style', 'margin-bottom: 0px;');
var th = $('
');
th.append($('
Code
'));
th.append($('
Description
'));
table.append(th);
$.each(transaction.Errors, function (i, val) {
var Code = parseInt(val.Code);
switch(Code) {
case 51:
Code += ': WordPress plugin error; please contact Support';
break;
case 400:
Code += ': Bad Request';
break;
case 405:
Code += ': Not Allowed';
break;
case 409:
Code += ': Conflict';
break;
case 412:
Code += ': Precondition Failed';
break;
case 422:
Code += ': Unprocessable Entity';
break;
default:
if(Code >= 1000) {
Code = Code - 1000;
Code += ': Callback failed; ebook watermarked successfully, but BooXtream is unable to respond to the callback url';
}
break;
}
var tr = $('
'));
$('#editavailabilitymodal .modal-footer .submit').hide();
$('#editavailabilitymodal .modal-footer .dismiss').text('Close');
return false;
});
}
// Prevent default click.
return false;
});
}
this.initialize();
}
// Credits
function Accounting() {
"use strict";
var op = this;
this.displayCreditOrders = function () {
$.getJSONAuth(baseurl + creditordersmethod, function (data) {
// show creditorders
$('#creditorders-tbody').children('.datarow').remove();
var costs = data.message.response;
// filter by selectedYear
var selectedYear = getSelectedYear();
costs = costs.filter(function (val) {
return new Date(val.DateTime).getFullYear() === selectedYear;
});
$.each(costs, function (i, val) {
if (val.OrderType === 'Credit order') {
// invoice numbers consisting a number of zero's have special meaning; check if invoice is not 0 or not null
var invoiceZerosCheck = parseInt(val.Invoice);
if (invoiceZerosCheck === 0 || val.Invoice === null) {
var downloadLink = '';
} else {
downloadLink = val.Invoice + ' ';
}
// format date, payment received
var d = new Date(val.DateTime);
var datetimeutcdate = formatDisplayUTCDate(d).split(' ')[0];
var paymentreceivedutcdate = '';
if (val.PaymentReceived != null) {
var d = new Date(val.PaymentReceived);
paymentreceivedutcdate = formatDisplayUTCDate(d).split(' ')[0];
}
// create table row
var tr = $('
').addClass('datarow');
tr.append($('
'));
tr.append($('
' + val.Credits + '
'));
tr.append($('
' + val.Amount + ' ' + val.Currency + '
'));
tr.append($('
'));
tr.append($('
' + downloadLink + '
'));
tr.append($('
' + paymentreceivedutcdate + '
'));
tr.append($('
' + val.ClientOrderID + '
'));
// append table row
$('#creditorders-tbody').append(tr);
}
});
// add download button
downloadInvoice();
});
}
this.showAccounts = function () {
var op = this;
var modaldata = {};
$.getJSONCache(baseurl + accountsmethod, function (data) {
$('#accounts-tbody').children('.datarow').remove();
$.each(data.message.response, function (i, val) {
var tr = $('
').addClass('datarow');
// when testaccount, give accountname and creditsused different layout
if (parseInt(val.Demo) === 1) {
tr.append($('
' + val.AccountName + ' (test account)
'));
tr.append($('
' + val.CreditsUsed + ' (free)
'));
} else {
tr.append($('
' + val.AccountName + '
'));
tr.append($('
' + val.CreditsUsed + '
'));
}
var numberOfFiles = '';
var totalFileSize = '';
// checks for number and size of stored files
if (typeof val.NumberOfFiles !== 'undefined') {
// convert size in bytes into megabytes, or (if the total size is equal to or more than 1 GB) into gigabytes
var totalFileSize = (parseInt(val.TotalFileSize) / (1024 * 1024)).toFixed(2);
if (totalFileSize >= 1024) {
totalFileSize = (parseInt(totalFileSize) / 1024).toFixed(2) + ' GB';
} else {
totalFileSize = totalFileSize + ' MB';
}
numberOfFiles = val.NumberOfFiles;
} else if (val.FTPuploadUser != null && val.FTPuploadUser != '') {
// display zeros when StoredFiles is enabled but no files are stored yet
var numberOfFiles = 0;
var totalFileSize = 0;
}
// expiredays
// discount factor
// kindlegen / calibre
tr.append($('
' + numberOfFiles + '
'));
if (parseInt(val.Demo) === 1) {
tr.append($('
');
modaldata[val.LoginName] = {
'loginname': val.LoginName,
'accesskey': val.AuthenticationKey,
'ftpuser': val.FTPuploadUser,
'ftppass': val.FTPuploadPassword
}
// place icons of the most used functions to the right
if (val.CopyrightHubClientID) {
settings.append('ARDITO enabled ');
}
if (val.Batcher != null && parseInt(val.Batcher) === 1) {
if (val.Mailing != null && parseInt(val.Mailing) === 1) {
settings.append(' ');
}
settings.append(' ');
}
if (val.Decoder != null && parseInt(val.Decoder) === 1) {
settings.append(' ');
}
if (val.FTPuploadUser != null && val.FTPuploadUser != '') {
settings.append(' ');
}
if (parseInt(val.CustomDisclaimer) === 1) {
settings.append(' ');
}
settings.append(' ');
tr.append(settings);
$('#accounts-tbody').append(tr);
});
// modals
$('tr.datarow td a.credentials').click(function () {
var credentials = modaldata[$(this).data().account];
var html = $('
');
html.append($('
API User Name
' + credentials.loginname + '
'));
html.append($('
API Access Key
' + credentials.accesskey + '
'));
$('#credentials .modal-body').html(html);
if(credentials.ftppass != null) {
var html = $('
');
html.append($('
Ftp Server
ftp://upload.booxtream.com
'));
html.append($('
Ftp User Name
' + credentials.ftpuser + '
'));
html.append($('
Ftp Password
' + credentials.ftppass + '
'));
$('#credentials .modal-body').append(html);
}
$('#credentials').modal();
});
});
// add tooltips
$('tr.datarow [data-toggle~="tooltip"]').tooltip();
// add popovers
$('tr.datarow [data-toggle~="popover"]').popover({
placement: 'top',
html: true,
trigger: 'hover'
});
}
this.resetSelectedYear = function () {
$(document).ready(function() {
var referrer = document.referrer;
referrer = referrer.slice(-14);
if (!['rkingcosts.php', 'oragecosts.php', 'ilingcosts.php'].includes(referrer)) {
// reset stored selectedYear
sessionStorage.removeItem('selectedYearAccounting');
$('#selectedYear').html(new Date().getFullYear());
}
});
}
this.initialize = function () {
// initialize page
var oPage = new Page();
this.displayCreditOrders();
this.showAccounts();
this.resetSelectedYear();
showCredits();
setYear();
// when the yearSelector dropdown is clicked on this page, reload display creditorders
$('#yearSelector li').on('click', function(){
op.displayCreditOrders();
});
}
this.initialize();
}
function StoredFiles() {
"use strict";
this.Accounts = [];
this.accountname = null;
this.batcheraccount = null;
this.accountkey = null;
this.pages = undefined;
this.page = undefined;
this.activesearch = false;
this.sURL = undefined;
this.CopyrightHubClientID = undefined;
this.MetadataModalID = undefined;
this._ignoreHashChange = false;
this.limit = localStorage.getItem("limit");
this.files = null;
this.keysandfiles = [];
if (this.limit == null) {
this.limit = 100;
}
this.processingEpubs = 0;
this.maxProcessingEpubs = 10;
this.firstValidationTimeout = 5000;
this.validationTimeout = 2000;
var op = this;
this.displayStoredFiles = function(storedFiles, total, size) {
// convert size in bytes into megabytes, or (if the total size is equal to or more than 1 GB) into gigabytes
var totalsize = (parseInt(size) / (1024 * 1024)).toFixed(2);
if (totalsize >= 1024) {
totalsize = (parseInt(totalsize) / 1024).toFixed(2) + ' GB';
} else {
totalsize = totalsize + ' MB';
}
this.pages = Math.ceil(total / this.limit);
// show total stored files
if (total === '1') {
$('.storedfiles-total').text('1 file, ' + totalsize);
} else {
$('.storedfiles-total').text(total + ' files, ' + totalsize);
}
// create table
var op = this;
$.each(storedFiles, function (i, val) {
// format data
var filename = getCellHTML('Filename', val.FileName, 80, true);
var datetime = '';
var title = getCellHTML('Title', op.setTitle(val), 40, false);
var filesize = (parseInt(val.FileSize) / (1024 * 1024)).toFixed(2) + ' MB';
// validation data and icons
var valid = $('');
if (val.StoredFileKey) {
var messages = JSON.parse(val.EpubcheckMessages);
op.checkValidationStatus(valid, val.EpubcheckStatus, val.FileName, messages);
}
var validcell = $('
').append(valid);
// create row; give it a color when it has a StoredFileKey
var row = $('
').addClass('datarow').attr('id', 'id' + i);
if (!val.StoredFileKey) {
row.addClass('text-muted');
}
var checkcell = $('
');
var datetimecell = $('
' + datetime + '
');
var filesizecell = $('
' + filesize + '
');
var filenamecell = $('
' + filename + '
');
var isbncell = $('
' + op.setISBN(val) + '
');
var titlecell = $('
' + title + '
');
// give cells a tooltip when it has a StoredFileKey (avoid giving tooltips to the left checkbox and to the right 2 columns); make it clickabe
if (val.StoredFileKey) {
checkcell.attr('data-toggle', 'tooltip').attr('data-placement', 'top').attr('title', 'Click to edit/view metadata').addClass('clickable');
datetimecell.attr('data-toggle', 'tooltip').attr('data-placement', 'top').attr('title', 'Click to edit/view metadata').addClass('clickable').addClass('callMetadataModal');
filesizecell.attr('data-toggle', 'tooltip').attr('data-placement', 'top').attr('title', 'Click to edit/view metadata').addClass('clickable').addClass('callMetadataModal');
filenamecell.attr('data-toggle', 'tooltip').attr('data-placement', 'top').attr('title', 'Click to edit/view metadata').addClass('clickable').addClass('callMetadataModal');
isbncell.attr('data-toggle', 'tooltip').attr('data-placement', 'top').attr('title', 'Click to edit/view metadata').addClass('clickable').addClass('callMetadataModal');
titlecell.attr('data-toggle', 'tooltip').attr('data-placement', 'top').attr('title', 'Click to edit/view metadata').addClass('clickable').addClass('callMetadataModal');
}
// or make it clickable for showing a png
if ((val.FileName.substr(-4) == '.png')) {
checkcell.addClass('clickable');
datetimecell.addClass('clickable').addClass('callPNGModal text-nowrap');
filesizecell.addClass('clickable').addClass('callPNGModal text-nowrap');
filenamecell.addClass('clickable').addClass('callPNGModal');
isbncell.addClass('clickable').addClass('callPNGModal');
titlecell.addClass('clickable').addClass('callPNGModal');
}
// append data cells
row.append(checkcell);
row.append(datetimecell);
row.append(filesizecell);
row.append(validcell);
row.append(filenamecell);
row.append(isbncell);
row.append(titlecell);
var buttonsmetadata = $('
');
var buttonsaction = $('
');
// download button
buttonsaction.append('');
// make search-link and manual mode available when there is a StoredFileKey
if (val.StoredFileKey) {
if (val.StoredFileKey.slice(-5) === '.epub') {
if (val.EpubcheckStatus === null) {
op.addValidateButton(validcell, val.FileName, validcell);
}
}
row.data('modalData', val);
if (val.Metadata != null) {
var md = val.Metadata;
// check for custom metadata
var custommetadata = 0;
$.each(md, function (key, value) {
if (key !== 'DOI' && key !== 'HubKey' && key !== 'ISBN' && key !== 'Title') {
custommetadata = 1;
}
});
// add button for custom metadata
if (custommetadata == 1) {
op.custommetadatabutton(buttonsmetadata);
}
// add button for hubkey (if this account has a CopyrightHubClientID)
if (op.CopyrightHubClientID !== undefined && md.HubKey !== undefined && md.HubKey !== null && md.HubKey.length > 0) {
op.arditobutton(buttonsmetadata);
}
// add button for doi
if (op.setDOI(val).length > 0) {
op.doibutton(buttonsmetadata);
}
}
// show action icons
buttonsaction.append(' ');
buttonsaction.append(' Watermark this ebook');
if (op.batcheraccount) {
buttonsaction.append(' Watermark in batch mode');
}
}
// otherwise, when png: show modal with png
if (val.PreSignedUrl) {
row.data('modalData', val);
}
// add button cells
row.append($(buttonsmetadata));
row.append($(buttonsaction));
$(buttonsaction).find('*[data-toggle="tooltip"]').tooltip();
$('#storedfiles-tbody').append(row);
return i < (op.limit - 1);
});
// calculate pages from total and limit and then add pagination
op.displayPagination();
// add functionality for downloadbutton
$('a.downloadbutton').click(function(event) {
event.preventDefault();
// try to get authentication from sessionstorage
var authentication = sessionStorage.getItem("authentication");
// or try to get it from localstorage
if (authentication === null) {
authentication = localStorage.getItem("authentication");
}
// create form
var form = $('');
form.append('');
form.append('');
form.append('');
$(this).after(form);
// submit and remove form
form.submit();
form.remove();
});
// add popovers
$('tr.datarow [data-toggle~="popover"]').popover({
placement: 'top',
html: true,
trigger: 'hover'
});
// color datarow and check checkbox when cell with checkbox is clicked
$('td.checkCell').click(function() {
var checkbox = $(this).find('input.checkBox');
var checked = checkbox.is(':checked');
if (checked) {
checkbox.prop('checked', false);
$(this).parent().removeClass('success');
} else {
checkbox.prop('checked', true);
$(this).parent().addClass('success');
}
op.allowDeleteButton();
});
// color datarow when chechbox is checked
$('input.checkBox').click(function() {
var checked = $(this).is(':checked');
if (checked) {
$(this).prop('checked', false);
$(this).parent().parent().removeClass('success');
} else {
$(this).prop('checked', true);
$(this).parent().parent().addClass('success');
}
op.allowDeleteButton();
});
// enable MetadataModal
$('.callMetadataModal').click(function() {
op.MetadataModalID = $(this).parent().attr('id');
op.showMetadataModal();
});
// enable PNGModal
$('.callPNGModal').click(function() {
var id = $(this).parent().attr('id');
var data = $('tr#' + id).data('modalData');
$('#showfilename').attr('value', data.FileName);
$('#exlibrisimage').attr('src', data.PreSignedUrl);
$('#showPNGModal').modal('show');
});
}
// get general metadata (doi, hubkey, isbn, title)
this.setDOI = function(data) {
var doi = '';
if (data.Metadata !== null && data.Metadata !== undefined && data.Metadata.DOI !== null && data.Metadata.DOI.length > 0) {
doi = data.Metadata.DOI;
}
return doi;
}
this.setISBN = function(data) {
var isbn = '';
if (data.Metadata !== null && data.Metadata !== undefined && data.Metadata.ISBN !== null && data.Metadata.ISBN.length > 0) {
isbn = data.Metadata.ISBN;
}
return isbn;
}
this.setTitle = function(data) {
var title = '';
if (data.Metadata !== null && data.Metadata !== undefined && data.Metadata.Title !== null && data.Metadata.Title.length > 0) {
title = data.Metadata.Title;
}
return title;
}
// add custom metadata input fields
this.addCustomMetadataInputFields = function() {
var op = this;
var metadatapair = $('').addClass('metadatapair');
var keyinput = $('').attr('type', 'text').addClass('form-control metadatakey').attr('placeholder', 'Key').attr('id', 'lastkey');
var valueinput = $('').attr('type', 'text').addClass('form-control metadatavalue').attr('placeholder', 'Value').attr('id', 'lastvalue');
metadatapair.append(keyinput).append(valueinput);
$('#custommetadata').append(metadatapair);
// if input fields are used, add new input fields
$('#lastkey').on('change keyup paste', function() {
if ($('#lastkey').val().length > 0) {
$('#lastkey').removeAttr('id');
$('#lastvalue').removeAttr('id');
op.addCustomMetadataInputFields();
}
});
$('#lastvalue').on('change keyup paste', function() {
if ($('#lastvalue').val().length > 0) {
$('#lastkey').removeAttr('id');
$('#lastvalue').removeAttr('id');
op.addCustomMetadataInputFields();
}
});
}
// make delete button clickable when files are checked
this.allowDeleteButton = function() {
var values = $('input:checkbox:checked.checkBox');
if (values.length > 0) {
$('.callDeleteModal').prop('disabled', false);
} else {
$('.callDeleteModal').prop('disabled', true);
}
}
this.showMetadataModal = function() {
// get data object from row; make id global
// var data = $('tr#' + id).data('modalData');
// op.MetadataModalID = id;
var data = $('tr#' + op.MetadataModalID).data('modalData');
// only show HubKey when this account has CopyrightHub-rights
if (op.CopyrightHubClientID !== undefined) {
$('.hubkeycontainer').removeClass('hidden');
}
$('#editfilename').val(data.FileName);
if (data.Metadata != null) {
$('#editisbn').val(op.setISBN(data));
$('#editdoi').val(op.setDOI(data));
$('#edithubkey').val(data.Metadata.HubKey);
$('#edittitle').val(op.setTitle(data));
}
$('#custommetadata').empty();
if (data.Metadata) {
$.each(data.Metadata, function (key, value) {
if (key !== 'DOI' && key !== 'HubKey' && key !== 'ISBN' && key !== 'Title') {
var metadatapair = $('').addClass('metadatapair');
var keyinput = $('').val(key);
var valueinput = $('').val(value);
metadatapair.append(keyinput).append(valueinput);
$('#custommetadata').append(metadatapair);
}
});
}
op.addCustomMetadataInputFields();
$('#editMetadataModal').modal('show');
}
// create page
this.getPage = function(pagenumber, search) {
var op = this;
startSpinner('#spinner');
this.page = parseInt(pagenumber);
var offset = (this.page - 1) * this.limit;
var storedfilestable = $('#tablecontainer table');
var storedfilestbody = $('#storedfiles-tbody');
$('#tablecontainer').append('
');
$('#messageTitle').replaceWith('Error');
$('#submit').prop('disabled', false);
},
success: function (data){
if (data.success == 1) {
$('#messagebox').addClass('panel-success');
$('#messageTitle').replaceWith('Completed');
} else {
$('#messagebox').addClass('panel-danger');
}
if (data.error !== undefined) {
$('#message .text-info').remove();
$('#message').append('
Error: ' + data.error + '
Please contact BooXtream
');
$('#messageTitle').replaceWith('Error');
}
if (data.processedRecords > 0) {
// split MySQL datetime strings and construct Javascript Date objects
var start = data.datetimeStart.split(/[- :]/);
var dateStart = new Date(start[0], start[1]-1, start[2], start[3], start[4], start[5]);
var end = data.datetimeEnd.split(/[- :]/);
var dateEnd = new Date(end[0], end[1]-1, end[2], end[3], end[4], end[5]);
// calculate time
var time = Math.round((dateEnd.getTime() - dateStart.getTime()) / 1000);
$('#message').append('
' + data.processedRecords + ' of ' + data.totalRecords + ' records processed in ' + time + ' seconds.
');
// try to get authentication from sessionstorage, we need this for CSV proxy
var authentication = sessionStorage.getItem("authentication");
// or try to get it from localstorage
if (authentication === null) {
authentication = localStorage.getItem("authentication");
}
}
}
});
return false;
});
}
// functionality for exlibris upload modal
this.handleBatchfile = function() {
Papa.DefaultDelimiter = ';';
var batchfile = $('#batchfile');
var confirmbutton = $('#batchfileconfirmbutton');
var batchfile = '';
var delimiter = '';
var op = this;
var confirm = $('#batchfileconfirm');
confirm.hide();
// choose file for upload
$('#batchfile').change(function(e) {
$('#batchfilepreview').hide();
$('#batchfilepreviewtable').empty();
// empty and hide error table
$('#batchfileerrors table tbody').empty();
$('#batchfileerrors').hide();
$('#batchfileconfirmbutton').prop('disabled', true);
$('#batchfileconfirm').hide();
filelist = $(this).get(0).files;
// secure invisibility of the uploadbutton when there is no file, or when file has not a .png-extension
if (filelist.length === 1) {
$('#uploadbatchfile').prop('disabled', false);
} else {
$('#uploadbatchfile').prop('disabled', true);
}
});
// set uploaded file
$('button#uploadbatchfile').click(function(e) {
e.preventDefault();
batchfile = $('#batchfile').get(0).files[0];
var firstRow = true;
var row = 0;
var table = $('#batchfilepreviewtable');
var errors = $('#batchfileerrors table tbody');
var errorsfound = false;
$('#batchfilepreview').show();
table.empty();
errors.empty();
confirmbutton.prop('disabled', false);
$('#batchfile').parse({
config: {
step: function (results, parser) {
error = '';
delimiter = results.meta.delimiter;
if (firstRow) {
// check the first row
header = results.data[0];
if (!(header.length === 3 && header[0] == 'customername' && header[1] == 'customeremailaddress' && header[2].trim() == 'referenceid')) {
error = 'Header is incorrect';
if(header.length !== 3) {
error += ', length should be 3 but is ' + header.length + '.';
} else {
error += ', it did not match the requirements.'
}
}
} else {
// check length of row
if (results.data[0].length != 3) {
error = 'Incorrect row length: ' + results.data[0].length;
}
}
if (row < 11) {
tablerow = $('
');
if (firstRow) {
tablerow.addClass('headerrow');
tablerow.append('
');
} else {
tablerow.append('
' + row.toString() + '
');
}
$.each(results.data[0], function (i, data) {
tablerow.append('
').click(function(event) {
$('#addTemplateName').val('Copy of ' + row.name);
$('#addTemplateSenderEmailAddress').val(row.from_email);
$('#addTemplateSenderName').val(row.from_name);
$('#addTemplateSubject').val(row.subject);
$('#addTemplateCode').val(row.code);
$('#addTemplate').modal('toggle');
});
$('#templatesdropdown').append(option);
}
this.checkNameExists = function(name) {
var op = this;
var data = {};
data['name'] = name;
var url = baseurl + 'account/' + this.accountkey + '/' + templatesexistsmethod;
return $.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + op.getAuthentication());
},
xhrFields: {
withCredentials: true
},
crossDomain: true,
type: 'POST',
url: url,
contentType: false,
processData: false,
data: JSON.stringify(data),
dataType: 'json'
});
}
this.validateUpdate = function() {
var op = this;
var message = '';
var name = $('#editTemplateName').val();
var emailaddress = $('#editTemplateSenderEmailAddress').val();
if (name.length === 0) {
message = 'Name is required';
}
message = op.checkEmailAddress(message, emailaddress);
if (message.length > 0) {
var messagebox = $('#editTemplateError');
messagebox.html(message);
messagebox.fadeIn('slow', function(){
messagebox.delay(5000).fadeOut();
});
return false;
}
return true;
}
this.initialize = function () {
this.oPage = new Page();
this.buttons();
var op = this;
// get key first
this.sURL = urlObject();
var accountname = this.sURL.parameters.account;
if(typeof accountname === "undefined") {
window.location = 'index.php';
}
this.accountname = accountname;
$('#accountname').html(this.accountname);
$.getJSONCache(baseurl + accountsmethod, function (data) {
var AccountNames = [];
var validaccount = false;
$.each(data.message.response, function (i,val) {
if(val.LoginName === accountname) {
validaccount = true;
$('#accountname').html(val.AccountName + (val.Demo === '1' ? ' (test account)' : ' (production account)'));
// redirect to home page when account does not have permission to view this page
// @todo: integer output instead of string
if (val.Batcher !== '1') {
window.location = 'index.php';
}
if (val.Mailing === 1) {
op.Mailing = true;
}
}
AccountNames[val.LoginName] = val.AccountName;
op.Accounts[val.LoginName] = val.AuthenticationKey;
});
if (!validaccount) {
window.location = 'index.php';
}
op.accountkey = op.Accounts[accountname];
// account loaded, get templates
op.getTemplates();
});
}
this.initialize();
}// Credits
function StorageCosts() {
"use strict";
var op = this;
this.displayStorageCosts = function () {
$.getJSONAuth(baseurl + creditordersmethod, function (data) {
$('#storagecosts-tbody').children('.datarow').remove();
// display the most recent first
var costs = data.message.response;
// filter by selectedYear
var selectedYear = getSelectedYear();
costs = costs.filter(function (val) {
return new Date(val.DateTime).getFullYear() === selectedYear;
});
$.each(costs, function (i, val) {
if (val.OrderType === 'Storage costs') {
// format date
var d = new Date(val.DateTime);
var datetimeutcdate = formatDisplayUTCDate(d).split(' ')[0];
// create table row
var tr = $('
').addClass('datarow');
tr.append($('
'));
tr.append($('
' + val.Credits + '
'));
tr.append($('
'));
tr.append($('
' + val.ClientOrderID + '
'));
// append table row
$('#storagecosts-tbody').append(tr);
}
});
});
}
this.initialize = function () {
var oPage = new Page();
this.displayStorageCosts();
showCredits();
setYear();
// when the yearSelector dropdown is clicked on this page, reload display storage costs
$('#yearSelector li').on('click', function(){
op.displayStorageCosts();
});
}
this.initialize();
}
// Credits
function MailingCosts() {
"use strict";
var op = this;
this.displayMailingCosts = function () {
$.getJSONAuth(baseurl + creditordersmethod, function (data) {
$('#storagecosts-tbody').children('.datarow').remove();
// display the most recent first
var costs = data.message.response;
// filter by selectedYear
var selectedYear = getSelectedYear();
costs = costs.filter(function (val) {
return new Date(val.DateTime).getFullYear() === selectedYear;
});
$.each(costs, function (i, val) {
if (val.OrderType === 'Mailing costs') {
// format date
var d = new Date(val.DateTime);
var datetimeutcdate = formatDisplayUTCDate(d).split(' ')[0];
// create table row
var tr = $('
').addClass('datarow');
tr.append($('
'));
tr.append($('
' + val.Credits + '
'));
tr.append($('
'));
tr.append($('
' + val.ClientOrderID + '
'));
// append table row
$('#storagecosts-tbody').append(tr);
}
});
});
}
this.initialize = function () {
var oPage = new Page();
this.displayMailingCosts();
showCredits();
setYear();
// when the yearSelector dropdown is clicked on this page, reload display mailing costs
$('#yearSelector li').on('click', function(){
op.displayMailingCosts();
});
}
this.initialize();
}
// Credits
function ScriptWatermarkingcosts() {
"use strict";
var op = this;
this.displayCreditUsage = function () {
$.getJSONAuth(baseurl + creditusagemethod, function (data) {
$('#creditusage-tbody').children('.datarow').remove();
// display the most recent first
var costs = data.message.response;
// filter by selectedYear
var selectedYear = getSelectedYear();
costs = costs.filter(function (val) {
return parseInt(val.year) === selectedYear;
});
$.each(costs, function (i, val) {
// get this year, this month
var this_year = new Date().getFullYear();
var this_month = new Date().getMonth();
this_month = this_month + 1;
// get prefix
var prefix_month = parseInt(val.month) + 1; // first, cast to integer and calculate
var prefix_year = parseInt(val.year);
if (prefix_month > 12) {
prefix_month = '01';
prefix_year = prefix_year + 1;
}
prefix_month = prefix_month.toString(); // now, cast to string and add leading zero
if (prefix_month.length === 1) {
prefix_month = '0' + prefix_month;
}
var prefix_day = '01';
// get postfix
var postfix_month = val.month;
if (postfix_month.length === 1) {
postfix_month = '0' + postfix_month;
}
// check if data is about current year, current month
var prefix = '';
var description = 'Total monthy watermark transactions';
if (val.year.toString() === this_year.toString() && val.month.toString() === this_month.toString()) {
description = 'Current watermark transactions';
} else {
prefix = prefix_year + '-' + prefix_month + '-' + prefix_day;
}
var postfix = val.year + '-' + postfix_month;
var value = '-' + val.value;
if (val.value == 0) {
value = val.value;
}
// create table row
var tr = $('
').addClass('datarow');
tr.append($('
' + prefix + '
'));
tr.append($('
' + value + '
'));
tr.append($('
'));
tr.append($('
' + description + ' ' + postfix + '
'));
// append table row
$('#creditusage-tbody').append(tr);
});
});
}
this.initialize = function () {
var oPage = new Page();
this.displayCreditUsage();
showCredits();
setYear();
// when the yearSelector dropdown is clicked on this page, reload display credit usage
$('#yearSelector li').on('click', function(){
op.displayCreditUsage();
});
}
this.initialize();
}