Embedded Extensions examples Tutorial 1

Documentation •
In this article

'Hello world' report

Hello World


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialhelloworld
// @description = Tutorial: Hello world
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Add a paragraph with some text
    report.addParagraph('Hello World!!!');

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Creating Reports

Add several paragraphs


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialaddseveralparagraphs
// @description = Tutorial: Add several paragraphs
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Add several paragraphs with some text
    report.addParagraph('This');
    report.addParagraph('is');
    report.addParagraph('a');
    report.addParagraph('text');
    report.addParagraph(' '); //Empty paragraph
    report.addParagraph('printed');
    report.addParagraph('on');
    report.addParagraph('several');
    report.addParagraph('paragraphs.');

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Add the header


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialheaderstyles
// @description = Tutorial: Add the header with some styles
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Add the header
    report.getHeader().addClass('header');
    report.getHeader().addText('This is the header text aligned to the right with a bottom border', 'header');

    //Add some style
    var stylesheet = Banana.Report.newStyleSheet();

    //Header style
    style = stylesheet.addStyle(".header");
    style.setAttribute("text-align", "right");
    style.setAttribute("border-bottom", "thin solid black");

    //Print the report
    Banana.Report.preview(report, stylesheet);

}

Add the footer


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialfooterstyles
// @description = Tutorial: Add the footer with some styles
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Add the footer with page numbers
    report.getFooter().addClass('footer');
    report.getFooter().addText('Banana Accounting, v. ' + Banana.document.info('Base', 'ProgramVersion'));
    report.getFooter().addText(' - Page' + ' ');
    report.getFooter().addFieldPageNr();

    //Add some style
    var stylesheet = Banana.Report.newStyleSheet();

    //Footer style
    style = stylesheet.addStyle(".footer");
    style.setAttribute("text-align", "right");
    style.setAttribute("font-size", "8px");
    style.setAttribute("font-family", "Courier New");

    //Print the report
    Banana.Report.preview(report, stylesheet);

}

Add an image


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialimage
// @description = Tutorial: Add an image
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Add an image stored in the document tabel
    report.addImage("documents:logo");

    //Add a png image passing the content of the image
    report.addImage("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAARqklEQVRogb2ZeVRT1/bHT9+TgiKTIiiCgAMig0wm997MzKKiOHR4WgdAUAhgRQWnIn1Pa21r+161Uu3wfG0d2tfqs1a7bJkHAyGQhJAACSQEUQZFxalWge/vj6AFoVZb+9trfde6f9yz92fvs885dyDkD1i87QTXLRMnLXnDbfLrh6d7f3TSa+aRr718P8+Z6rlv40SX9I3OzqIkm0l2fyTGMzURISPEjhNDd7tNffOIp09hgV9QmyyIgpJFQzVAilkUpIHs3ryZAReOePrk73Bx35vu5DLfnxDb3xPX3cHScXMc68cXhFMOEkKe+z0+nlvrMGHhN14z86RB7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GBn7GFuh/4s2/mB8/plYRGQxo2H9Lw+SgPi4Y0dD4kYdHIXRGDwv/EoqFqA1qqMmEo3wR9+UYYJBthLM9AS/lmGCXboCvYgtLjq7tytgZX/i3c5Q2HMYQhhJg9c/ABZjbZ3Hqaj41NBGU7Lnaek3N2grvHZ1leAbmHAjmad3wp2eJprkfXLvM9dWBnhOTY3ui6E/sXNZ/+cOGFU/tjjEffnqM9mB1W+Y9U7vcJC70+DJk1LsV9wgg+ecyv1P8Pe86eECsLQlyJ6R+xmRshFlZWxN7CgriPHk1m2I0mPmNGE29zczKFEOLoRMioPxPo/wBFxyrdFyIbZQAAAABJRU5ErkJggg==");

    //Add a svg image passing the content of image
    report.addImage('data:image/svg;utf8,<svg version="1.2" baseProfile="tiny" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:a="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/" x="0px" y="0px" width="337px" height="82px" viewBox="0 0 337 82" xml:space="preserve"><defs></defs><path fill="#234571" d="M16.737,0c5.755,0,9.592,3.309,9.592,8.151c0,3.453-2.973,6.38-5.803,6.906c3.405,0.191,8.105,3.405,8.105,8.632c0,5.947-4.172,9.881-10.839,9.881H4.651V0H16.737z M16.209,14.1c4.412,0,7.337-2.35,7.337-5.851s-2.925-5.755-7.337-5.755H7.48v11.604L16.209,14.1L16.209,14.1z M17.648,31.078c4.556,0,8.104-2.734,8.104-7.242c0-4.221-3.836-7.29-8.393-7.29H7.48v14.532H17.648z"/><path fill="#234571" d="M59.56,24.076H39.514l-4.844,9.495h-3.069L48.77,0.001h1.535l17.169,33.57h-3.069L59.56,24.076z M58.218,21.438L49.873,4.989l-0.336-0.863l-0.335,0.863l-8.345,16.448L58.218,21.438L58.218,21.438z"/><path fill="#234571" d="M100.178,0v33.568H97.54L76.678,5.801l-0.671-1.007l0.096,1.391v27.387h-2.83V0.001h2.638l20.91,27.672l0.624,1.055l-0.096-1.438V0H100.178z"/><path fill="#234571" d="M132.833,24.076h-20.047l-4.844,9.495h-3.069l17.169-33.57h1.535l17.168,33.57h-3.068L132.833,24.076z M131.492,21.438L123.145,4.99l-0.336-0.863l-0.334,0.863l-8.346,16.448H131.492z"/><path fill="#234571" d="M173.452,0v33.568h-2.638L149.954,5.8l-0.672-1.007l0.096,1.391v27.387h-2.83V0.001h2.64l20.91,27.672l0.623,1.055l-0.097-1.438V0H173.452z"/><path fill="#234571" d="M206.105,24.076h-20.047l-4.844,9.495h-3.068l17.168-33.57h1.535l17.17,33.57h-3.067L206.105,24.076z M204.762,21.438L196.416,4.99l-0.336-0.863l-0.336,0.863L187.4,21.438H204.762z"/><path fill="#234571" d="M26.376,75.723H10.934l-1.966,4.316H0l15.826-33.57h5.659l15.826,33.57h-8.968L26.376,75.723z M22.972,68.193l-3.837-8.486l-0.479-1.344l-0.479,1.344l-3.837,8.486H22.972z"/><path fill="#234571" d="M61.334,56.875c-1.535-1.918-4.412-3.117-7.05-3.117c-5.563,0-9.016,3.98-9.016,9.496c0,5.803,3.789,9.398,9.016,9.398c3.213,0,6.283-1.633,7.673-3.934l8.153,2.109c-2.781,5.945-8.776,9.88-15.826,9.88c-9.64,0-17.409-7.338-17.409-17.457s7.769-17.457,17.409-17.457c6.618,0,12.277,3.55,15.251,8.92L61.334,56.875z"/><path fill="#234571" d="M97.012,56.875c-1.535-1.918-4.412-3.117-7.05-3.117c-5.563,0-9.016,3.98-9.016,9.496c0,5.803,3.789,9.398,9.016,9.398c3.213,0,6.283-1.633,7.673-3.934l8.153,2.109c-2.781,5.945-8.776,9.88-15.826,9.88c-9.64,0-17.409-7.338-17.409-17.457s7.769-17.457,17.409-17.457c6.618,0,12.277,3.55,15.251,8.92L97.012,56.875z"/><path fill="#234571" d="M125.64,45.797c9.642,0,17.457,7.338,17.457,17.457s-7.815,17.457-17.457,17.457c-9.64,0-17.409-7.338-17.409-17.457S116,45.797,125.64,45.797z M125.64,72.749c5.467,0,9.064-3.884,9.064-9.495c0-5.658-3.598-9.496-9.064-9.496c-5.418,0-9.016,3.838-9.016,9.496C116.623,68.865,120.22,72.749,125.64,72.749z"/><path fill="#234571" d="M178.102,46.469v18.655c0,10.069-6.232,15.587-15.104,15.587c-8.922,0-15.106-5.518-15.106-15.587V46.469h8.057v18.943c0,4.796,2.637,7.77,7.051,7.77c4.412,0,7.049-2.974,7.049-7.77V46.469H178.102z"/><path fill="#234571" d="M214.645,46.469v33.57h-7.58l-13.905-17.938l-0.671-1.248l0.097,1.248v17.938h-8.06v-33.57h7.576l13.908,17.696l0.672,1.247l-0.098-1.247V46.469H214.645z"/><path fill="#234571" d="M247.204,46.469v7.529h-10.218v26.041h-8.059v-26.04h-10.068v-7.53H247.204L247.204,46.469z"/><path fill="#234571" d="M251.418,80.04V46.469h8.061v33.57L251.418,80.04L251.418,80.04z"/><path fill="#234571" d="M297.077,46.469v33.57h-7.578L275.59,62.102l-0.67-1.248l0.096,1.248v17.938h-8.057v-33.57h7.576l13.908,17.696l0.672,1.247l-0.098-1.247V46.469H297.077z"/><path fill="#234571" d="M329.008,77.307c-1.965,2.109-5.317,3.404-9.106,3.404c-9.644,0-17.408-7.338-17.408-17.457s7.77-17.457,17.408-17.457c6.52,0,12.229,3.453,15.25,8.92l-8.199,2.158c-1.584-1.918-4.412-3.117-7.051-3.117c-5.562,0-9.021,3.98-9.021,9.496c0,5.896,3.98,9.592,9.496,9.592c5.371,0,7.725-2.781,8.684-5.273v-0.051h-8.823v-6.474h15.682v18.991h-6.906v-2.732H329.008L329.008,77.307z"/></svg>');

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    stylesheet.addStyle("img", "margin-bottom:4em");
    Banana.Report.preview(report, stylesheet);

}

Add page break


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialpagebreak
// @description = Tutorial: Page break
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Add a paragraph with some text
    report.addParagraph('Hello');

    //Add a page break
    report.addPageBreak();

    //Add an other paragraph 
    report.addParagraph('World!!!');

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Add attachments


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialattachments
// @description = Tutorial: Attachments
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report attachments');

    //Add a paragraph with some text
    report.addParagraph('Report with attachments');

    //Attach text files created on the fly
    //We use the prefix 'data:...' to tell that the string is not an url but is itself the content of the file
    report.addAttachment('text file 1.txt', 'data:text/plain;utf8,This is the content of the text file 1.');
    report.addAttachment('text file 2.txt', 'data:text/plain;utf8,This is the content of the text file 2.');
    report.addAttachment('text file 3.txt', 'data:text/plain;utf8,This is the content of the text file 3.');

    //Attach an image stored in the document table
    //We use the prefix 'document:...'
    report.addAttachment('logo.jpg', 'documents:logo');

    //Add an xml element
    //We just add the new created Banana.Xml.newDocument
    var xmlDocument = Banana.Xml.newDocument("eCH-0217:VATDeclaration");
    var rootNode = xmlDocument.addElement("eCH-0217:VATDeclaration");
    rootNode.addElement("title").addTextNode("Vat Declaration 2018");
    report.addAttachment('vat_declaration.xml', xmlDocument);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);
}

Print multiple reports


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialmultiplereports
// @description = Tutorial: Multiple reports
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
	var docs = [];
	var styles = [];
	
	// Report
	for (var i = 0; i < 10; i++) {
		var report = Banana.Report.newReport("Report title");
		report.addParagraph("Hello World #" + i + " !!!", "styleHelloWorld");
		report.setTitle("Document " + i);
		report.getFooter().addFieldPageNr();
		docs.push(report);

		// Styles
		var stylesheet = Banana.Report.newStyleSheet();
		var style = stylesheet.addStyle(".styleHelloWorld");
		style.setAttribute("font-size", "24pt");
		style.setAttribute("text-align", "center");
		style.setAttribute("margin-top", "10mm");
		var style2 = stylesheet.addStyle("@page");
		style2.setAttribute("size", "landscape");
		styles.push(stylesheet);
	}

	// Print preview of 10 documents together
	Banana.Report.preview("Multi documents printing example", docs, styles);
}

Add structured text


// Banana Accounting Extension Javascript
// @api = 1.2.0
// @id = ch.banana.uni.app.tutorialstructuredtext
// @description = Hello world
// @task = app.command
// @doctype = nodocument
// @publisher = Publisher name
// @pubdate = 2022-05-31
// @inputdatasource = none
// @timeout = -1

function exec() {

    //Create the report and the stylesheet
    var report = Banana.Report.newReport('Tutorial Banana.ReportElement.addStructuredText');
    var stylesheet = Banana.Report.newStyleSheet();
    stylesheet.addStyle(".example", "margin-top: 2em; margin-bottom: 0.5em; font-style: italic;");

    report.addParagraph("--- Markdown example ---", "example");

    let mdText = "# Header 1\n";
    mdText += "## Header 2\n";
    mdText += "### Header 3\n";
    mdText += "Markdown text with **bold** and *italic*.  \n";
    mdText += "[Markdown link](https://www.banana.ch)  \n";
    mdText += "* List row 1\n";
    mdText += "* List row 2\n";
    mdText += "* List row 3\n";
    report.addStructuredText(mdText, "md");
    
    report.addParagraph("--- Simple html example ---", "example");

    let htmlText = "<h1 style=\"color: purple\">Header 1</h1>\n";
    htmlText += "<p style=\"color: blue\">Paragraph</p>\n";
    report.addStructuredText(htmlText, "html");

    report.addParagraph("--- Full html example ---", "example");

    htmlText = "<html>\n";
    htmlText += "<head>\n";
    htmlText += "<style>\n";
    htmlText += "p.green {color: green;}\n";
    htmlText += ".red {color: red;}\n";
    htmlText += "</style>\n";
    htmlText += "</head>\n";
    htmlText += "<body>\n";
    htmlText += "<h1 class=\"red\">Header 1</h1>\n";
    htmlText += "<p class=\"green\">Paragraph</p>\n";
    htmlText += "</body>\n";
    htmlText += "</html>\n";
    report.addStructuredText(htmlText, "html", stylesheet);

    report.addParagraph("--- Plain html example ---", "example");

    let plainText = "Testo riga 1\n";
    plainText += "Testo riga 2\n";
    plainText += "Testo riga 3\n";
    report.addStructuredText(plainText, "text");	

    //Print the report
    Banana.Report.preview(report, stylesheet);

}

Creating Reports with table object

Create a table with one row


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialtableonerow
// @description = Tutorial: Create a table with one row
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Create a table
    var table = report.addTable('myTable');

    //Add a row
    tableRow = table.addRow();
    tableRow.addCell('Cash');
    tableRow.addCell('1200');

    //Create style
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Create a table with multiple rows


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialtablemultiplerows
// @description = Tutorial: Create a table with multiple rows
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Create a table
    var table = report.addTable('myTable');

    //Add row 1
    tableRow = table.addRow();
    tableRow.addCell('Cash');
    tableRow.addCell('1200');

    //Add row 2
    tableRow = table.addRow();
    tableRow.addCell('Bank 1');
    tableRow.addCell('500');

    //Add row 3
    tableRow = table.addRow();
    tableRow.addCell('Bank 2');
    tableRow.addCell('2600');

    //Print report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Create a table with multiple rows and a header


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialtablewithheader
// @description = Tutorial: Create a table with multiple rows and header
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Create a table
    var table = report.addTable('myTable');

    //Create table header
    var tableHeader = table.getHeader();

    //Add the header of the table
    tableRow = tableHeader.addRow();
    tableRow.addCell('Description');
    tableRow.addCell('Amount');

    //Add row 1
    tableRow = table.addRow();
    tableRow.addCell('Cash');
    tableRow.addCell('1200');

    //Add row 2
    tableRow = table.addRow();
    tableRow.addCell('Bank 1');
    tableRow.addCell('500');

    //Add row 3
    tableRow = table.addRow();
    tableRow.addCell('Bank 2');
    tableRow.addCell('2600');

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Create a table with multiple rows, header and borders


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialtablewithheaderandborders
// @description = Tutorial: Create a table with multiple rows, header and borders
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Create a table
    var table = report.addTable('myTable');

    //Create table header
    var tableHeader = table.getHeader();

    //Add the header of the table
    tableRow = tableHeader.addRow();
    tableRow.addCell('Description');
    tableRow.addCell('Amount');

    //Add row 1
    tableRow = table.addRow();
    tableRow.addCell('Cash');
    tableRow.addCell('1200');

    //Add row 2
    tableRow = table.addRow();
    tableRow.addCell('Bank 1');
    tableRow.addCell('500');

    //Add row 3
    tableRow = table.addRow();
    tableRow.addCell('Bank 2');
    tableRow.addCell('2600');

    //Stylesheet
    var stylesheet = Banana.Report.newStyleSheet();

    //Create style for the table adding borders
    var style = stylesheet.addStyle("table");
    stylesheet.addStyle("table.myTable td", "border: thin solid black");

    //Print report
    Banana.Report.preview(report, stylesheet);

}

Create a table with fixed columns widths


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialtablecolumnswidth
// @description = Tutorial: Create a table with fixed columns width
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {

   var report = Banana.Report.newReport("Javascrip Tutorial - Table with fixed column widths");
   
   /* Create the table */
   var table = report.addTable("table");
   
   /* Add columns */
   var column1 = table.addColumn("col1");
   var column2 = table.addColumn("col2");
   var column3 = table.addColumn("col3");
   var column4 = table.addColumn("col4");

   var row;
   
   /* Add a row with cells */
   row = table.addRow(); //Add a row
   row.addCell("A", "", 1); //add first cell
   row.addCell("B", "", 1); //add second cell
   row.addCell("C", "", 1); //add third cell
   row.addCell("D", "", 1); //add fourth cell

   //Add more rows...

   /* Print the report */
   var stylesheet = createStyleSheet();
   Banana.Report.preview(report, stylesheet);
}

function createStyleSheet() {
   var stylesheet = Banana.Report.newStyleSheet();

   var style = stylesheet.addStyle(".table");
	style.setAttribute("width","100%"); //table takes all the page width
	stylesheet.addStyle("table.table td", "border: thin solid black");

   /* Set column widths */
   stylesheet.addStyle(".col1", "width:10%");
   stylesheet.addStyle(".col2", "width:55%");
   stylesheet.addStyle(".col3", "width:30%");
   stylesheet.addStyle(".col4", "width:5%");
   
   return stylesheet;
}

Add multiple paragraphs in one cell


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialcellmultipleparagraphs
// @description = Tutorial: Add multiple paragraphs in one cell of the table
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
   
   var report = Banana.Report.newReport("Javascrip Tutorial - Add multiple paragraphs in one cell");
   
   /* Create the table */
   var table = report.addTable("table");
   var row;
   
   /* Add a row */
   row = table.addRow(); 
   
   /* Add first cell with paragraphs*/
   var cell1 = row.addCell("", "", 1);
   cell1.addParagraph("First paragraph...", "");
   cell1.addParagraph("Second paragraph...", "");
   cell1.addParagraph(" "); //empty paragraph
   cell1.addParagraph("Fourth paragraph...", "");

   /* Add second cell without paragraphs */
   var cell2 = row.addCell("Cell2...", "", 1);

   /* Print the report */
   var stylesheet = createStyleSheet();
   Banana.Report.preview(report, stylesheet);

}

function createStyleSheet() {
   var stylesheet = Banana.Report.newStyleSheet();

   style = stylesheet.addStyle(".table");
   style.setAttribute("width","100%");
   stylesheet.addStyle("table.table td", "border: thin solid black");
   
   return stylesheet;
}

Create a table with fixed columns and cells span


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialtablefixedcolumnscellspan
// @description = Tutorial: Create a table with fixed columns and cells span
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {

   var report = Banana.Report.newReport("Javascrip Tutorial - Simple Table");
   
   /* Create the table */
   var table = report.addTable("table");
   
   /* Add columns */
   var column1 = table.addColumn("col1");
   var column2 = table.addColumn("col2");
   var column3 = table.addColumn("col3");
   var column4 = table.addColumn("col4");
   var row;
   
   /* 1st row */
   row = table.addRow();
   row.addCell("Row 1, Cell 1: span cell over 4 columns", "", 4); //span cell over 4 columns

   /* 2nd row */
   row = table.addRow();
   row.addCell("Row 2, Cell 1: span cell over 2 columns", "", 2); //span cell over 2 columns
   row.addCell("Row 2, Cell 3: span cell over 2 columns", "", 2); //span cell over 2 columns

   /* 3rd row */
   row = table.addRow();
   row.addCell("Row 3, Cell 1", "", 1);
   row.addCell("Row 3, Cell 2: span cell over 2 columns", "", 2); //span cell over 2 columns
   row.addCell("Row 3, Cell 4", "", 1);

   /* 4th row*/
   row = table.addRow();
   row.addCell("Row 4, Cell 1", "", 1);
   row.addCell("Row 4, Cell 2", "", 1);
   row.addCell("Row 4, Cell 3", "", 1);
   row.addCell("Row 4, Cell 4", "", 1);

   /* 5th row */
   row = table.addRow();
   row.addCell("Row 5, Cell 1: span cell over 3 columns", "", 3); //span cell over 3 columns
   row.addCell("Row 5, Cell 4", "", 1);

   /* Print the report */
   var stylesheet = createStyleSheet();
   Banana.Report.preview(report, stylesheet);

}

function createStyleSheet() {
   var stylesheet = Banana.Report.newStyleSheet();

   var style = stylesheet.addStyle(".table");
   style.setAttribute("width","100%"); //table takes all the page width
   stylesheet.addStyle("table.table td", "border: thin solid black; padding-top:10px; padding-bottom:10px;");

   /* Set columns' width */
   stylesheet.addStyle(".col1", "width:25%");
   stylesheet.addStyle(".col2", "width:25%");
   stylesheet.addStyle(".col3", "width:25%");
   stylesheet.addStyle(".col4", "width:25%");

   return stylesheet;
}

Add reporting styles

Set page margins


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialstylesheetsetmargins
// @description = Tutorial: Stylesheet set margins
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Add a paragraph with some text using a style
    report.addParagraph('Hello world!');

    //Add some styles
    var stylesheet = Banana.Report.newStyleSheet();

    //Create the margin for the page: [top, right, bottom, left]
    var pageStyle = stylesheet.addStyle("@page");
    pageStyle.setAttribute("margin", "10mm 20mm 10mm 20mm");

    //Print the report
    Banana.Report.preview(report, stylesheet);

}

Set landscape page


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialstylesheetsetlandscape
// @description = Tutorial: Stylesheet set landscape
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Add a paragraph with some text using a style
    report.addParagraph('Hello world!');

    //Add some styles
    var stylesheet = Banana.Report.newStyleSheet();

    //Create the margin for the page
    var pageStyle = stylesheet.addStyle("@page");
    pageStyle.setAttribute("size", "landscape");

    //Print the report
    Banana.Report.preview(report, stylesheet);

}

Add bold style to a text


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialstylesheetboldtext
// @description = Tutorial: Stylesheet add bold style to a text
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Add a paragraph with some text using a style
    report.addParagraph('Hello world!', 'boldStyle');

    //Add some styles
    var stylesheet = Banana.Report.newStyleSheet();

    //Create the "boldStyle"
    style = stylesheet.addStyle(".boldStyle");
    style.setAttribute("font-weight", "bold");

    //Print the report
    Banana.Report.preview(report, stylesheet);

}

Add a font size to a text


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialstylesheetfontsizetext
// @description = Tutorial: Stylesheet add a specific font size to a text
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Add a paragraph with some text using a style
    report.addParagraph('Hello world!', 'titleStyle');

    //Add some styles
    var stylesheet = Banana.Report.newStyleSheet();

    //Create the style for the text
    style = stylesheet.addStyle(".titleStyle");
    style.setAttribute("font-size", "20px");

    //Print the report
    Banana.Report.preview(report, stylesheet);

}

Add a color to a text


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialstylesheetcolortext
// @description = Tutorial: Stylesheet add a color to a text
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Add a paragraph with some text using a style
    report.addParagraph('Hello world!', 'colorStyle');

    //Add some styles
    var stylesheet = Banana.Report.newStyleSheet();

    //Create the style for the text
    style = stylesheet.addStyle(".colorStyle");
    style.setAttribute("color", "red");

    //Print the report
    Banana.Report.preview(report, stylesheet);

}

First page/cover example


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialcoverpageexample
// @description = Tutorial: First page/cover example
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport("Cover example");

    var title = " 'This is the title' ";
    var companyName = "Banana.ch SA";
    var openingDate = "01.01.2015";
    var closufeDate = "31.12.2015";
    var year = "2015";

    report.addParagraph(title, "heading1 alignCenter");
    report.addParagraph(" ");
    report.addParagraph(companyName, "heading2 alignCenter");
    report.addParagraph(" ");
    report.addParagraph(year, "heading3 alignCenter");
    report.addParagraph(" ");
    report.addParagraph("(" + openingDate + " - " + closufeDate + ")", "heading4 alignCenter");

    //Add some styles
    var stylesheet = Banana.Report.newStyleSheet();
    var pageStyle = stylesheet.addStyle("@page");
    pageStyle.setAttribute("margin", "10mm 10mm 10mm 20mm");

    stylesheet.addStyle("body", "font-family : Helvetica");

    style = stylesheet.addStyle(".heading1");
    style.setAttribute("font-size", "22px");
    style.setAttribute("font-weight", "bold");
    style.setAttribute("border-top", "100mm");

    style = stylesheet.addStyle(".heading2");
    style.setAttribute("font-size", "18px");
    style.setAttribute("font-weight", "bold");

    style = stylesheet.addStyle(".heading3");
    style.setAttribute("font-size", "14px");
    style.setAttribute("font-weight", "bold");

    style = stylesheet.addStyle(".heading4");
    style.setAttribute("font-size", "10px");
    style.setAttribute("font-weight", "bold");

    style = stylesheet.addStyle(".alignCenter");
    style.setAttribute("text-align", "center");

    //Print the report
    Banana.Report.preview(report, stylesheet);

}

Format values

Format numbers


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialformatnumbers
// @description = Tutorial: Format numbers
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Convert the value
    var convertedAmount1 = Banana.Converter.toLocaleNumberFormat("1200.65");
    var convertedAmount2 = Banana.Converter.toLocaleNumberFormat("0");
    var convertedAmount3 = Banana.Converter.toLocaleNumberFormat(1234.56);
    var convertedAmount4 = Banana.Converter.toLocaleNumberFormat(1);

    //Add the converted amount to the report's paragraph
    report.addParagraph(convertedAmount1);
    report.addParagraph(convertedAmount2);
    report.addParagraph(convertedAmount3);
    report.addParagraph(convertedAmount4);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Format dates


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialformatdates
// @description = Tutorial: Format dates
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Convert the value: parameter is a string
    var date1 = Banana.Converter.toLocaleDateFormat('2015-12-31');

    //Convert the value: parameter is a date object
    var d = new Date();
    var date2 = Banana.Converter.toLocaleDateFormat(d);

    //Add the converted amount to the report's paragraph
    report.addParagraph(date1);
    report.addParagraph(date2);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Format transactions journal data


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialformattransactionjournaldata
// @description = Tutorial: Format transactions journal data
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Create the table that will be printed on the report
    var table = report.addTable("myTable");

    //Add column titles to the table report
    var tableHeader = table.getHeader();
    tableRow = tableHeader.addRow();
    tableRow.addCell('Data', 'boldStyle');
    tableRow.addCell('Account', 'boldStyle');
    tableRow.addCell('Description', 'boldStyle');
    tableRow.addCell('Amount', 'boldStyle');

    //Create a table with all transactions
    var journal = Banana.document.journal(Banana.document.ORIGINTYPE_CURRENT, Banana.document.ACCOUNTTYPE_NORMAL);

    //Read some values of the journal table
    for (var i = 0; i < journal.rowCount; i++) {
        var tRow = journal.row(i);

        //Add the values taken from the rows to the respective cells of the table
        //For the dates and the amounts we apply the format functions
        tableRow = table.addRow();
        tableRow.addCell(Banana.Converter.toLocaleDateFormat(tRow.value('JDate')));
        tableRow.addCell(tRow.value('JAccount'));
        tableRow.addCell(tRow.value('JAccountDescription'));
        tableRow.addCell(Banana.Converter.toLocaleNumberFormat(tRow.value('JAmount')), 'alignRight');
    }

    //Create the styleSheet
    var stylesheet = Banana.Report.newStyleSheet();

    //Add borders to the table
    var style = stylesheet.addStyle("table");
    stylesheet.addStyle("table.myTable td", "border: thin solid black");

    //Add the right alignment for the amount
    style = stylesheet.addStyle(".alignRight");
    style.setAttribute("text-align", "right");

    //Add the bold style for the header
    style = stylesheet.addStyle(".boldStyle");
    style.setAttribute("font-weight", "bold");

    //Print the report
    Banana.Report.preview(report, stylesheet);

}

Numbers operations with SDecimal() functions

Basic mathematical operations (sum, subtract, multiply, divide)


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialbasicmathematicaloperations
// @description = Tutorial: Basic mathematical operations (sum, subtract, multiply, divide)
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Do some mathematical operations and add the results to the report

    //Sum
    var sum = Banana.SDecimal.add('6.50', '3.50'); // return '10.00'
    report.addParagraph(sum);

    //Subtract
    var sub = Banana.SDecimal.subtract('10', '3'); // return '7'
    report.addParagraph(sub);

    //Multiply
    var mul = Banana.SDecimal.multiply('6', '3'); // return '18'
    report.addParagraph(mul);

    //Divide
    var div = Banana.SDecimal.divide('6', '3'); // return '2'
    report.addParagraph(div);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

abs function


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialabsfunction
// @description = Tutorial: abs function 
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Return the value without the sign
    var absValue = Banana.SDecimal.abs('-10');

    //Add a paragraph to the report
    report.addParagraph(absValue);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Compare two values


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialcomparevalues
// @description = Tutorial: Compare two values
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    // Compare the values:
    // return 1 if value1 > value2
    // return 0 if value1 = value2
    // return -1 if value1 < value2

    var compareValue = Banana.SDecimal.compare('5', '2');

    //Add a paragraph to the report
    report.addParagraph(compareValue);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Invert sign of a value


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialinvertsign
// @description = Tutorial: Invert value sign
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Invert the sign:
    //if positive return a negative value
    //if negative return a positive value

    var invertValue = Banana.SDecimal.invert('4');

    //Add a paragraph to the report
    report.addParagraph(invertValue);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Check the sign of a value


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialcheckvaluesign
// @description = Tutorial: Check value sign
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Check the sign of the value:
    //return 1 if value > 0
    //return 0 if  value = 0
    //return -1 if value <0

    var signValue = Banana.SDecimal.sign('-6');

    //Add a paragraph to the report
    report.addParagraph(signValue);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Number of decimals and rounding properties


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialdecimalsrounding
// @description = Tutorial: Number of decimals and rounding properties
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Divide without properties
    var result1 = Banana.SDecimal.divide('10', '3.25'); //return '3.3333333333333333333333333'
    report.addParagraph(result1);

    //Divide with number of decimals property
    var result2 = Banana.SDecimal.divide('10', '3.25', {
        'decimals': 4
    });
    report.addParagraph(result2);

    //Divide with number of decimals and rounding properties
    var result3 = Banana.SDecimal.divide('10', '3.25', {
        'decimals': 2,
        'mode': Banana.SDecimal.HALF_UP
    });
    report.addParagraph(result3);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

User interface functions

Dialog information


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialinformationdialog
// @description = Tutorial: Information dialog
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Open a dialog window with an information
    Banana.Ui.showInformation('Title', 'This is the information message!');
}

Dialog question


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialquestiondialog
// @description = Tutorial: Question dialog
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create a report
    var report = Banana.Report.newReport("Report title");

    //Open a dialog window with a question
    var question = Banana.Ui.showQuestion('Question title', 'Print the report?');

    //If 'true' do something... 
    if (question) {
        //...for example add some text to the paragraph
        report.addParagraph('The answer was YES!');

        //...then print the report
        var stylesheet = Banana.Report.newStyleSheet();
        Banana.Report.preview(report, stylesheet);
    }

}

Dialog show text


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialshowtextdialog
// @description = Tutorial: Show text dialog
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Open a dialog window showing the text.
    //In this case we want to show the table Accounts as html file
    Banana.Ui.showText(Banana.document.table('Accounts').toHtml(['Account', 'Group', 'Description', 'Balance'], true));

}

Dialog input text


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialinputtextdialog
// @description = Tutorial: Input text dialog
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create a report
    var report = Banana.Report.newReport("Report title");

    //Open a dialog window asking the user to insert some text
    //The text inserted is saved into a variable
    var textInsertedByUser = Banana.Ui.getText('This is a dialog window', 'Insert some text', '');

    //Add to the paragraph the text inserted by the user
    report.addParagraph(textInsertedByUser);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);
}

Dialog item selection


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialitemselectiondialog
// @description = Tutorial: Item selection dialog
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Open a dialog window asking to select an item from the list
    //The selected item is then saved into a variable
    var itemSelected = Banana.Ui.getItem('Input', 'Choose a value', ['Item ONE', 'Item TWO', 'Item THREE', 'Item FOUR', 'Item FIVE'], 2, false);

    //Add the selected item to the paragraph
    report.addParagraph(itemSelected);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);
}

Dialog period selection


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialperiodselectiondialog
// @description = Tutorial: Period selection dialog
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create a report
    var report = Banana.Report.newReport("Report title");

    //Open a dialog windows to choose a period
    var date = Banana.Ui.getPeriod('Period selection', '2015-01-01', '2015-12-31');

    //Add the date information to the report
    report.addParagraph(date.startDate);
    report.addParagraph(date.endDate);
    report.addParagraph(date.hasSelection);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);
}

Dialog multiple items selection


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialmultipleitemsselectiondialog
// @description = Tutorial: Multiple items selection dialog
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Open a dialog window asking to select an item from the list
    //The selected item is then saved into a variable
    var itemsSelected = Banana.Ui.getItems(
       'Input', 
       'Choose one or more values', 
       ['Item ONE', 'Item TWO', 'Item THREE', 'Item FOUR', 'Item FIVE'], 
       ['Item ONE', 'Item THREE']
    );

    if (!itemsSelected) {
       // User pressed cancel
       return;
    }

    //Add the selected item to the paragraph
    report.addParagraph("Selected items:");

    if (itemsSelected.length > 0) {
        for (var i = 0; i < itemsSelected.length; ++i) {
            report.addParagraph("- " + itemsSelected[i]);
        }
    } else {
        report.addParagraph("No item selected");
    }

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);
}

Message functions

Show messages


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialshowmessages
// @description = Tutorial: Show messages
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    Banana.document.clearMessages();

    //Step 1 - table access
    var transactionTable = Banana.document.table('Transactions');

    //Step 2 - loop on each row of the table
    for (var i = 0; i < transactionTable.rowCount; i++) {

        var tRow = transactionTable.row(i);

        //Check the length of the description
        if (tRow.value('Description').length > 20 && tRow.value('Description').length < 30) {
            Banana.document.addMessage("Warning: row " + tRow.rowNr + ", description's length is " + tRow.value('Description').length + "!");
        } else if (tRow.value('Description').length >= 30) {
            Banana.document.addMessage("Error: row " + tRow.rowNr + ", description's length is " + tRow.value('Description').length + "!");
        }
    }

}

Show messages linked to table Transaction


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialshowmessageslinkedtotable
// @description = Tutorial: Show messages linked to table Transactions
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    Banana.document.clearMessages();

    //Step 1 - table access
    var transactionTable = Banana.document.table('Transactions');

    //Step 2 - loop on each row of the table
    for (var i = 0; i < transactionTable.rowCount; i++) {

        var tRow = transactionTable.row(i);

        //Check the length of the description
        if (tRow.value('Description').length > 20 && tRow.value('Description').length < 30) {
            tRow.addMessage("Warning: description's length is " + tRow.value('Description').length + "!");
        } else if (tRow.value('Description').length >= 30) {
            tRow.addMessage("Error: description's length is " + tRow.value('Description').length + "!");
        }
    }

}

Clear all messages


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialclearmessages
// @description = Tutorial: Clear all messages
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    Banana.document.clearMessages();
}

Save settings

Save settings


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialsavesettings
// @description = Tutorial: Save settings
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {

    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Readscript settings
    var readText = Banana.document.scriptReadSettings();

    //If there is a saved setting we can use it
    if (readText) {

        //Use the JSON.parse() to convert a JSON text into a JavaScript object
        var object = JSON.parse(readText);

        //Add a paragraph with the saved and parsed text
        report.addParagraph('Previously saved value: ' + object);

        //Print the report
        var stylesheet = Banana.Report.newStyleSheet();
        Banana.Report.preview(report, stylesheet);
    }

    // If it doesn't exists a saved setting yet (which it happens the very first time the script is executed),
    //	it is necessary to create and save it

    //For example using an dialog window to insert some text
    var text = Banana.Ui.getText('Save settings example', 'Insert some text', '');

    //Convert a JavaScript value into a JSON string using the JSON.stringify() function
    var textToSave = JSON.stringify(text);

    //Save script settings
    var savedText = Banana.document.scriptSaveSettings(textToSave);

}

Retrieving informations from "File and account properties..."

Retrieve basic accounting informations


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialretrievebasicaccountinginformation
// @description = Tutorial: Retrieve basic accounting information
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create report
    var report = Banana.Report.newReport('Report title');

    //Get some value of the accounting file 
    var fileName = Banana.document.info("Base", "FileName");
    var decimalsAmounts = Banana.document.info("Base", "DecimalsAmounts");
    var headerLeft = Banana.document.info("Base", "HeaderLeft");
    var headerRight = Banana.document.info("Base", "HeaderRight");
    var basicCurrency = Banana.document.info("AccountingDataBase", "BasicCurrency");

    //For openingDate and closureDate
    var startDate = Banana.document.info('AccountingDataBase', 'OpeningDate');
    var endDate = Banana.document.info('AccountingDataBase', 'ClosureDate');

    //For file accounting type
    var fileType = Banana.document.info("Base", "FileType");
    var fileGroup = Banana.document.info("Base", "FileTypeGroup");
    var fileNumber = Banana.document.info("Base", "FileTypeNumber");

    //Add the informations to the report
    report.addParagraph(fileName);
    report.addParagraph(decimalsAmounts);
    report.addParagraph(headerLeft);
    report.addParagraph(headerRight);
    report.addParagraph(basicCurrency);
    report.addParagraph(startDate);
    report.addParagraph(endDate);
    report.addParagraph(fileType);
    report.addParagraph(fileGroup);
    report.addParagraph(fileNumber);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Retrieve address informations


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialretrieveaddressinformation
// @description = Tutorial: Retrieve address information
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create report
    var report = Banana.Report.newReport('Report title');

    //Save informations
    var company = Banana.document.info('AccountingDataBase', 'Company');
    var courtesy = Banana.document.info('AccountingDataBase', 'Courtesy');
    var name = Banana.document.info('AccountingDataBase', 'Name');
    var familyName = Banana.document.info('AccountingDataBase', 'FamilyName');
    var address1 = Banana.document.info('AccountingDataBase', 'Address1');
    var address2 = Banana.document.info('AccountingDataBase', 'Address2');
    var zip = Banana.document.info('AccountingDataBase', 'Zip');
    var city = Banana.document.info('AccountingDataBase', 'City');
    var state = Banana.document.info('AccountingDataBase', 'State');
    var country = Banana.document.info('AccountingDataBase', 'Country');
    var web = Banana.document.info('AccountingDataBase', 'Web');
    var email = Banana.document.info('AccountingDataBase', 'Email');
    var phone = Banana.document.info('AccountingDataBase', 'Phone');
    var mobile = Banana.document.info('AccountingDataBase', 'Mobile');
    var fax = Banana.document.info('AccountingDataBase', 'Fax');
    var fiscalNumber = Banana.document.info('AccountingDataBase', 'FiscalNumber');
    var vatNumber = Banana.document.info('AccountingDataBase', 'VatNumber');

    //Add the informations to the report
    report.addParagraph(company);
    report.addParagraph(courtesy);
    report.addParagraph(name);
    report.addParagraph(familyName);
    report.addParagraph(address1);
    report.addParagraph(address2);
    report.addParagraph(zip);
    report.addParagraph(city);
    report.addParagraph(state);
    report.addParagraph(country);
    report.addParagraph(web);
    report.addParagraph(email);
    report.addParagraph(phone);
    report.addParagraph(mobile);
    report.addParagraph(fax);
    report.addParagraph(fiscalNumber);
    report.addParagraph(vatNumber);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Retrieving data from Banana tables

Retrieve rows table values using findRowByValue() function


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialretrieverowstablevaluesusingfindrowbyvalue
// @description = Tutorial: Retrieve rows table values using findRowByValue() function
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create report
    var report = Banana.Report.newReport("Report title");

    //Save the row extracted from the table
    var rowToExtract = Banana.document.table('Accounts').findRowByValue('Account', '1000');

    //Add the Account, Description and Balance informations to the report
    report.addParagraph(rowToExtract.value('Account'));
    report.addParagraph(rowToExtract.value('Description'));
    report.addParagraph(rowToExtract.value('Balance'));

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Retrieve specific rows table values


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialretrievespecificrowstablevalues
// @description = Tutorial: Retrieve specific rows table values
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create report
    var report = Banana.Report.newReport("Report title");

    // Step 1 - table access: specify the name of the table ("Accounts", "Transactions", "VatCodes", ...)
    var accountsTable = Banana.document.table("Accounts");

    //Step 2 - row selection: 	it is important to note that the rows of the Banana table start counting from 0,
    //so keep in mind to specify one number less than the desired one 
    //1st row = 0
    //2nd row = 1
    //3rd row = 2
    //4th row = 3
    //...

    var row3 = accountsTable.row(2); // We want the third row

    // Step 3 - select all the desired columns
    var account = row3.value("Account");
    var description = row3.value("Description");
    var balance = row3.value("Balance");

    //Add the informations to the report
    report.addParagraph(account);
    report.addParagraph(description);
    report.addParagraph(balance);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);
}

Retrieve rows table values


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialretrieverowstablevalues
// @description = Tutorial: Retrieve rows table values
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create a report
    var report = Banana.Report.newReport('Report title');

    //Step 1 - table access
    var accountsTable = Banana.document.table('Accounts');

    //Step 2 - loop on each row of the table, instead of specifying a single row
    for (var rowNumber = 0; rowNumber < accountsTable.rowCount; rowNumber++) {

        var tRow = accountsTable.row(rowNumber);

        //Step 3 - select the desired columns
        var account = tRow.value('Account');
        var description = tRow.value('Description');
        var balance = tRow.value('Balance');

        //Add the informations to the report
        report.addParagraph(account + ', ' + description + ', ' + balance);
    }

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Retrieve rows table with account number


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialretretrieverowstablewithaccountnumber
// @description = Tutorial: Retrieve rows table with account number
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create a report
    var report = Banana.Report.newReport('Report title');

    //Step 1 - table access
    var accountsTable = Banana.document.table('Accounts');

    //Step 2 - loop on each row of the table, instead of specifying a single row
    for (var rowNumber = 0; rowNumber < accountsTable.rowCount; rowNumber++) {

        var tRow = accountsTable.row(rowNumber);

        //If the row has an account number we save the values and print them
        if (tRow.value('Account')) {

            //Step 3 - select the desired columns
            var account = tRow.value('Account');
            var description = tRow.value('Description');
            var balance = tRow.value('Balance');

            //Add the informations to the report
            report.addParagraph(account + ', ' + description + ', ' + balance);
        }
    }

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Print all table rows in a table format


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialretprintrowstablewithaccountnumberintableformat
// @description = Tutorial: Print rows table with account number in table format
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create a report
    var report = Banana.Report.newReport('Report title');

    //Create the table that will be printed on the report
    var table = report.addTable("myTable");

    //Add column titles to the table report
    var tableHeader = table.getHeader();
    tableRow = tableHeader.addRow();
    tableRow.addCell("Account");
    tableRow.addCell("Description");
    tableRow.addCell("Balance");


    //Step 1 - table access
    var accountsTable = Banana.document.table('Accounts');

    //Step 2 - loop on each row of the table, instead of specifying a single row
    for (var rowNumber = 0; rowNumber < accountsTable.rowCount; rowNumber++) {

        var tRow = accountsTable.row(rowNumber);

        //If the row has an account number we save the values and print them
        if (tRow.value('Account')) {

            //Step 3 - select the desired columns
            var account = tRow.value('Account');
            var description = tRow.value('Description');
            var balance = tRow.value('Balance');

            //Add the values taken from the rows to the respective cells of the table
            tableRow = table.addRow();
            tableRow.addCell(account);
            tableRow.addCell(description);
            tableRow.addCell(balance);
        }
    }

    //Create the styleSheet to 
    var stylesheet = Banana.Report.newStyleSheet();

    //Create a table style adding the border
    var style = stylesheet.addStyle("table");
    stylesheet.addStyle("table.myTable td", "border: thin solid black");

    //Print the report
    Banana.Report.preview(report, stylesheet);

}

Find all rows that match a condition using findRows


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialfindrows
// @description = Tutorial: Retrieve all rows table that match a condition using findRows
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    var tableAccounts = Banana.document.table('Accounts');
    var rows = tableAccounts.findRows(accountStartsWith25XX);
    var accounts = [];
    for(var i = 0; i < rows.length; i++) {
       accounts.push(rows[i].value('Account'));
    }
    Banana.Ui.showInformation('Info', 'Accounts that start with 25XX: ' + accounts.join(';')); 
}

function accountStartsWith25XX(rowObj,rowNr,table) {
   // Return true if account start with '25XX'
   return rowObj.value('Account').startsWith('25');
}

Retrieve all rows that match a condition using extractRows


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialextractrows
// @description = Tutorial: Retrieve all rows table that match a condition using extractRows
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    var tableAccounts = Banana.document.table('Accounts');
    tableAccounts.extractRows(accountStartsWith25XX, 'Accounts that start with 25XX');
}

function accountStartsWith25XX(rowObj,rowNr,table) {
   // Return true if account start with '25XX'
   return rowObj.value('Account').startsWith('25');
}

Retriveing data with currentBalance() function

Amount of opening for all transactions for an account


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialcurrentbalancesingleaccount
// @description = Tutorial: Retrieve amount of an account using currentBalance() function
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Take opening sum for a non-specific period: period taken from Banana
    var amount1 = Banana.document.currentBalance('1000', '', '').opening;

    //Take opening sum for a specific period
    var amount2 = Banana.document.currentBalance('1000', '2015-01-05', '2015-02-07').opening;

    //Add a paragraph with the amounts just calculated
    report.addParagraph(Banana.document.accountDescription('1000'));
    report.addParagraph(amount1);
    report.addParagraph(amount2);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Amount of opening for all transactions for multiple accounts


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialcurrentbalancemultipleaccounts
// @description = Tutorial: Retrieve amount of multiple accounts using currentBalance() function
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Take opening sum for a non-specific period: period taken from Banana
    var amount1 = Banana.document.currentBalance('1000|1010|1011', '', '').opening;

    //Take opening sum for a specific period
    var amount2 = Banana.document.currentBalance('1000|1010|1011', '2015-01-05', '2015-02-07').opening;

    //Add a paragraph with the amounts just calculated
    report.addParagraph(amount1);
    report.addParagraph(amount2);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Amount of opening for all transactions for a single group


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialcurrentbalancesinglegroup
// @description = Tutorial: Retrieve amount of single group using currentBalance() function
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Take opening sum for a non-specific period: period taken from Banana
    var amount1 = Banana.document.currentBalance('Gr=100', '', '').opening;

    //Take opening sum for a specific period
    var amount2 = Banana.document.currentBalance('Gr=100', '2015-01-05', '2015-02-07').opening;

    //Add a paragraph with the amounts just calculated
    report.addParagraph(Banana.document.accountDescription('Gr=100'));
    report.addParagraph(amount1);
    report.addParagraph(amount2);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Amount of opening for all transactions for multiple groups


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialcurrentbalancemultiplegroups
// @description = Tutorial: Retrieve amount of multiple groups using currentBalance() function
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Take opening sum for a non-specific period: period taken from Banana
    var amount1 = Banana.document.currentBalance('Gr=100|110|120', '', '').opening;

    //Take opening sum for a specific period
    var amount2 = Banana.document.currentBalance('Gr=100|110|120', '2015-01-05', '2015-02-07').opening;

    //Add a paragraph with the amounts just calculated
    report.addParagraph(amount1);
    report.addParagraph(amount2);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Amount of opening for all transactions for a BClass


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialcurrentbalancesinglebclass
// @description = Tutorial: Retrieve amount of a single BClass using currentBalance() function
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Take opening sum for a non-specific period: period taken from Banana
    var amount1 = Banana.document.currentBalance('BClass=1', '', '').opening;

    //Take opening sum for a specific period
    var amount2 = Banana.document.currentBalance('BClass=1', '2015-01-05', '2015-02-07').opening;

    //Add a paragraph with the amounts just calculated
    report.addParagraph(amount1);
    report.addParagraph(amount2);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Amount of opening for all transactions for multiple BClass values


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialcurrentbalancemultiplebclass
// @description = Tutorial: Retrieve amount of multiple BClass using currentBalance() function
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Take opening sum for a non-specific period: period taken from Banana
    var amount1 = Banana.document.currentBalance('BClass=1|2', '', '').opening;

    //Take opening sum for a specific period
    var amount2 = Banana.document.currentBalance('BClass=1|2', '2015-01-05', '2015-02-07').opening;

    //Add a paragraph with the amounts just calculated
    report.addParagraph(amount1);
    report.addParagraph(amount2);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Retriveing data with vatCurrentBalance() function

Sum the Vat amounts for the specified vat code


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialvatcurrentbalancesinglevatcode
// @description = Tutorial: Sum the VAT amounts for single VAT code using vatCurrentBalance() function
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Take the vatAmount sum for a non-specific period: period taken from Banana
    var amount1 = Banana.document.vatCurrentBalance('S10', '', '').vatAmount;

    //Take the vatAmount sum for a specific period
    var amount2 = Banana.document.vatCurrentBalance('S10', '2015-01-01', '2015-01-06').vatAmount;

    //Add a paragraph with the amounts just calculated
    report.addParagraph(amount1);
    report.addParagraph(amount2);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Sum the Vat amounts for multiple vat codes


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialvatcurrentbalancemultiplevatcodes
// @description = Tutorial: Sum the VAT amounts for multiple VAT codes using vatCurrentBalance() function
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Take the vatAmount sum for a non-specific period: period taken from Banana
    var amount1 = Banana.document.vatCurrentBalance('S10|P10', '', '').vatAmount;

    //Take the vatAmount sum for a specific period
    var amount2 = Banana.document.vatCurrentBalance('S10|P10', '2015-02-01', '2015-02-28').vatAmount;

    //Add a paragraph with the amounts just calculated
    report.addParagraph(amount1);
    report.addParagraph(amount2);

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Retriveing data with currentCard() function

For a given account without specifying the period


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialcurrentcardnoperiod
// @description = Tutorial: Use currentCard() function for a given account
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Create a table with all the transactions of the given account
    var transTab = Banana.document.currentCard('1010', '', '');

    //For each row of the table we save the values
    for (var i = 0; i < transTab.rowCount; i++) {
        var tRow = transTab.row(i);

        var date = tRow.value('JDate');
        var account = tRow.value('JAccount');
        var description = tRow.value("JDescription");
        var debit = tRow.value('JDebitAmount');
        var credit = tRow.value('JCreditAmount');
        var balance = tRow.value('JBalance');

        //Add a paragraph with the values just calculated
        report.addParagraph(date + ', ' + account + ', ' + description + ', ' + debit + ', ' + credit + ', ' + balance);
    }

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

For a given account and period


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialcurrentcardwithperiod
// @description = Tutorial: Use currentCard() function for a given account and period
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Create a table with all transactions for the given account and period
    var transTab = Banana.document.currentCard('1010', '2015-01-03', '2015-02-07');

    //For each row of the table we save the values
    for (var i = 0; i < transTab.rowCount; i++) {
        var tRow = transTab.row(i);

        var date = tRow.value('JDate');
        var account = tRow.value('JAccount');
        var description = tRow.value("JDescription");
        var debit = tRow.value('JDebitAmount');
        var credit = tRow.value('JCreditAmount');
        var balance = tRow.value('JBalance');

        //Add a paragraph with the values just calculated
        report.addParagraph(date + ', ' + account + ', ' + description + ', ' + debit + ', ' + credit + ', ' + balance);
    }

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Retriveing data with journal() function

Get all transaction for normal accounts


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialjournal
// @description = Tutorial: Retrieve all transactions for normal accounts using the journal() function
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    //Create the report
    var report = Banana.Report.newReport('Report title');

    //Create a table with all transactions
    var journal = Banana.document.journal(Banana.document.ORIGINTYPE_CURRENT, Banana.document.ACCOUNTTYPE_NORMAL);

    //Read the table and save some values
    for (var i = 0; i < journal.rowCount; i++) {
        var tRow = journal.row(i);

        var date = tRow.value('JDate');
        var account = tRow.value('JAccount');
        var accDescription = tRow.value('JAccountDescription');
        var description = tRow.value('JDescription');
        var vatCode = tRow.value('JVatCodeWithoutSign');
        var vatDescription = tRow.value('JVatCodeDescription');
        var amount = tRow.value('JAmount');

        //Add to the paragraph the values just saved
        report.addParagraph(date + ', ' + account + ', ' + accDescription + ', ' + description + ', ' + vatCode + ', ' + vatDescription + ', ' + amount);
    }

    //Print the report
    var stylesheet = Banana.Report.newStyleSheet();
    Banana.Report.preview(report, stylesheet);

}

Reading and writing xml files

Reading an xml file


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialreadxmlfile
// @description = Tutorial: Read an XML file
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1


var xml =   '<Library updated="2018-09-03">' +                            //  To simplify,
    '<Book>' +                                                  //  the variable
    '<Title>Paths of colours</Title>' +                       //  xml contains
    '<Author>Rosa Indaco</Author>' +                          //  the xml string
    '</Book>' +
    '<Book>' +
    '<Title>Accounting exercises</Title>' +
    '<Author>Su Zhang</Author>' +
    '</Book>' +
    '</Library>';

var bookList = "";                                                        //  Create string for the output
var xmlFile = Banana.Xml.parse(xml);                                      //  Create XML Parse object
var xmlRoot = xmlFile.firstChildElement('Library');                       //  Find the first tag "Library" in the XML
var updateDate = xmlRoot.attribute('updated');                            //  Take attribute assigned to the tag
bookList += "Books in the library on " + updateDate + "\n\n";             //  Append to the output string

var bookNode = xmlRoot.firstChildElement('Book');                         //  Take the first Book
while (bookNode) {                                                        //  As long as there are books, repeat
    var title = bookNode.firstChildElement('Title').text;                 //  Find the first tag "Title" in the XML
    var authorNode = bookNode.firstChildElement('Author');                //  Find the first tag "Author" in the XML
    var author = authorNode ? authorNode.text : 'unknow';                 //  Check whether there is a tag "Author"
    bookList += title + " - " + author + "\n";                            //  Append to the output string
    bookNode = bookNode.nextSiblingElement('Book');                       //  Go to the next book
}

Banana.Ui.showText("List of books present in the xml file", bookList);    //  Output the results


Writing an xml file


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialwritexmlfile
// @description = Tutorial: Write an XML file
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {

    var xmlDocument = Banana.Xml.newDocument("Library");                    //  Create XML file
    xmlDocument.addComment("This is the generated xml file");               //  Add comment to the file
    var rootNode = xmlDocument.addElement("Library");                       //  Set root tag "Library"
    rootNode.setAttribute("updated", "2018-09-03");      //  Set attribute to the tag "Library"

    var bookNode = rootNode.addElement("Book");                             //  Create tag "Book" child of "Library"
    bookNode.addElement("Title").addTextNode("Paths of colours");           //  Create tag "Title" child of "Book"
    bookNode.addElement("Author").addTextNode("Rosa Indaco");               //  Create tag "Author" child of "Book"

    var bookNode = rootNode.addElement("Book");                             //  Create tag "Book" child of "Library"
    bookNode.addElement("Title").addTextNode("Accounting exercises");       //  Create tag "Title" child of "Book"
    bookNode.addElement("Author").addTextNode("Su Zhang");                  //  Create tag "Author" child of "Book"

    var xmlString = Banana.Xml.save(xmlDocument);                           //  Create output

    // Show the xml file
    Banana.Ui.showText("Xml file", xmlString);                              //  Generate output
}

Validate an xml file via xsd


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialxmlvalidation
// @description = Tutorial: Validate an XML file via XSD
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {

    // The xml file
    var xml = '<Library updated="2018-09-03"> \
		<Book> \
			<Title>Paths of colours</Title> \
			<Author>Rosa Indaco</Author> \
		</Book> \
		<Book> \
			<Title>Accounting exercises</Title> \
			<Author>Su Zhang</Author> \
		</Book> \
   </Library>';

    // Parse the xml
    var xmlFile = Banana.Xml.parse(xml);

    // Validate the xml
    var valid = Banana.Xml.validate(xmlFile, 'documents:xsd');
    if (valid) {
        Banana.Ui.showInformation('Validation result', 'The xml is valid');
    } else  {
        Banana.Ui.showInformation('Validation result', 'The xml is not valid: ' + Banana.Xml.errorString);
    }
}

Filter for xml file


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialgeneralxmlFile
// @description = Tutorial: General functions on XML files
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2020-03-27
// @inputdatasource = none
// @timeout = -1

function exec(){
    const xml = '<solarSystem updated="2020-03-27">' +
                    '<Planet>' +
                        '<name>Sun</name>' +
                        '<sizeOrder>1</sizeOrder>' +
                    '</Planet>' +
                    '<Planet>' +
                        '<name>Earth</name>' +
                        '<sizeOrder>6</sizeOrder>' +
                        '<satellite>Moon</satellite>' +
                    '</Planet>' +
                    '<Planet>' +
                        '<name>Jupiter</name>' +
                        '<sizeOrder>2</sizeOrder>' +
                        '<satellite>Callisto</satellite>' +
                    '</Planet>' +
                    '<Planet>' +
                        '<name>Saturn</name>' +
                        '<sizeOrder>3</sizeOrder>' +
                        '<satellite>Cronus</satellite>' +
                    '</Planet>' +
                    '<Planet>' +
                        '<name>Mars</name>' +
                        '<sizeOrder>8</sizeOrder>' +
                        '<satellite>Phobos</satellite>' +
                    '</Planet>' +
                    '<Planet>' +
                        '<name>Neptune</name>' +
                        '<sizeOrder>5</sizeOrder>' +
                        '<satellite>Triton</satellite>' +
                    '</Planet>' +
                    '<Planet>' +
                        '<name>Mercury</name>' +
                        '<sizeOrder>9</sizeOrder>' +
                    '</Planet>' +
                    '<Planet>' +
                        '<name>Venus</name>' +
                        '<sizeOrder>7</sizeOrder>' +
                    '</Planet>' +
                    '<Planet>' +
                        '<name>Uranus</name>' +
                        '<sizeOrder>4</sizeOrder>' +
                        '<satellite>Ariel</satellite>' +
                    '</Planet>' +
        '</solarSystem>';

    var outputString = "";
    var xmlFile = Banana.Xml.parse(xml);
    var xmlRoot = xmlFile.firstChildElement('solarSystem');
    var updateDate = xmlRoot.attribute('updated');
    outputString += "Planets in the solar System with satellites updated on " + updateDate + "\n\n";

    var planet = xmlRoot.firstChildElement('Planet');
    while (planet) {
        if (planet.hasChildElements('satellite')) {
            var planetName = planet.firstChildElement('name').text;
            var planetSatellite = planet.firstChildElement('satellite').text;
            outputString += "name: " + planetName + ", satellite: " + planetSatellite + "\n";
        }
        planet = planet.nextSiblingElement('Planet');
    }
    Banana.Ui.showText("Planets in the XML with satellites", outputString);
}

Export Transaction table to xml file


// Banana Accounting Extension Javascript
// @id = ch.banana.apps.export
// @api = 1.0
// @pubdate = 2016-04-08
// @doctype = *.*
// @description = Export into an xml file (.xml)
// @task = export.file
// @exportfiletype = xml
// @timeout = -1

function exec() {
    var xmlDocument = Banana.Xml.newDocument("Transactions");
    xmlDocument.addComment("This is the generated xml file");
    var rootNode = xmlDocument.addElement("transactions");
    var tableTransactions = Banana.document.table('Transactions');
    if (!tableTransactions) {
        return;
    }
    for (i=0;i<tableTransactions.rowCount;i++) {
        if (tableTransactions.row(i).value('Amount')) {
            var transactionNode = rootNode.addElement("transaction");
            transactionNode.addElement("date").addTextNode(tableTransactions.row(i).value('Date'));
            transactionNode.addElement("description").addTextNode(tableTransactions.row(i).value('Description'));
            transactionNode.addElement("amount").addTextNode(tableTransactions.row(i).value('Amount'));
        }
    }
    var xmlString = Banana.Xml.save(xmlDocument);
    Banana.Ui.showText("Xml file", xmlString);
    return xmlString;
}

Import Transactions from xml file


// Banana Accounting Extension Javascript
// @api = 1.0
// @pubdate = 2020-04-02
// @id = ch.banana.uni.app.tutorialretrieverowstablevalues
// @description = Import transactions
// @task = import.transactions
// @outputformat = transactions.simple
// @doctype = *
// @inputdatasource = openfiledialog
// @inputencoding = latin1
// @inputfilefilter = Text files (*.xml);;All files (*.*)
// @publisher = Banana.ch SA
// @timeout = -1

function exec(inputFile) {
    var CSV_String = "Date" + '","' + "Description" + '","' + "Income" + '","' + "Expenses" + '\n';
    var xmlFile = Banana.Xml.parse(inputFile);
    var xmlRoot = xmlFile.firstChildElement('transactions');
    var transactionNode = xmlRoot.firstChildElement('transaction');
    while (transactionNode) {
        var date = transactionNode.firstChildElement('date').text;
        var description = transactionNode.firstChildElement('description').text;
        var income = transactionNode.firstChildElement('income').text;
        var expenses = transactionNode.firstChildElement('expenses').text;
        CSV_String += ('"' + date + '","' + description + '","' + income + '","' + expenses + '"' + '\n');
        transactionNode = transactionNode.nextSiblingElement('transaction');
    }
    Banana.console.debug(CSV_String);
    var csvFile = Banana.Converter.csvToArray(CSV_String, ',', '"');
    var tsvFile = Banana.Converter.arrayToTsv(csvFile);
    return tsvFile;
}

Debugging

Ouput messages to the debug panel


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialdebugmessages
// @description = Tutorial: Output messages to the debug panel
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-01-25
// @inputdatasource = none
// @timeout = -1

function exec() {
    Banana.console.log("An info message");
    Banana.console.debug("A debug message");
    Banana.console.warn("A warning message"); // Since Banana 9.0.4 use Banana.console.warning
    Banana.console.critical("A critical message");
}

Progress bar and timeout

Script timeout


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialscripttimeout
// @description = Tutorial: Progress bar
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-12-06
// @inputdatasource = none
// @timeout = 2000

function exec() {
	while(true) {
    }     
}

Progess bar


// Banana Accounting Extension Javascript
// @api = 1.0
// @id = ch.banana.uni.app.tutorialprogressbar
// @description = Tutorial: Progress bar
// @task = app.command
// @doctype = nodocument
// @publisher = Banana.ch SA
// @pubdate = 2019-12-06
// @inputdatasource = none
// @timeout = 20000

function exec() {
     
    var nr = 100000000;
 
    var progressBar = Banana.application.progressBar;
    progressBar.start(nr); 
    
    for (var i = 0; i < nr; ++i) {
       if (!progressBar.step(1)) {
           break; // Operation canceled by the user
     	}
    }
}

User interface

QTableWidget interaction


// Banana Accounting Extension Javascript
/**
 * This example shows the use of a QTableWidget
 * The user interface is defined in file "ch.banana.tutorial.tablewidget.ui"
 * This example is also found in the tutorial file "embedded_javascript_tutorial1.ac2"
 */
// @id = ch.banana.exmaple.tablewidget
// @version = 1.0
// @date = 2019-12-06
// @publisher = Banana.ch SA
// @description = Tutorial QTableWidget
// @task = app.command
// @inputdatasource = none
// @timeout = -1
// @doctype = nodocument

var param = {};

/** Dialog's functions declaration */
var dialog = Banana.Ui.createUi("documents:740.ui");
var table = dialog.findChild("tableWidget");
var buttonBox = dialog.findChild("buttonBox");
var statusLabel = dialog.findChild("statusLabel");

/** Main function */
function exec(inData) {
    //Check the version of Banana
    var requiredVersion = "9.1.0.0";
    if (!Banana.compareVersion || Banana.compareVersion(Banana.application.version, requiredVersion) < 0) {
        Banana.Ui.showInformation("You need Banana 9.1.0.0 or newer to run this example");
        return;
	}

    // Connect button box signals
    buttonBox.accepted.connect(function() {dialog.close();});
    buttonBox.rejected.connect(function() {dialog.close();});

    // Set the table read
    // table.setEditTriggers(0); // see flags QAbstractItemView::EditTriggers

    // Set columns
    table.setColumnCount(4);
    table.setHorizontalHeaderLabels(["A", "B", "C", "D"])
    table.setColumnWidth(1, 200);

    // Set rows
    table.setRowCount(5);

    // Set cell text
    table.item(1,0).text = "hello";

    // Set cell colors
    var item2 = table.item(1,1);
    item2.text = "colors";
    item2.background = "red";
    item2.foreground = "white";

    // Set cell checkable
    var item3 = table.item(1,2);
    item3.flags = 0x33; // See flags Qt::ItemFlags
    item3.text = "check-it";
    item3.checkState = 0; // See flags Qt::CheckState

    // Set current cell
    // table.setCurrentCell(1,0);

    // Connect table's signals after the table is populated
    table.cellClicked.connect(updateStatusBar);
    table.cellChanged.connect(updateStatusBar);

    // Show dialog
    Banana.application.progressBar.pause();
    dialog.exec();
    Banana.application.progressBar.resume();

    // Get table size
    Banana.console.log("Table size: " + table.rowCount + ", " + table.columnCount);

    // Get current position
    Banana.console.log("Current position: " + table.currentRow + ", " + table.currentColumn);

    // Get current text
    var curItem = table.currentItem();
    Banana.console.log("Current text: " + curItem.text);

    // Get item check state
    Banana.console.log("Item check state: " + (item3.checkState === 2 ? "checked" : "unchecked"));
}

// Update status bar with useful info about the current cell
function updateStatusBar() {
    var curItem = table.currentItem();
    if (curItem) {
        var msg = "Cell " + (table.currentRow + 1) + "," + (table.currentColumn + 1) + " clicked. ";
        if (curItem.text.length > 0)
            msg += "Text: '" + curItem.text + "'. ";
        if (curItem.checkState === 2)
            msg += "Checked: true.";
        statusLabel.text = msg;
    } else {
        statusLabel.text = "";
    }
}

- User interface for QTableWidget interaction


// Banana Accounting Extension Javascript
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Dialog</class>
 <widget class="QDialog" name="Dialog">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>584</width>
    <height>411</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>QTableWidget Tutorial</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout">
   <item>
    <widget class="QTableWidget" name="tableWidget"/>
   </item>
   <item>
    <layout class="QHBoxLayout" name="horizontalLayout">
     <item>
      <widget class="QLabel" name="statusLabel">
       <property name="text">
        <string/>
       </property>
      </widget>
     </item>
    </layout>
   </item>
   <item>
    <widget class="QDialogButtonBox" name="buttonBox">
     <property name="standardButtons">
      <set>QDialogButtonBox::Ok</set>
     </property>
    </widget>
   </item>
  </layout>
 </widget>
 <tabstops>
  <tabstop>tableWidget</tabstop>
 </tabstops>
 <resources/>
 <connections/>
</ui>

Find dialog


// Banana Accounting Extension Javascript
/** 
* This example search a text in all the tables of the document, 
* and show the matches in the messages pane.
*/
// @id = ch.banana.scripts.find
// @version = 1.3
// @date = 2019-12-06
// @publisher = Banana.ch SA
// @description = Find in whole accounting
// @description.it = Cerca in tutta la contabilità
// @description.de = Suchen in der gesamten Buchhaltung
// @description.fr = Chercher dans toute la comptabilité
// @task = app.command
// @inputdatasource = none
// @timeout = -1

/**
 * param values are loaded from Banana.document, edited through dialog and saved to Banana.document
 * This array object is like a map (associative array) i.e. "key":"value", see initParam()
 * Examples of keys: searchText, wholeText, ...
 */
var param = {};

/** Dialog's functions declaration */
var dialog = Banana.Ui.createUi("documents:742.ui"); // ch.banana.scripts.find.ui

/** Dialog Objects declaration */
var findNextButton = dialog.findChild('findNextButton');
var helpButton = dialog.findChild('helpButton');
var closeButton = dialog.findChild('closeButton');
var searchTextLineEdit = dialog.findChild('searchTextLineEdit');
var matchCaseCheckBox = dialog.findChild('matchCaseCheckBox');
var wholeTextCheckBox = dialog.findChild('wholeTextCheckBox');


dialog.checkdata = function () {
    var valid = true;

    if (searchTextLineEdit.text.length <= 0) {
        Banana.Ui.showInformation("Error", "Search text can't be empty");
        valid = false;
    }

    if (valid) {
        dialog.accept();
    }
};

dialog.showHelp = function () {
    Banana.Ui.showHelp("ch.banana.script.find");
};

dialog.closeDialog = function () {
    dialog.close();
};

/** Dialog's events declaration */
findNextButton.clicked.connect(dialog, dialog.checkdata);
helpButton.clicked.connect(dialog, dialog.showHelp);
closeButton.clicked.connect(dialog, dialog.closeDialog);

/** Main function */
function exec(inData) {
    //calls dialog
    // var rtnDialog = true;
    var rtnDialog = dialogExec();

    //search text in the whole accounting
    if (rtnDialog && Banana.document) {
        Banana.document.clearMessages();
        searchInTables();
    }
}

/** Show the dialog and set the parameters */
function dialogExec() {
    // Read saved script settings
    initParam();
    if (Banana.document) {
        var data = Banana.document.getScriptSettings();
        if (data.length > 0) {
            param = JSON.parse(data);
        }
    }

    // Text at cursor position
    var cursor = Banana.document.cursor;
    var columnName = cursor.tableName === 'Documents' && cursor.columnName == 'Attachments' ? 'Description' : cursor.columnName;
    param["searchText"] = Banana.document.value(cursor.tableName,cursor.rowNr,columnName);
    searchTextLineEdit.text = param["searchText"];
    // Set dialog parameters
    if (param["matchCase"] == "true")
        matchCaseCheckBox.checked = true;
    else
        matchCaseCheckBox.checked = false;
    if (param["wholeText"] == "true")
        wholeTextCheckBox.checked = true;
    else
        wholeTextCheckBox.checked = false;

    Banana.application.progressBar.pause();
    var dlgResult = dialog.exec();
    Banana.application.progressBar.resume();

    if (dlgResult !== 1)
        return false;

    // Read dialog parameters
    param["searchText"] = searchTextLineEdit.text;
    if (matchCaseCheckBox.checked)
        param["matchCase"] = "true";
    else
        param["matchCase"] = "false";
    if (wholeTextCheckBox.checked)
        param["wholeText"] = "true";
    else
        param["wholeText"] = "false";

    // Save script settings
    var paramString = JSON.stringify(param);
    var value = Banana.document.setScriptSettings(paramString);

    return true;
}

/** Initialize dialog values with default values */
function initParam() {
    param = {
        "searchText": "",
        "matchCase": "false",
        "wholeText": "false"
    };
}

/** Search a text in the accounting's tables */
function searchInTables() {
    var searchText = param["searchText"];
    if (param["matchCase"] === "false")
        searchText = searchText.toLowerCase();
    var tables = Banana.document.tableNames;
    // Tables
    for (var t=0; t < tables.length; t++) {
        var table = Banana.document.table(tables[t]);
        var columns = table.columnNames;
        // Rows
        for (var r=0; r < table.rowCount; r++) {
            // Columns
            for (var c=0; c < columns.length; c++) {
                var textFound = false;
                var text = table.value(r, columns[c]);
                if (param["matchCase"] === "false")
                    text = text.toLowerCase();
                // Find text
                if (param["wholeText"] === "true") {
                    if (text === searchText)
                        textFound = true;
                } else {
                    if (text.indexOf(searchText) >= 0)
                        textFound = true;
                }
                // Show message
                if (textFound) {
                    table.addMessage("Text \"" + param["searchText"] +
                        "\" found in \"" + table.value(r, columns[c]) + "\"", r, columns[c]);
                }
            }
        }
    }
}

- User interface for Find dialog


// Banana Accounting Extension Javascript
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>DlgFind</class>
 <widget class="QDialog" name="DlgFind">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>438</width>
    <height>193</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Find</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout_2">
   <item>
    <layout class="QGridLayout" name="gridLayout">
     <property name="horizontalSpacing">
      <number>40</number>
     </property>
     <item row="0" column="0">
      <widget class="QLabel" name="searchTextLabel">
       <property name="text">
        <string>Search &text</string>
       </property>
      </widget>
     </item>
     <item row="0" column="1">
      <widget class="QLineEdit" name="searchTextLineEdit"/>
     </item>
    </layout>
   </item>
   <item>
    <widget class="QGroupBox" name="groupBox">
     <property name="title">
      <string>Options</string>
     </property>
     <property name="flat">
      <bool>false</bool>
     </property>
     <property name="checkable">
      <bool>false</bool>
     </property>
     <layout class="QVBoxLayout" name="verticalLayout">
      <item>
       <widget class="QCheckBox" name="matchCaseCheckBox">
        <property name="text">
         <string>&Match case</string>
        </property>
       </widget>
      </item>
      <item>
       <widget class="QCheckBox" name="wholeTextCheckBox">
        <property name="text">
         <string>&Whole text</string>
        </property>
       </widget>
      </item>
     </layout>
    </widget>
   </item>
   <item>
    <spacer name="verticalSpacer">
     <property name="orientation">
      <enum>Qt::Vertical</enum>
     </property>
     <property name="sizeHint" stdset="0">
      <size>
       <width>20</width>
       <height>15</height>
      </size>
     </property>
    </spacer>
   </item>
   <item>
    <layout class="QHBoxLayout" name="horizontalLayout">
     <item>
      <spacer name="horizontalSpacer">
       <property name="orientation">
        <enum>Qt::Horizontal</enum>
       </property>
       <property name="sizeHint" stdset="0">
        <size>
         <width>80</width>
         <height>20</height>
        </size>
       </property>
      </spacer>
     </item>
     <item>
      <widget class="QPushButton" name="findNextButton">
       <property name="text">
        <string>&Find</string>
       </property>
      </widget>
     </item>
     <item>
      <widget class="QPushButton" name="helpButton">
       <property name="text">
        <string>Help</string>
       </property>
      </widget>
     </item>
     <item>
      <widget class="QPushButton" name="closeButton">
       <property name="text">
        <string>Close</string>
       </property>
      </widget>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <tabstops>
  <tabstop>matchCaseCheckBox</tabstop>
  <tabstop>findNextButton</tabstop>
 </tabstops>
 <resources/>
 <connections/>
</ui>

Export

Export tutorial1 javascript codes


// Banana Accounting Extension Javascript
// @id = ch.banana.apps.exportjavascriptcodestutorial1.js
// @api = 1.0
// @publisher = Banana.ch SA
// @description = Tutorial: Export javascript codes of the Tutorial 1 examples
// @task = export.file
// @doctype = *.*
// @docproperties = 
// @timeout = -1
// @exportfiletype = js

//Main function
function exec() {

    //Check if we are on an opened document
    if (!Banana.document) {
        return;
    }

    //Take the table Documents
    var documents = Banana.document.table('Documents');

    //We check if the table Documents exists, then we can take all the codes 
    //If the table Documents doesn't exists, then we stop the script execution
    if (!documents) {
        return;
    } else {

        //We use this variable to save all the codes
        var jsCode = '';

        jsCode += '// Copyright [2018] [Banana.ch SA - Lugano Switzerland]' + '\n';
        jsCode += '// ' + '\n';
        jsCode += '// Licensed under the Apache License, Version 2.0 (the "License");' + '\n';
        jsCode += '// you may not use this file except in compliance with the License.' + '\n';
        jsCode += '// You may obtain a copy of the License at' + '\n';
        jsCode += '// ' + '\n';
        jsCode += '//     http://www.apache.org/licenses/LICENSE-2.0' + '\n';
        jsCode += '// ' + '\n';
        jsCode += '// Unless required by applicable law or agreed to in writing, software' + '\n';
        jsCode += '// distributed under the License is distributed on an "AS IS" BASIS,' + '\n';
        jsCode += '// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.' + '\n';
        jsCode += '// See the License for the specific language governing permissions and' + '\n';
        jsCode += '// limitations under the License.' + '\n' + '\n' + '\n' + '\n' + '\n' + '\n' + '\n';

        //Function call to get all the tutorial's codes
        jsCode = getJavascriptCode(jsCode, documents);
    }

    return jsCode;
}




//Function that, for each tutorial's example, gets the javascript code and save it into the jsCode variable.
function getJavascriptCode(jsCode, documents) {

    //Read row by row the table Documents
    var len = documents.rowCount;
    for (var i = 0; i < len; i++) {

        //Create a variable for the row
        var tRow = documents.row(i);

        //We get some values
        var fName = Banana.document.info("Base", "FileName").replace(/^.*[\\\/]/, ''); //the file name (without path)
        var id = tRow.value("RowId"); //the id of the example
        var description = tRow.value("Description"); //the description of the example
        var attachments = tRow.value("Attachments"); //the javascript code of the example

        //We consider only the rows that contain an id, a description and an attachment
        if (id && description && attachments) {

            //At the beginning of each code, we insert some information
            jsCode += "/** " + '\n';
            jsCode += "    File:        " + fName + '\n';
            jsCode += "    Id:          " + id + '\n';
            jsCode += "    Description: " + description + '\n';
            jsCode += "*/" + '\n';

            //we add the code of the attachments
            jsCode += attachments;

            //At the end of each code, we insert some new lines
            jsCode += '\n' + '\n' + '\n' + '\n' + '\n' + '\n' + '\n';
        }
    }

    //Finally we return the variable containing all the codes of all the examples
    return jsCode;
}

Export tutorial1 javascript codes to HTML


// Banana Accounting Extension Javascript
// @id = ch.banana.apps.exporthtmljavascriptcodestutorial1.js
// @api = 1.0
// @publisher = Banana.ch SA
// @description = Tutorial: Export javascript codes of the Tutorial 1 examples in HTML
// @task = export.file
// @doctype = *.*
// @docproperties = 
// @timeout = -1
// @exportfiletype = html

//Main function
function exec() {

    //Check if we are on an opened document
    if (!Banana.document) {
        return;
    }

    //Take the table Documents
    var documents = Banana.document.table('Documents');

    //We check if the table Documents exists, then we can take all the codes 
    //If the table Documents doesn't exists, then we stop the script execution
    if (!documents) {
        return;
    } else {

        //We use this variable to save all the codes
        var jsCode = '';

        //Function call to get all the tutorial's codes
        jsCode = getJavascriptCode(jsCode, documents);
    }

    return jsCode;
}

//Function that, for each tutorial's example, gets the javascript code and save it into the jsCode variable.
function getJavascriptCode(jsCode, documents) {

    //Read row by row the table Documents
    var len = documents.rowCount;
    for (var i = 0; i < len; i++) {

        //Create a variable for the row
        var tRow = documents.row(i);

        //We get some values
        var fName = Banana.document.info("Base", "FileName").replace(/^.*[\\\/]/, ''); //the file name (without path)
        var section = tRow.value("Section"); // the section column used to define the title type
        var id = tRow.value("RowId"); //the id of the example
        var description = tRow.value("Description"); //the description of the example
        var attachments = tRow.value("Attachments"); //the javascript code of the example
        attachments = attachments.replace(/</g,'&lt;'); // replace the < symbol
        attachments = attachments.replace(/>/g,'&gt;'); // replace the > symbol

        //For tilte h2 we conside only rows with section h2
        if (section && section === "h2") {
            jsCode += '<h2>' + description + '</h2>\n';
        }
        
        //For js codes we consider only rows with section h3, id, description and attachment
        else if (section && section === "h3" && id && description && attachments) {
            jsCode += '<h3>' + description + '</h3>\n';
            jsCode += '<pre><code class="language-javascript">\n';
            jsCode += '// Banana Accounting Extension Javascript' + '\n';
            jsCode += attachments;
            jsCode += '\n';
            jsCode += '</code></pre>\n';
        }
    }

    //Finally we return the variable containing all the codes of all the examples
    return jsCode;
}

Help us improve the documentation

We welcome feedback on how to improve this page.

Tell us what theme needs a better explanation or how to clarify a topic.

Share this article: Twitter | Facebook | LinkedIn | Email