more postgres migration
more postgres migration

<?php <?php
include_once ("./lib/common.inc.php"); include_once ("./lib/common.inc.php");
if ($_REQUEST['agency']) { if ($_REQUEST['agency']) {
$agency = htmlentities(strip_tags($_REQUEST['agency'])); $agency = htmlentities(strip_tags($_REQUEST['agency']));
include_header($agency); include_header($agency);
echo '<center><h1>'.$agency.'</h1></center>'; echo '<center><h1>'.$agency.'</h1></center>';
// MethodCountGraph($agency); // MethodCountGraph($agency);
// CnCGraph($agency); // CnCGraph($agency);
// MethodValueGraph($agency); // MethodValueGraph($agency);
/* biggest contracts /* biggest contracts
spending by year spending by year
spending by industry/category spending by industry/category
spending by supplier spending by supplier
spread procurement methods (stacked bar graph) spread procurement methods (stacked bar graph)
+ percent consultancies + percent confidential (bar graph) + percent consultancies + percent confidential (bar graph)
Average value by procurement type Average value by procurement type
--- info --- info
website, procurement plan, annual reports website, procurement plan, annual reports
Breakdown of divisions/branches Breakdown of divisions/branches
Breakdown percentage,number,value by procurement type Breakdown percentage,number,value by procurement type
Histograph, overlaying number value reported per week over X years Histograph, overlaying number value reported per week over X years
Compliance statistics: amendments, delay in reporting average and number completely late */ Compliance statistics: amendments, delay in reporting average and number completely late */
$query = 'SELECT "CNID", "description", "value", "agencyName", "category", $query = 'SELECT "CNID", "description", "value", "agencyName", "category",
"contractStart", "supplierName" "contractStart", "supplierName"
FROM contractnotice FROM contractnotice
WHERE "agencyName" = :agency WHERE "agencyName" like :agency
ORDER BY "value" DESC limit 100'; ORDER BY "value" DESC limit 100';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":agency", $agency); $query->bindParam(":agency", $agency);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
echo "<table> <thead> echo "<table> <thead>
<tr> <tr>
<th>Contract Notice Number</th> <th>Contract Notice Number</th>
<th>Contract Description</th> <th>Contract Description</th>
<th>Total Contract Value</th> <th>Total Contract Value</th>
<th>Agency</th> <th>Agency</th>
<th>Contract Start Date</th> <th>Contract Start Date</th>
<th>Supplier</th> <th>Supplier</th>
</tr> </tr>
</thead>"; </thead>";
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
$value = number_format(doubleval($row['value']), 2); $value = number_format(doubleval($row['value']), 2);
echo ("<tr> echo ("<tr>
<td><a href=\"displayContract.php?CNID={$row['CNID']}\">{$row['CNID']}</a></td> <td><a href=\"displayContract.php?CNID={$row['CNID']}\">{$row['CNID']}</a></td>
<td><b>{$row['description']}</b></a></td> <td><b>{$row['description']}</b></a></td>
<td>\$$value</td><td>{$row['agencyName']}</td> <td>\$$value</td><td>{$row['agencyName']}</td>
<td>{$row['contractStart']}</td> <td>{$row['contractStart']}</td>
<td>{$row['supplierName']}</td> <td>{$row['supplierName']}</td>
</tr>"); </tr>");
} }
echo "</table>"; echo "</table>";
} else { } else {
/* /*
split by portfolio split by portfolio
*/ */
include_header("Agencies"); include_header("Agencies");
agenciesGraph(); agenciesGraph();
$query = 'SELECT SUM("value"), "agencyName" $query = 'SELECT SUM("value"), "agencyName"
FROM contractnotice FROM contractnotice
WHERE "childCN" is null WHERE "childCN" is null
GROUP BY "agencyName" '; GROUP BY "agencyName" ';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
echo "<table> <thead> echo "<table> <thead>
<tr> <tr>
<th>Agency</th> <th>Agency</th>
<th>Total Contracts Value</th> <th>Total Contracts Value</th>
</tr> </tr>
</thead>"; </thead>";
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
$value = number_format(doubleval($row[0]), 2); $value = number_format(doubleval($row[0]), 2);
$agency = stripslashes($row[1]); $agency = stripslashes($row[1]);
echo ("<tr><td><b><a href=\"displayAgency.php?agency={$agency}\">{$agency}</a></b></td><td>\$$value</td></tr>\n"); echo ("<tr><td><b><a href=\"displayAgency.php?agency={$agency}\">{$agency}</a></b></td><td>\$$value</td></tr>\n");
} }
echo "</table>"; echo "</table>";
} }
include_footer(); include_footer();
?> ?>
   
<?php <?php
date_default_timezone_set("Australia/ACT"); date_default_timezone_set("Australia/ACT");
error_reporting(E_ALL ^ E_NOTICE); error_reporting(E_ALL ^ E_NOTICE);
$conn = new PDO("pgsql:dbname=contractDashboard;user=postgres;password=snmc;host=localhost"); $conn = new PDO("pgsql:dbname=contractDashboard;user=postgres;password=snmc;host=localhost");
if (!$conn) { if (!$conn) {
die("A database error occurred.\n"); die("A database error occurred.\n");
} }
define('ROOT', pathinfo(__FILE__, PATHINFO_DIRNAME)); define('ROOT', pathinfo(__FILE__, PATHINFO_DIRNAME));
if (strstr($_SERVER['PHP_SELF'], "labs/")) { if (strstr($_SERVER['PHP_SELF'], "labs/")) {
$basePath = "../"; $basePath = "../";
} }
require ROOT . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'openid.php'; require ROOT . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'openid.php';
$openid = new LightOpenID($_SERVER['HTTP_HOST']); $openid = new LightOpenID($_SERVER['HTTP_HOST']);
function login() { function login() {
global $openid; global $openid;
if (!$openid->mode) { if (!$openid->mode) {
$openid->required = array('contact/email'); $openid->required = array('contact/email');
$openid->identity = 'https://www.google.com/accounts/o8/id'; $openid->identity = 'https://www.google.com/accounts/o8/id';
header('Location: ' . $openid->authUrl()); header('Location: ' . $openid->authUrl());
} }
} }
function auth() { function auth() {
global $openid; global $openid;
if ($_SESSION['authed'] == true) { if ($_SESSION['authed'] == true) {
return true; return true;
} }
if ($openid->mode) { if ($openid->mode) {
$attr = $openid->getAttributes(); $attr = $openid->getAttributes();
if ($attr['contact/email'] != 'maxious@gmail.com') { if ($attr['contact/email'] != 'maxious@gmail.com') {
die('Access Denied'); die('Access Denied');
} else { } else {
$_SESSION['authed'] = true; $_SESSION['authed'] = true;
} }
} else { } else {
login(); login();
} }
} }
// $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function databaseError($errMsg) { function databaseError($errMsg) {
if ($errMsg[2] != "") { if ($errMsg[2] != "") {
echo '<div class="alert-message error">'; echo '<div class="alert-message error">';
die(print_r($errMsg, true)); die(print_r($errMsg, true));
echo "</div>"; echo "</div>";
} }
} }
function ucsmart($str) { function ucsmart($str) {
$shortWords = Array("The", "Pty", "Ltd", "Inc", "Red", "Oil", "A", "An", "And", "At", "For", "In" $shortWords = Array("The", "Pty", "Ltd", "Inc", "Red", "Oil", "A", "An", "And", "At", "For", "In"
, "Of", "On", "Or", "The", "To", "With"); , "Of", "On", "Or", "The", "To", "With");
$strArray = explode(" ", preg_replace("/(?<=(?<!:|’s)\W) $strArray = explode(" ", preg_replace("/(?<=(?<!:|’s)\W)
(A|An|And|At|For|In|Of|On|Or|The|To|With) (A|An|And|At|For|In|Of|On|Or|The|To|With)
(?=\W)/e", 'strtolower("$1")', ucwords(strtolower($str)))); (?=\W)/e", 'strtolower("$1")', ucwords(strtolower($str))));
foreach ($strArray as &$word) { foreach ($strArray as &$word) {
if (strlen($word) <= 4 && !in_array($word, $shortWords)) if (strlen($word) <= 4 && !in_array($word, $shortWords))
$word = strtoupper($word); $word = strtoupper($word);
} }
return implode(" ", $strArray); return implode(" ", $strArray);
} }
function percent($num_amount, $num_total) { function percent($num_amount, $num_total) {
$count1 = $num_amount / $num_total; $count1 = $num_amount / $num_total;
$count2 = $count1 * 100; $count2 = $count1 * 100;
$count = number_format($count2, 2); $count = number_format($count2, 2);
return $count; return $count;
} }
function array_sum_all($a) { function array_sum_all($a) {
if (!is_array($a)) if (!is_array($a))
return $a; return $a;
foreach ($a as $key => $value) foreach ($a as $key => $value)
$totale += array_sum_all($value); $totale += array_sum_all($value);
return $totale; return $totale;
} }
// magic query modifiers // magic query modifiers
$agency = filter_var($_REQUEST['agency'], FILTER_SANITIZE_STRING); $agency = filter_var($_REQUEST['agency'], FILTER_SANITIZE_STRING);
if ($agency != "") if ($agency != "")
$agencyQ = "agencyName = '" . $agency . "' AND "; $agencyQ = "agencyName = '" . $agency . "' AND ";
$supplier = filter_var($_REQUEST['supplier'], FILTER_SANITIZE_STRING); $supplier = filter_var($_REQUEST['supplier'], FILTER_SANITIZE_STRING);
if ($supplier != "") { if ($supplier != "") {
$supplierParts = explode("-", $supplier); $supplierParts = explode("-", $supplier);
$supplierName = "%" . $supplierParts[1] . "%"; $supplierName = "%" . $supplierParts[1] . "%";
$supplierABN = $supplierParts[0]; $supplierABN = $supplierParts[0];
if ($supplierParts[0] > 0) if ($supplierParts[0] > 0)
$supplierQ = ' "supplierABN" = :supplierABN AND '; $supplierQ = ' "supplierABN" = :supplierABN AND ';
else else
$supplierQ = ' "supplierName" LIKE :supplierName AND '; $supplierQ = ' "supplierName" LIKE :supplierName AND ';
} }
$startYear = 2007; $startYear = 2007;
$year = filter_var($_REQUEST['year'], FILTER_SANITIZE_NUMBER_INT); $year = filter_var($_REQUEST['year'], FILTER_SANITIZE_NUMBER_INT);
if ($year != "") if ($year != "") {
$yearQ = "YEAR(publishDate) = " . $year . " AND "; $yearQ = "YEAR(publishDate) = " . $year . " AND ";
  }
$standardQ = ' "childCN" is null '; // AND YEAR(contractStart) >= 2007 AND YEAR(contractStart) <= 2010'; $standardQ = ' "childCN" is null '; // AND YEAR(contractStart) >= 2007 AND YEAR(contractStart) <= 2010';
$start = 0.0; $start = 0.0;
function local_url() { function local_url() {
return "http://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/"; return "http://" . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/";
} }
function include_header($title) { function include_header($title) {
global $start; global $start;
?> ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> "http://www.w3.org/TR/html4/strict.dtd">
<html> <html>
<head> <head>
<title><?php echo $title; ?> - Contract Dashboard</title> <title><?php echo $title; ?> - Contract Dashboard</title>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="bootstrap-responsive.css"> <link rel="stylesheet" type="text/css" href="bootstrap-responsive.css">
<!-- Le HTML5 shim, for IE6-8 support of HTML elements --> <!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]> <!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]--> <![endif]-->
<script type="text/javascript" src="lib/bsn.AutoSuggest_2.1.3_comp.js" charset="utf-8"></script> <script type="text/javascript" src="lib/bsn.AutoSuggest_2.1.3_comp.js" charset="utf-8"></script>
<link rel="stylesheet" href="autosuggest_inquisitor.css" type="text/css" media="screen" charset="utf-8" /> <link rel="stylesheet" href="autosuggest_inquisitor.css" type="text/css" media="screen" charset="utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript"> <script type="text/javascript">
$(document).ready(function() $(document).ready(function()
{ {
//hide the all of the element with class msg_body //hide the all of the element with class msg_body
$(".msg_body").hide(); $(".msg_body").hide();
//toggle the componenet with class msg_body //toggle the componenet with class msg_body
$(".msg_head").click(function() $(".msg_head").click(function()
{ {
$(this).next(".msg_body").slideToggle(600); $(this).next(".msg_body").slideToggle(600);
}); });
}); });
</script> </script>
<style type="text/css" title="currentStyle"> <style type="text/css" title="currentStyle">
@import "media/css/demo_table.css"; @import "media/css/demo_table.css";
</style> </style>
<script type="text/javascript" language="javascript" src="media/js/jquery.dataTables.js"></script> <script type="text/javascript" language="javascript" src="media/js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" src="lib/bootstrap-dropdown.js"></script> <script type="text/javascript" language="javascript" src="lib/bootstrap-dropdown.js"></script>
<script type="text/javascript" charset="utf-8"> <script type="text/javascript" charset="utf-8">
jQuery.fn.dataTableExt.aTypes.unshift( jQuery.fn.dataTableExt.aTypes.unshift(
function ( sData ) function ( sData )
{ {
var sValidChars = "0123456789.-,"; var sValidChars = "0123456789.-,";
var Char; var Char;
/* Check the numeric part */ /* Check the numeric part */
for ( i=1 ; i<sData.length ; i++ ) for ( i=1 ; i<sData.length ; i++ )
{ {
Char = sData.charAt(i); Char = sData.charAt(i);
if (sValidChars.indexOf(Char) == -1) if (sValidChars.indexOf(Char) == -1)
{ {
return null; return null;
} }
} }
/* Check prefixed by currency */ /* Check prefixed by currency */
if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' ) if ( sData.charAt(0) == '$' || sData.charAt(0) == '£' )
{ {
return 'currency'; return 'currency';
} }
return null; return null;
} }
); );
jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a,b) { jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a,b) {
/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */ /* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
var x = a == "-" ? 0 : a.replace( /,/g, "" ); var x = a == "-" ? 0 : a.replace( /,/g, "" );
var y = b == "-" ? 0 : b.replace( /,/g, "" ); var y = b == "-" ? 0 : b.replace( /,/g, "" );
/* Remove the currency sign */ /* Remove the currency sign */
x = x.substring( 1 ); x = x.substring( 1 );
y = y.substring( 1 ); y = y.substring( 1 );
/* Parse and return */ /* Parse and return */
x = parseFloat( x ); x = parseFloat( x );
y = parseFloat( y ); y = parseFloat( y );
return x - y; return x - y;
}; };
jQuery.fn.dataTableExt.oSort['currency-desc'] = function(a,b) { jQuery.fn.dataTableExt.oSort['currency-desc'] = function(a,b) {
/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */ /* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
var x = a == "-" ? 0 : a.replace( /,/g, "" ); var x = a == "-" ? 0 : a.replace( /,/g, "" );
var y = b == "-" ? 0 : b.replace( /,/g, "" ); var y = b == "-" ? 0 : b.replace( /,/g, "" );
/* Remove the currency sign */ /* Remove the currency sign */
x = x.substring( 1 ); x = x.substring( 1 );
y = y.substring( 1 ); y = y.substring( 1 );
/* Parse and return */ /* Parse and return */
x = parseFloat( x ); x = parseFloat( x );
y = parseFloat( y ); y = parseFloat( y );
return y - x; return y - x;
}; };
$(document).ready(function() { $(document).ready(function() {
$('table').dataTable(); $('table').dataTable();
} ); } );
</script> </script>
<link type="text/css" rel="stylesheet" href="style.css"> <link type="text/css" rel="stylesheet" href="style.css">
</head> </head>
<body> <body>
<div class="navbar"> <div class="navbar">
<div class="navbar-inner"> <div class="navbar-inner">
<div class="container-fluid"> <div class="container-fluid">
<a class="brand" href="#">contract dashboard</a> <a class="brand" href="#">contract dashboard</a>
<ul class="nav"> <ul class="nav">
<li><a href="displayAgency.php">agencies</a></li> <li><a href="displayAgency.php">agencies</a></li>
<li><a href="displaySupplier.php">suppliers</a></li> <li><a href="displaySupplier.php">suppliers</a></li>
<li><a href="displayCategory.php">categories</a></li> <li><a href="displayCategory.php">categories</a></li>
<li><a href="displayCalendar.php">time periods</a></li> <li><a href="displayCalendar.php">time periods</a></li>
<!-- <li class="dropdown"> <!-- <li class="dropdown">
<a href="#" class="dropdown-toggle">metrics</a> <a href="#" class="dropdown-toggle">metrics</a>
<ul class="dropdown-menu">--> <ul class="dropdown-menu">-->
<li><a href="displayProcurementMethod.php">tenderm</a></li> <li><a href="displayProcurementMethod.php">tenderm</a></li>
<li><a href="displayConfidentialities.php">confidentiality</a></li> <li><a href="displayConfidentialities.php">confidentiality</a></li>
<li><a href="displayConsultancies.php">consultancies</a></li> <li><a href="displayConsultancies.php">consultancies</a></li>
<li><a href="displayAmendments.php">amendments</a></li> <li><a href="displayAmendments.php">amendments</a></li>
<li><a href="displayMap.php">geo</a></li> <li><a href="displayMap.php">geo</a></li>
</ul> </ul>
<form method="post" action="search.php" class="pull-right"> <form method="post" action="search.php" class="pull-right">
<input type="text" id="searchKeyword" name="searchKeyword" value="" placeholder="Search" /> <input type="text" id="searchKeyword" name="searchKeyword" value="" placeholder="Search" />
<input type="hidden" id="searchID" name="searchID" value=""/> <input type="hidden" id="searchID" name="searchID" value=""/>
</form> </form>
</div> </div>
</div><!-- /topbar-inner --> </div><!-- /topbar-inner -->
</div><!-- /topbar --> </div><!-- /topbar -->
</div><!-- /topbar-wrapper --> </div><!-- /topbar-wrapper -->
<script type="text/javascript"> <script type="text/javascript">
var options_xml = { var options_xml = {
script: function (input) { return "search_autosuggest.php?input="+input; }, script: function (input) { return "search_autosuggest.php?input="+input; },
varname:"input", varname:"input",
callback: function (obj) { document.getElementById('searchID').value = obj.id; } callback: function (obj) { document.getElementById('searchID').value = obj.id; }
}; };
var as_xml = new bsn.AutoSuggest('searchKeyword', options_xml); var as_xml = new bsn.AutoSuggest('searchKeyword', options_xml);
</script> </script>
<div class="container-fluid"> <div class="container-fluid">
<div class="row-fluid"> <div class="row-fluid">
<div class="span3"> <div class="span3">
<div class="well sidebar-nav"> <div class="well sidebar-nav">
<li class="nav-header">Filter by:</li> <li class="nav-header">Filter by:</li>
<li>2008</li> <li>2008</li>
</div> </div>
</div> </div>
<div class="span9"> <div class="span9">
<?php <?php
$start = (float) array_sum(explode(' ', microtime())); $start = (float) array_sum(explode(' ', microtime()));
} }
function include_footer() { function include_footer() {
global $start; global $start;
$end = (float) array_sum(explode(' ', microtime())); $end = (float) array_sum(explode(' ', microtime()));
echo '</div> <footer>' . "Processing time: " . sprintf("%.4f", ($end - $start)) . " seconds" . ' <footer>'; echo '</div> <footer>' . "Processing time: " . sprintf("%.4f", ($end - $start)) . " seconds" . ' <footer>';
if (strpos($_SERVER['SERVER_NAME'], ".gs")) { if (strpos($_SERVER['SERVER_NAME'], ".gs")) {
?> ?>
<script type="text/javascript"> <script type="text/javascript">
var _gaq = _gaq || []; var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-12341040-3']); _gaq.push(['_setAccount', 'UA-12341040-3']);
_gaq.push(['_trackPageview']); _gaq.push(['_trackPageview']);
(function() { (function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})(); })();
</script> </script>
<?php <?php
} }
echo '</div> </div></body> </html>'; echo '</div> </div></body> </html>';
} }
include ("graphs.inc.php"); include ("graphs.inc.php");
   
<?php <?php
$includedFlot = false; $includedFlot = false;
   
function includeFlot() { function includeFlot() {
if (!$includedFlot) { if (!$includedFlot) {
echo ' <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="lib/flot/excanvas.min.js"></script><![endif]--> echo ' <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="lib/flot/excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.js"></script> <script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.pie.js"></script> <script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.pie.js"></script>
<script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.selection.js"></script> <script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.selection.js"></script>
<script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.stack.js"></script> <script language="javascript" type="text/javascript" src="lib/flot/jquery.flot.stack.js"></script>
   
'; ';
$includedFlot = true; $includedFlot = true;
} }
} }
   
function CNDistributionGraph() { function CNDistributionGraph() {
global $conn; global $conn;
includeFlot(); includeFlot();
?> ?>
<center><div id="cndist" style="width:900px;height:550px"></div></center> <center><div id="cndist" style="width:900px;height:550px"></div></center>
<script type="text/javascript"> <script type="text/javascript">
var placeholder = $("#cndist"); var placeholder = $("#cndist");
$(function () { $(function () {
   
var d1 = []; var d1 = [];
var d2 = []; var d2 = [];
<?php <?php
$query = 'select cnid, count(*) from $query = 'select cnid, count(*) from
(select ("CNID"::integer - MOD("CNID"::integer,100)) as cnid (select ("CNID"::integer - MOD("CNID"::integer,100)) as cnid
from contractnotice where "CNID"::integer < 999999 from contractnotice where "CNID"::integer < 999999
and "CNID" not like \'%-A%\' and "CNID" not like \'%-A%\'
and "parentCN" is null) as a group by cnid order by cnid'; and "parentCN" is null) as a group by cnid order by cnid';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
$errors = $conn->errorInfo(); $errors = $conn->errorInfo();
if ($errors[2] != "") { if ($errors[2] != "") {
echo("Export terminated, db error" . print_r($errors, true)); echo("Export terminated, db error" . print_r($errors, true));
return Array(); return Array();
} }
   
foreach ($query->fetchAll() as $delta) { foreach ($query->fetchAll() as $delta) {
   
echo "d1.push([ " . intval($delta['cnid']) . ", " . intval($delta['count']) . "]); \n"; echo "d1.push([ " . intval($delta['cnid']) . ", " . intval($delta['count']) . "]); \n";
}; };
$query = 'select cnid, count(*) from (select ("CNID"::integer - MOD("CNID"::integer,100)) as cnid $query = 'select cnid, count(*) from (select ("CNID"::integer - MOD("CNID"::integer,100)) as cnid
from contractnotice where "CNID" not like \'%-A%\' and "parentCN" is not null) from contractnotice where "CNID" not like \'%-A%\' and "parentCN" is not null)
as a group by cnid order by cnid'; as a group by cnid order by cnid';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
$errors = $conn->errorInfo(); $errors = $conn->errorInfo();
if ($errors[2] != "") { if ($errors[2] != "") {
echo("Export terminated, db error" . print_r($errors, true)); echo("Export terminated, db error" . print_r($errors, true));
return Array(); return Array();
} }
   
foreach ($query->fetchAll() as $delta) { foreach ($query->fetchAll() as $delta) {
   
echo "d2.push([ " . intval($delta['cnid']) . ", " . intval($delta['count']) . "]); \n"; echo "d2.push([ " . intval($delta['cnid']) . ", " . intval($delta['count']) . "]); \n";
}; };
d1d2Graph(); d1d2Graph();
} }
function d1d2Graph($time = false) { function d1d2Graph($time = false) {
?> ?>
   
var data = [ var data = [
{ {
data: d1, data: d1,
series: { series: {
lines: { show: true }, lines: { show: true },
points: { show: true } points: { show: true }
} }
<?php if (!$time){ <?php if (!$time){
echo ',bars: { show: true }'; echo ',bars: { show: true }';
}?> }?>
}, },
{ {
data: d2, data: d2,
series: { series: {
lines: { show: true }, lines: { show: true },
points: { show: true } points: { show: true }
} }
<?php if (!$time){ <?php if (!$time){
echo ',bars: { show: true }'; echo ',bars: { show: true }';
} else { } else {
echo ',yaxis: 2'; echo ',yaxis: 2';
} }
?> ?>
}] }]
; ;
var options = var options =
{ {
grid: { hoverable: true, clickable: true, labelMargin: 17 }, grid: { hoverable: true, clickable: true, labelMargin: 17 },
selection: { mode: "x" }<?php if ($time){ selection: { mode: "x" }<?php if ($time){
echo ', xaxis: { echo ', xaxis: {
mode: "time" mode: "time"
}';} else { }';} else {
echo 'series: { echo 'series: {
stack: true stack: true
},'; },';
} ?> } ?>
}; };
   
placeholder.bind("plotselected", function (event, ranges) { placeholder.bind("plotselected", function (event, ranges) {
plot = $.plot(placeholder, data, plot = $.plot(placeholder, data,
$.extend(true, {}, options, { $.extend(true, {}, options, {
xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to } xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to }
})); }));
}); });
var previousPoint = null; var previousPoint = null;
placeholder.bind("plothover", function (event, pos, item) { placeholder.bind("plothover", function (event, pos, item) {
$("#x").text(pos.x.toFixed(2)); $("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2)); $("#y").text(pos.y.toFixed(2));
if (item) { if (item) {
if (previousPoint != item.dataIndex) { if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex; previousPoint = item.dataIndex;
$("#tooltip").remove(); $("#tooltip").remove();
var x = item.datapoint[0].toFixed(2), var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2); y = item.datapoint[1].toFixed(2);
showTooltip(item.pageX, item.pageY, showTooltip(item.pageX, item.pageY,
item.series.label + " of " + x + " = " + y); item.series.label + " of " + x + " = " + y);
} }
} }
else { else {
$("#tooltip").remove(); $("#tooltip").remove();
previousPoint = null; previousPoint = null;
} }
}); });
   
var plot = $.plot(placeholder, data, var plot = $.plot(placeholder, data,
options); options);
}); });
   
function showTooltip(x, y, contents) { function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css( { $('<div id="tooltip">' + contents + '</div>').css( {
position: 'absolute', position: 'absolute',
display: 'none', display: 'none',
top: y + 5, top: y + 5,
left: x + 5, left: x + 5,
border: '1px solid #fdd', border: '1px solid #fdd',
padding: '2px', padding: '2px',
'background-color': '#fee', 'background-color': '#fee',
opacity: 0.80 opacity: 0.80
}).appendTo("body").fadeIn(200); }).appendTo("body").fadeIn(200);
} }
</script> </script>
<?php <?php
} }
   
function agenciesGraph() { function agenciesGraph() {
   
global $conn; global $conn;
includeFlot(); includeFlot();
$query = 'SELECT SUM("value") as val, MAX(contractnotice."agencyName") as agencyname FROM contractnotice join agency_nametoabn on contractnotice."agencyName"=agency_nametoabn."agencyName" WHERE "childCN" is null $query = 'SELECT SUM("value") as val, MAX(contractnotice."agencyName") as agencyname FROM contractnotice join agency_nametoabn on contractnotice."agencyName"=agency_nametoabn."agencyName" WHERE "childCN" is null
GROUP BY abn ORDER BY SUM("value") DESC'; GROUP BY abn ORDER BY SUM("value") DESC';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
$errors = $conn->errorInfo(); $errors = $conn->errorInfo();
if ($errors[2] != "") { if ($errors[2] != "") {
echo("Export terminated, db error" . print_r($errors, true)); echo("Export terminated, db error" . print_r($errors, true));
return Array(); return Array();
} }
?> ?>
<script type="text/javascript"> <script type="text/javascript">
$(function () { $(function () {
// data // data
var data = [ var data = [
<?php <?php
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
echo '{ label: "' . $row['agencyname'] . '", data: ' . doubleval($row["val"]) . '},'; echo '{ label: "' . $row['agencyname'] . '", data: ' . doubleval($row["val"]) . '},';
} }
?> ?>
]; ];
// GRAPH 7 // GRAPH 7
$.plot($("#graph7"), data, $.plot($("#graph7"), data,
{ {
series: { series: {
pie: { pie: {
show: true, show: true,
radius: 1, radius: 1,
tilt: 0.75, tilt: 0.75,
label: { label: {
show: true, show: true,
radius: 1, radius: 1,
formatter: function(label, series){ formatter: function(label, series){
return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+': '+Math.round(series.percent)+'%</div>'; return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+': '+Math.round(series.percent)+'%</div>';
}, },
background: { background: {
opacity: 0.5, opacity: 0.5,
color: '#000' color: '#000'
} }
}, },
combine: { combine: {
color: '#999', color: '#999',
threshold: 0.012 threshold: 0.012
} }
} }
}, },
legend: { legend: {
show: false show: false
} }
}); });
}); });
</script> </script>
<div id="graph7" style="width:900px;height:550px"></div> <div id="graph7" style="width:900px;height:550px"></div>
   
<?php <?php
} }
   
; ;
   
function agencySuppliersGraph($agency) { function agencySuppliersGraph($agency) {
   
global $conn; global $conn;
$agency = "AusAid"; $agency = "AusAid";
$topX = 15; $topX = 15;
$query = 'SELECT SUM(value) as val, "supplierName" FROM contractnotice WHERE (extract ("YEAR" from "contractStart") >= :startYear) AND "childCN" is null AND "agencyName" = :agency $query = 'SELECT SUM(value) as val, "supplierName" FROM contractnotice WHERE extract ("YEAR" from "contractStart") >= :startYear AND "childCN" is null AND "agencyName" like :agency
GROUP BY lower(supplierName) ORDER BY val DESC limit $topX'; GROUP BY lower(supplierName) ORDER BY val DESC limit $topX';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":startYear", $startYear); $query->bindParam(":startYear", $startYear);
$query->bindParam(":agency", $agency); $query->bindParam(":agency", $agency);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
$suppliers = Array(); $suppliers = Array();
$values = Array(); $values = Array();
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
$suppliers[] = ucsmart($row['supplierName']); $suppliers[] = ucsmart($row['supplierName']);
$values[] = doubleval($row["val"]); $values[] = doubleval($row["val"]);
} }
   
   
$query = 'SELECT sum(a.val) as value, count(1) as count from (SELECT SUM(value) as val, "supplierName" FROM contractnotice WHERE (extract ("YEAR" from "contractStart") >= :startYear) AND "childCN" is null and "agencyName" = :agency $query = 'SELECT sum(a.val) as value, count(1) as count from (SELECT SUM(value) as val, "supplierName" FROM contractnotice WHERE (extract ("YEAR" from "contractStart") >= :startYear) AND "childCN" is null and "agencyName" like :agency
GROUP BY lower("supplierName") ORDER BY val DESC LIMIT 18446744073709551610 OFFSET $topX) as a'; GROUP BY lower("supplierName") ORDER BY val DESC LIMIT 18446744073709551610 OFFSET $topX) as a';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":startYear", $startYear); $query->bindParam(":startYear", $startYear);
$query->bindParam(":agency", $agency); $query->bindParam(":agency", $agency);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
if ($row['count'] > 0) { if ($row['count'] > 0) {
$suppliers[] = $row['count'] . " other suppliers"; $suppliers[] = $row['count'] . " other suppliers";
$values[] = doubleval($row[0]); $values[] = doubleval($row[0]);
} }
} }
} }
   
function CnCGraph() { function CnCGraph() {
   
global $conn; global $conn;
$query = 'select procurementMethod, count(1) as count, SUM(value) as val, MONTH(contractStart) as month, YEAR(contractStart) as year from contractnotice $query = 'select procurementMethod, count(1) as count, SUM(value) as val, MONTH(contractStart) as month, YEAR(contractStart) as year from contractnotice
where $agencyQ $supplierQ $standardQ group by procurementMethod,year,month order by procurementMethod,year,month'; where $agencyQ $supplierQ $standardQ group by procurementMethod,year,month order by procurementMethod,year,month';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
   
$methods = Array("Direct", "Open", "Select"); $methods = Array("Direct", "Open", "Select");
$dates = Array(); $dates = Array();
$methodCountsP = Array(); $methodCountsP = Array();
$methodCounts = Array(); $methodCounts = Array();
$maxValue = 0; $maxValue = 0;
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
if ($row['val'] > $maxValue) if ($row['val'] > $maxValue)
$maxValue = $row['val']; $maxValue = $row['val'];
$date = date('F ', mktime(0, 0, 0, $row["month"])) . $row["year"]; $date = date('F ', mktime(0, 0, 0, $row["month"])) . $row["year"];
if (array_search($date, $dates) === false) { if (array_search($date, $dates) === false) {
$dates[$row["year"] * 100 + $row["month"]] = $date; $dates[$row["year"] * 100 + $row["month"]] = $date;
ksort($dates); ksort($dates);
} }
$methodCountsP[$row["procurementMethod"]][$date] = $row["count"]; $methodCountsP[$row["procurementMethod"]][$date] = $row["count"];
} }
foreach ($methods as $method) { foreach ($methods as $method) {
foreach ($dates as $date) { foreach ($dates as $date) {
if ($methodCountsP[$method][$date] > 0) if ($methodCountsP[$method][$date] > 0)
$methodCounts[$method][] = $methodCountsP[$method][$date]; $methodCounts[$method][] = $methodCountsP[$method][$date];
else else
$methodCounts[$method][] = 0; $methodCounts[$method][] = 0;
} }
} }
$dates = array_values($dates); $dates = array_values($dates);
$totalRecords = array_sum_all($methodCounts); $totalRecords = array_sum_all($methodCounts);
   
function formatCallback($aVal) { function formatCallback($aVal) {
global $totalRecords; global $totalRecords;
return percent($aVal, $totalRecords) . "%"; return percent($aVal, $totalRecords) . "%";
} }
   
$attributes = Array(); $attributes = Array();
$attributeNames = Array( $attributeNames = Array(
"Consultancies", "Consultancies",
"Confidentialities" "Confidentialities"
); );
$query = 'SELECT \'consultancy\', count(1) FROM contractnotice WHERE $agencyQ $supplierQ consultancy=\'Yes\' AND "childCN" is null;'; $query = 'SELECT \'consultancy\', count(1) FROM contractnotice WHERE $agencyQ $supplierQ consultancy=\'Yes\' AND "childCN" is null;';
$result = $conn->query($query); $result = $conn->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC); $row = $result->fetch(PDO::FETCH_ASSOC);
$attributes[0] = $row[1]; $attributes[0] = $row[1];
$query = 'SELECT \'confidentiality\', count(1) FROM contractnotice WHERE $agencyQ $supplierQ (confidentialityContract=\'Yes\' OR confidentialityOutputs=\'Yes\') AND "childCN" is null;'; $query = 'SELECT \'confidentiality\', count(1) FROM contractnotice WHERE $agencyQ $supplierQ (confidentialityContract=\'Yes\' OR confidentialityOutputs=\'Yes\') AND "childCN" is null;';
$result = $conn->query($query); $result = $conn->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC); $row = $result->fetch(PDO::FETCH_ASSOC);
$attributes[1] = $row[1]; $attributes[1] = $row[1];
} }
   
function ContractPublishedGraph() { function ContractPublishedGraph() {
   
global $conn; global $conn;
$query = 'SELECT extract(year from "contractStart"),extract(month from "contractStart"), $query = 'SELECT extract(year from "contractStart"),extract(month from "contractStart"),
SUM(value) as val, count(1) as count FROM contractnotice SUM(value) as val, count(1) as count FROM contractnotice
WHERE (extract(year from "contractStart") >= 2008) WHERE (extract(year from "contractStart") >= 2008)
AND "childCN" is null AND "childCN" is null
GROUP BY extract(month from "contractStart"), extract(year from "contractStart") GROUP BY extract(month from "contractStart"), extract(year from "contractStart")
ORDER BY extract(year from "contractStart"), extract(month from "contractStart")'; ORDER BY extract(year from "contractStart"), extract(month from "contractStart")';
   
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
   
$dates = Array(); $dates = Array();
$values = Array(); $values = Array();
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
$value = number_format(doubleval($row["val"]), 2); $value = number_format(doubleval($row["val"]), 2);
$month_name = date('F', mktime(0, 0, 0, $row[1])); $month_name = date('F', mktime(0, 0, 0, $row[1]));
$dates[] = $month_name . " {$row[0]}"; $dates[] = $month_name . " {$row[0]}";
$counts[] = doubleval($row["count"]); $counts[] = doubleval($row["count"]);
$values[] = doubleval($row["val"]); $values[] = doubleval($row["val"]);
} }
} }
   
function ContractStartingGraph() { function ContractStartingGraph() {
   
global $conn; global $conn;
$query = 'SELECT extract (YEAR from "contractStart") as year, extract (MONTH from "contractStart") as month, $query = 'SELECT extract (YEAR from "contractStart") as year, extract (MONTH from "contractStart") as month,
SUM(value) as val, count(*) as count FROM contractnotice SUM(value) as val, count(*) as count FROM contractnotice
WHERE extract (YEAR from "contractStart") >= 2008 WHERE extract (YEAR from "contractStart") >= 2008
AND "childCN" is null AND "childCN" is null
GROUP BY extract (MONTH from "contractStart"), extract (YEAR from "contractStart") GROUP BY extract (MONTH from "contractStart"), extract (YEAR from "contractStart")
ORDER BY extract (YEAR from "contractStart"), extract (MONTH from"contractStart")'; ORDER BY extract (YEAR from "contractStart"), extract (MONTH from"contractStart")';
   
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
$dates = Array(); $dates = Array();
$counts = Array(); $counts = Array();
$values = Array(); $values = Array();
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
$value = number_format(doubleval($row["val"]), 2); $value = number_format(doubleval($row["val"]), 2);
$date = mktime(0, 0, 0, $row["month"],1,$row["year"])*1000; $date = mktime(0, 0, 0, $row["month"],1,$row["year"])*1000;
if ($row["count"] > 1) { if ($row["count"] > 1) {
$dates[] = $date; $dates[] = $date;
$counts[] = $row["count"]; $counts[] = $row["count"];
$values[] = $row["val"]; $values[] = $row["val"];
} }
} }
includeFlot(); includeFlot();
?> ?>
<center><div id="cstart" style="width:900px;height:550px"></div></center> <center><div id="cstart" style="width:900px;height:550px"></div></center>
<script type="text/javascript"> <script type="text/javascript">
var placeholder = $("#cstart"); var placeholder = $("#cstart");
$(function () { $(function () {
   
var d1 = []; var d1 = [];
var d2 = []; var d2 = [];
<?php <?php
foreach ($counts as $key => $count) { foreach ($counts as $key => $count) {
   
echo "d1.push([ " . $dates[$key] . ", " . $count . "]); \n"; echo "d1.push([ " . $dates[$key] . ", " . $count . "]); \n";
}; };
foreach ($values as $key => $value) { foreach ($values as $key => $value) {
   
echo "d2.push([ " . $dates[$key] . ", " . $value . "]); \n"; echo "d2.push([ " . $dates[$key] . ", " . $value . "]); \n";
}; };
d1d2Graph(true); d1d2Graph(true);
} }
   
function MethodCountGraph() { function MethodCountGraph() {
   
global $conn; global $conn;
$query = 'select procurementMethod, count(1) as count, SUM(value) as value, MONTH(contractStart) as month, YEAR(contractStart) as year from contractnotice $query = 'select procurementMethod, count(1) as count, SUM(value) as value, MONTH(contractStart) as month, YEAR(contractStart) as year from contractnotice
where $agencyQ $supplierQ $standardQ group by procurementMethod,year,month order by procurementMethod,year,month'; where $agencyQ $supplierQ $standardQ group by procurementMethod,year,month order by procurementMethod,year,month';
$methods = Array("Direct", "Open", "Select"); $methods = Array("Direct", "Open", "Select");
$dates = Array(); $dates = Array();
$methodCountsP = Array(); $methodCountsP = Array();
$methodCounts = Array(); $methodCounts = Array();
$maxValue = 0; $maxValue = 0;
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
   
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
if ($row['value'] > $maxValue) if ($row['value'] > $maxValue)
$maxValue = $row['value']; $maxValue = $row['value'];
$date = date('F ', mktime(0, 0, 0, $row["month"])) . $row["year"]; $date = date('F ', mktime(0, 0, 0, $row["month"])) . $row["year"];
if (array_search($date, $dates) === false) { if (array_search($date, $dates) === false) {
$dates[$row["year"] * 100 + $row["month"]] = $date; $dates[$row["year"] * 100 + $row["month"]] = $date;
ksort($dates); ksort($dates);
} }
$methodCountsP[$row["procurementMethod"]][$date] = $row["count"]; $methodCountsP[$row["procurementMethod"]][$date] = $row["count"];
} }
foreach ($methods as $method) { foreach ($methods as $method) {
foreach ($dates as $date) { foreach ($dates as $date) {
if ($methodCountsP[$method][$date] > 0) if ($methodCountsP[$method][$date] > 0)
$methodCounts[$method][] = $methodCountsP[$method][$date]; $methodCounts[$method][] = $methodCountsP[$method][$date];
else else
$methodCounts[$method][] = 0; $methodCounts[$method][] = 0;
} }
} }
$dates = array_values($dates); $dates = array_values($dates);
$totalRecords = array_sum_all($methodCounts); $totalRecords = array_sum_all($methodCounts);
} }
   
function MethodValueGraph() { function MethodValueGraph() {
   
global $conn; global $conn;
$query = "select procurementMethod, SUM(value) as value, MONTH(contractStart) as month, YEAR(contractStart) as year from contractnotice $query = "select procurementMethod, SUM(value) as value, MONTH(contractStart) as month, YEAR(contractStart) as year from contractnotice
where $agencyQ $supplierQ $standardQ group by procurementMethod,year,month order by procurementMethod,year,month"; where $agencyQ $supplierQ $standardQ group by procurementMethod,year,month order by procurementMethod,year,month";
$methods = Array("Direct", "Open", "Select"); $methods = Array("Direct", "Open", "Select");
$dates = Array(); $dates = Array();
$methodValuesP = Array(); $methodValuesP = Array();
$methodValues = Array(); $methodValues = Array();
$maxValue = 0; $maxValue = 0;
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
   
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
if ($row['value'] > $maxValue) if ($row['value'] > $maxValue)
$maxValue = $row['value']; $maxValue = $row['value'];
$date = date('F ', mktime(0, 0, 0, $row["month"])) . $row["year"]; $date = date('F ', mktime(0, 0, 0, $row["month"])) . $row["year"];
if (array_search($date, $dates) === false) { if (array_search($date, $dates) === false) {
$dates[$row["year"] * 100 + $row["month"]] = $date; $dates[$row["year"] * 100 + $row["month"]] = $date;
ksort($dates); ksort($dates);
} }
$methodValuesP[$row["procurementMethod"]][$date] = $row["value"]; $methodValuesP[$row["procurementMethod"]][$date] = $row["value"];
} }
foreach ($methods as $method) { foreach ($methods as $method) {
foreach ($dates as $date) { foreach ($dates as $date) {
if ($methodValuesP[$method][$date] > 0) if ($methodValuesP[$method][$date] > 0)
$methodValues[$method][] = $methodValuesP[$method][$date]; $methodValues[$method][] = $methodValuesP[$method][$date];
else else
$methodValues[$method][] = 0; $methodValues[$method][] = 0;
} }
} }
$dates = array_values($dates); $dates = array_values($dates);
$totalRecords = array_sum_all($methodValues); $totalRecords = array_sum_all($methodValues);
} }
   
function SuppliersGraph() { function SuppliersGraph() {
   
global $conn; global $conn;
includeFlot(); includeFlot();
$topX = 10; $topX = 10;
$suppliers = Array(); $suppliers = Array();
$values = Array(); $values = Array();
   
   
$query = 'SELECT SUM("value") as value, MAX("supplierName") as supplierName, ( $query = 'SELECT SUM("value") as value, MAX("supplierName") as supplierName, (
case when "supplierABN" != 0 THEN "supplierABN"::text ELSE "supplierName" END) as supplierID case when "supplierABN" != 0 THEN "supplierABN"::text ELSE "supplierName" END) as supplierID
FROM contractnotice FROM contractnotice
WHERE "childCN" is null WHERE "childCN" is null
GROUP BY supplierID GROUP BY supplierID
ORDER BY value DESC ORDER BY value DESC
LIMIT ' . $topX; LIMIT ' . $topX;
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
setlocale(LC_MONETARY, 'en_US'); setlocale(LC_MONETARY, 'en_US');
// $value = number_format(doubleval($row["value"]) , 2); // $value = number_format(doubleval($row["value"]) , 2);
$suppliers[] = ucsmart($row[1]); $suppliers[] = ucsmart($row[1]);
$values[] = doubleval($row["value"]); $values[] = doubleval($row["value"]);
} }
   
$query = 'SELECT sum(a.svalue) as val, suppliercountry from (SELECT sum("value") as svalue, max("supplierCountry") as suppliercountry $query = 'SELECT sum(a.svalue) as val, suppliercountry from (SELECT sum("value") as svalue, max("supplierCountry") as suppliercountry
FROM contractnotice WHERE "childCN" is null and "supplierCountry" NOT ILIKE \'Australia\' FROM contractnotice WHERE "childCN" is null and "supplierCountry" NOT ILIKE \'Australia\'
GROUP BY "supplierName" ORDER BY svalue LIMIT 18446744073 OFFSET 10) as a group by suppliercountry order by val DESC limit 10 '; GROUP BY "supplierName" ORDER BY svalue LIMIT 18446744073 OFFSET 10) as a group by suppliercountry order by val DESC limit 10 ';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
   
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
$suppliers[] = "Other suppliers in " . ucsmart($row["suppliercountry"]); $suppliers[] = "Other suppliers in " . ucsmart($row["suppliercountry"]);
$values[] = doubleval($row[0]); $values[] = doubleval($row[0]);
} }
   
   
$query = 'SELECT sum(a.value) as val, substring( $query = 'SELECT sum(a.value) as val, substring(
supplierpostcode from 0 for 2) as postcode from (SELECT sum(value) as value, max("supplierPostcode") as supplierpostcode, max("supplierCountry") as suppliercountry supplierpostcode from 0 for 2) as postcode from (SELECT sum(value) as value, max("supplierPostcode") as supplierpostcode, max("supplierCountry") as suppliercountry
FROM contractnotice WHERE "childCN" is null FROM contractnotice WHERE "childCN" is null
GROUP BY "supplierABN" ORDER BY sum(value) LIMIT 1844674 OFFSET 10) as a GROUP BY "supplierABN" ORDER BY sum(value) LIMIT 1844674 OFFSET 10) as a
WHERE (suppliercountry ILIKE \'Australia\') WHERE (suppliercountry ILIKE \'Australia\')
group by substring( group by substring(
supplierpostcode from 0 for 2) supplierpostcode from 0 for 2)
order by val DESC;'; order by val DESC;';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
   
foreach ($query->fetchAll() as $row) { foreach ($query->fetchAll() as $row) {
if ($row['postcode'][0] == 2 && $row['postcode'][1] == 6) if ($row['postcode'][0] == 2 && $row['postcode'][1] == 6)
$ACTvalue += $row[0]; $ACTvalue += $row[0];
else if ($row['postcode'][0] == 2 || $row['postcode'][0] == 1) else if ($row['postcode'][0] == 2 || $row['postcode'][0] == 1)
$NSWvalue += $row[0]; $NSWvalue += $row[0];
else if ($row['postcode'][0] == 3 || $row['postcode'][0] == 8) else if ($row['postcode'][0] == 3 || $row['postcode'][0] == 8)
$Vicvalue += $row[0]; $Vicvalue += $row[0];
else if ($row['postcode'][0] == 4 || $row['postcode'][0] == 9) else if ($row['postcode'][0] == 4 || $row['postcode'][0] == 9)
$QLDvalue += $row[0]; $QLDvalue += $row[0];
else if ($row['postcode'][0] == 5) else if ($row['postcode'][0] == 5)
$SAvalue += $row[0]; $SAvalue += $row[0];
else if ($row['postcode'][0] == 6) else if ($row['postcode'][0] == 6)
$WAvalue += $row[0]; $WAvalue += $row[0];
else if ($row['postcode'][0] == 7) else if ($row['postcode'][0] == 7)
$Tasvalue += $row[0]; $Tasvalue += $row[0];
else if ($row['postcode'][0] == 0) else if ($row['postcode'][0] == 0)
$NTvalue += $row[0]; $NTvalue += $row[0];
} }
$suppliers[] = "Other suppliers in Australia - ACT"; $suppliers[] = "Other suppliers in Australia - ACT";
$values[] = doubleval($ACTvalue); $values[] = doubleval($ACTvalue);
$suppliers[] = "Other suppliers in Australia - NSW"; $suppliers[] = "Other suppliers in Australia - NSW";
$values[] = doubleval($NSWvalue); $values[] = doubleval($NSWvalue);
$suppliers[] = "Other suppliers in Australia - Victoria"; $suppliers[] = "Other suppliers in Australia - Victoria";
$values[] = doubleval($Vicvalue); $values[] = doubleval($Vicvalue);
$suppliers[] = "Other suppliers in Australia - Queensland"; $suppliers[] = "Other suppliers in Australia - Queensland";
$values[] = doubleval($QLDvalue); $values[] = doubleval($QLDvalue);
$suppliers[] = "Other suppliers in Australia - NT"; $suppliers[] = "Other suppliers in Australia - NT";
$values[] = doubleval($NTvalue); $values[] = doubleval($NTvalue);
$suppliers[] = "Other suppliers in Australia - West Australia"; $suppliers[] = "Other suppliers in Australia - West Australia";
$values[] = doubleval($WAvalue); $values[] = doubleval($WAvalue);
$suppliers[] = "Other suppliers in Australia - South Australia"; $suppliers[] = "Other suppliers in Australia - South Australia";
$values[] = doubleval($SAvalue); $values[] = doubleval($SAvalue);
$suppliers[] = "Other suppliers in Australia - Tasmania"; $suppliers[] = "Other suppliers in Australia - Tasmania";
$values[] = doubleval($Tasvalue); $values[] = doubleval($Tasvalue);
?> ?>
<script type="text/javascript"> <script type="text/javascript">
$(function () { $(function () {
// data // data
var data = [ var data = [
<?php <?php
foreach ($suppliers as $key => $supplier) { foreach ($suppliers as $key => $supplier) {
echo '{ label: "' . $supplier . '", data: ' . doubleval($values[$key]) . '},'; echo '{ label: "' . $supplier . '", data: ' . doubleval($values[$key]) . '},';
} }
?> ?>
]; ];
// GRAPH 7 // GRAPH 7
$.plot($("#graph7"), data, $.plot($("#graph7"), data,
{ {
series: { series: {
pie: { pie: {
show: true, show: true,
radius: 1, radius: 1,
tilt: 0.75, tilt: 0.75,
label: { label: {
show: true, show: true,
radius: 1, radius: 1,
formatter: function(label, series){ formatter: function(label, series){
return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+': '+Math.round(series.percent)+'%</div>'; return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+': '+Math.round(series.percent)+'%</div>';
}, },
background: { background: {
opacity: 0.5, opacity: 0.5,
color: '#000' color: '#000'
} }
}, },
combine: { combine: {
color: '#999', color: '#999',
threshold: 0.012 threshold: 0.012
} }
} }
}, },
legend: { legend: {
show: false show: false
} }
}); });
}); });
</script> </script>
<div id="graph7" style="width:900px;height:550px"></div> <div id="graph7" style="width:900px;height:550px"></div>
   
<?php <?php
} }
?> ?>