<window id="fypurchase">
	<reporttitle>Purchase:->Coffee Purchase Previous Years Comparison</reporttitle>
	<layout type="vertical">
		<layout type="horizontal">
			<daterange id = "dates" initial="23" /><!--Lifetime-->
			<label>Weight Unit:</label>
			<sqldrop id="unit" />
			<stretch />
		</layout>
		<webview id="report" />
	</layout>
	<menu name="File">
		<item id="print" shortcut="Ctrl+P">Print...</item>
	</menu>
	<program>
		<![CDATA[
			this.windowTitle = TTR("fypurchase", "Typica - Coffee Purchase Previous Years Comparison");
			/* Set Lifetime range. */
			var dateSelect = findChildObject(this, 'dates');
			var query = new QSqlQuery();
			query.exec("SELECT concat(EXTRACT(YEAR FROM time::date), '-01-01') FROM purchase WHERE time = (SELECT min(time) FROM purchase) UNION SELECT concat(EXTRACT(YEAR FROM 'now'::date), '-12-31') ORDER BY concat ASC");
			query.next();
			var lifetimeStartDate = query.value(0);
			query.next();
			var lifetimeEndDate = query.value(0);
			dateSelect.setLifetimeRange(lifetimeStartDate, lifetimeEndDate);
			query = query.invalidate();
			/* Enable printing */
			var view = findChildObject(this, 'report');
			var printMenu = findChildObject(this, 'print');
			printMenu.triggered.connect(function() {
				view.print();
			});
			/* Add units to unit selector and enable functionality */
			var unitBox = findChildObject(this, 'unit');
			unitBox.addItem(TTR("fypurchase", "Kg"));
			unitBox.addItem(TTR("fypurchase", "Lb"));
			unitBox.currentIndex = QSettings.value("script/report_unit", 1);
			unitBox['currentIndexChanged(int)'].connect(function() {
				QSettings.setValue("script/report_unit", unitBox.currentIndex);
				refresh();
			});
			/* Generate report */
			function refresh() {
				var buffer = new QBuffer;
				buffer.open(3);
				var output = new XmlWriter(buffer);
				output.writeStartDocument("1.0");
				output.writeDTD('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg.dtd">');
                output.writeStartElement("html");
                output.writeAttribute("xmlns", "http://www.w3.org/1999/xhtml");
                output.writeStartElement("head");
				output.writeTextElement("title", TTR("fypurchase", "Coffee Purchase Previous Years Comparison"));
				output.writeEndElement();
				output.writeStartElement("body");
				output.writeTextElement("h1", TTR("fypurchase", "Coffee Purchase Previous Years Comparison"));
				output.writeStartElement("table");
				output.writeAttribute("style", "page-break-after: auto; text-align: left");
				output.writeAttribute("rules", "groups");
				output.writeAttribute("cellpadding", "3px");
				output.writeStartElement("thead");
				output.writeStartElement("tr");
				output.writeEmptyElement("th");
				output.writeTextElement("th", TTR("fypurchase", "Sacks Purchased"));
				switch(unitBox.currentIndex) {
					case 0:
						output.writeTextElement("th", TTR("fypurchase", "Kg Purchased"));
						break;
					case 1:
						output.writeTextElement("th", TTR("fypurchase", "Lb Purchased"));
						break;
				}
				output.writeTextElement("th", TTR("fypurchase", "Cost"));
                                switch(unitBox.currentIndex) {
                                    case 0:
                                        output.writeTextElement("th", TTR("fypurchase", "Cost per Kg"));
                                        break;
                                    case 1:
                                        output.writeTextElement("th", TTR("fypurchase", "Cost per Lb"));
                                        break;
                                }
				output.writeEndElement(); //tr
				output.writeEndElement(); //thead
				output.writeStartElement("tbody");
				var sacktotal = 0;
				var unittotal = 0;
				var costtotal = 0;
				var query = new QSqlQuery();
				var dateRange = dateSelect.currentRange();
				var startYear = Number(dateRange[0].substr(0, 4));
				var endYear = Number(dateRange[dateRange.length - 1].substr(0, 4));
				for(var i = startYear; i <= endYear; i++)
				{
					output.writeStartElement("tr");
					output.writeAttribute("id", "y"+i);
					var q = "SELECT sum(quantity/(SELECT conversion FROM lb_bag_conversion WHERE item = purchase.item)), (sum(quantity) / :conversion)::numeric(12,2), sum(cost*quantity)::numeric(12,2) FROM purchase WHERE time >= '" + i + "-01-01' AND time < '" + (i+1) + "-01-01'";
					query.prepare(q);
					query.bind(":conversion", unitBox.currentIndex == 0 ? 2.2 : 1);
					query.exec();
					query.next();
					output.writeStartElement("th");
					output.writeStartElement("a");
					output.writeAttribute("href", "typica://script/y" + i);
					output.writeCharacters(i);
					output.writeEndElement(); //a
					output.writeEndElement(); //th
					output.writeTextElement("td", query.value(0));
					output.writeTextElement("td", query.value(1));
					output.writeTextElement("td", Number(query.value(2)).toFixed(2));
					sacktotal += Number(query.value(0));
					unittotal += Number(query.value(1));
					costtotal += Number(query.value(2));
                                        output.writeTextElement("td", (Number(query.value(2))/Number(query.value(1))).toFixed(2));
					output.writeEndElement(); //tr
				}
				query = query.invalidate();
				output.writeEndElement(); //tbody
				output.writeStartElement("tfoot");
				output.writeTextElement("th", TTR("fypurchase", "Totals:"));
				output.writeTextElement("td", sacktotal.toFixed(2));
				output.writeTextElement("td", unittotal.toFixed(2));
				output.writeTextElement("td", costtotal.toFixed(2));
				output.writeEndElement(); //tfoot
				output.writeEndElement(); //table
				output.writeEndElement(); //body
				output.writeEndElement(); //html
				output.writeEndDocument();
				view.setContent(buffer);
				buffer.close();
			}
			refresh();
			/* Update report as needed. */
			dateSelect.rangeUpdated.connect(function() {
				refresh();
			});
			/* Expand year data */
			var expandedYears = new Array();
			var expandYear = function(url) {
				if(expandedYears.indexOf(url) == -1) {
					expandedYears.push(url);
					var element = new WebElement(view.findFirstElement("#" + url));
					var year = url.slice(1,url.length);
					var details = '<tr><td /><td colspan="3"><table><tr><th>Id</th><th>' + TTR("fypurchase", "Invoice") +
                                        '</th><th>' + TTR("fypurchase", "Vendor") +
                                        '</th><th>' + TTR("fypurchase", "Cost") +
                                        '</th></tr>';
					q = "SELECT id, invoice, vendor, (SELECT sum(cost) FROM invoice_items WHERE invoice_id = id) FROM invoices WHERE time >= '" + year + "-01-01' AND time <= '" + year + "-12-31'";
					var query = new QSqlQuery();
					query.exec(q);
					while(query.next())
					{
						details += '<tr><td><a href="typica://script/i' + query.value(0) + '">' + query.value(0) + '</a></td>';
						details += '<td>' + query.value(1) + '</td>';
						details += '<td>' + query.value(2) + '</td>';
						details += '<td>' + Number(query.value(3)).toFixed(2) + '</td></tr>';
					}
					query = query.invalidate();
					details += '</table></td></tr>'
					element.appendOutside(details);
				}
			};
			/* Open invoices */
			var openInvoice = function(url) {
				var arg = url.slice(1, url.length);
				var info = createWindow("invoiceinfo");
				info.setInvoiceID(arg);
				var query = new QSqlQuery();
				query.exec("SELECT time, invoice, vendor FROM invoices WHERE id = " + arg);
				query.next();
				var timefield = findChildObject(info, 'date');
				timefield.text = query.value(0);
				var vendorfield = findChildObject(info, 'vendor');
				vendorfield.text = query.value(2);
				var invoicefield = findChildObject(info, 'invoice');
				invoicefield.text = query.value(1);
				var itemtable = findChildObject(info, 'itemtable');
				itemtable.setQuery("SELECT record_type, item_id, description, (SELECT reference FROM items WHERE id = item_id) AS reference, (SELECT cost FROM purchase WHERE item = item_id) AS unit_cost, (SELECT quantity FROM purchase WHERE item = item_id) AS quantity, ((SELECT quantity FROM purchase WHERE item = item_id)/(SELECT conversion FROM lb_bag_conversion WHERE item = item_id))::numeric(12,2) AS sacks, cost FROM invoice_items WHERE invoice_id = " + arg + " AND record_type = 'PURCHASE' UNION SELECT record_type, NULL, description, NULL, NULL, NULL, NULL, cost FROM invoice_items WHERE invoice_id = " + arg + " AND record_type = 'FEE' ORDER BY item_id");
				query = query.invalidate();
			};
			/* Dispatch script link clicks */
			view.scriptLinkClicked.connect(function(url) {
				var linkType = url[0];
				switch(linkType) {
					case 'y':
						expandYear(url);
						break
					case 'i':
						openInvoice(url);
						break;
				}
			});
		]]>
	</program>
</window>
