Fix more graphs
Fix more graphs

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>org.lambdacomplex.contractdashboard</groupId> <groupId>org.lambdacomplex.contractdashboard</groupId>
<artifactId>neo4jimporter</artifactId> <artifactId>neo4jimporter</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.neo4j</groupId> <groupId>org.neo4j</groupId>
<artifactId>neo4j</artifactId> <artifactId>neo4j</artifactId>
<version>1.5</version> <version>1.6.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>postgresql</groupId> <groupId>postgresql</groupId>
<artifactId>postgresql</artifactId> <artifactId>postgresql</artifactId>
<version>9.0-801.jdbc4</version> <version>9.0-801.jdbc4</version>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>
   
import java.io.ObjectInputStream.GetField; import java.io.ObjectInputStream.GetField;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DriverManager; import java.sql.DriverManager;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.SQLWarning; import java.sql.SQLWarning;
import java.sql.Statement; import java.sql.Statement;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
   
import org.neo4j.graphdb.DynamicRelationshipType; import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.index.BatchInserterIndex; import org.neo4j.graphdb.index.BatchInserterIndex;
import org.neo4j.graphdb.index.BatchInserterIndexProvider; import org.neo4j.graphdb.index.BatchInserterIndexProvider;
import org.neo4j.helpers.collection.MapUtil; import org.neo4j.helpers.collection.MapUtil;
import org.neo4j.kernel.impl.batchinsert.BatchInserter; import org.neo4j.kernel.impl.batchinsert.BatchInserter;
import org.neo4j.kernel.impl.batchinsert.BatchInserterImpl; import org.neo4j.kernel.impl.batchinsert.BatchInserterImpl;
import org.neo4j.index.impl.lucene.*; import org.neo4j.index.impl.lucene.*;
   
public class Importer { public class Importer {
   
public static void main(String[] argv) { public static void main(String[] argv) {
BatchInserter inserter = new BatchInserterImpl("target/neo4jdb-batchinsert"); BatchInserter inserter = new BatchInserterImpl("target/neo4jdb-batchinsert");
BatchInserterIndexProvider indexProvider = new LuceneBatchInserterIndexProvider(inserter); BatchInserterIndexProvider indexProvider = new LuceneBatchInserterIndexProvider(inserter);
BatchInserterIndex labels = indexProvider.nodeIndex("labels", MapUtil.stringMap("type", "exact")); BatchInserterIndex labels = indexProvider.nodeIndex("labels", MapUtil.stringMap("type", "exact"));
labels.setCacheCapacity("Label", 100000); labels.setCacheCapacity("Label", 100000);
   
   
   
System.out.println("-------- PostgreSQL " System.out.println("-------- PostgreSQL "
+ "JDBC Connection Testing ------------"); + "JDBC Connection Testing ------------");
   
try { try {
   
Class.forName("org.postgresql.Driver"); Class.forName("org.postgresql.Driver");
   
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
   
System.out.println("Where is your PostgreSQL JDBC Driver? " System.out.println("Where is your PostgreSQL JDBC Driver? "
+ "Include in your library path!"); + "Include in your library path!");
e.printStackTrace(); e.printStackTrace();
   
} }
   
System.out.println("PostgreSQL JDBC Driver Registered!"); System.out.println("PostgreSQL JDBC Driver Registered!");
   
Connection conn = null; Connection conn = null;
   
try { try {
   
conn = DriverManager.getConnection( conn = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/contractDashboard", "jdbc:postgresql://127.0.0.1:5432/contractDashboard",
"postgres", "snmc"); "postgres", "snmc");
   
} catch (SQLException e) { } catch (SQLException e) {
   
System.out.println("Connection Failed! Check output console"); System.out.println("Connection Failed! Check output console");
e.printStackTrace(); e.printStackTrace();
   
} }
   
if (conn != null) { if (conn != null) {
System.out.println("You made it, take control your database now!"); System.out.println("You made it, take control your database now!");
} else { } else {
System.out.println("Failed to make connection!"); System.out.println("Failed to make connection!");
} }
try { try {
// Print all warnings // Print all warnings
for (SQLWarning warn = conn.getWarnings(); warn != null; warn = warn.getNextWarning()) { for (SQLWarning warn = conn.getWarnings(); warn != null; warn = warn.getNextWarning()) {
System.out.println("SQL Warning:"); System.out.println("SQL Warning:");
System.out.println("State : " + warn.getSQLState()); System.out.println("State : " + warn.getSQLState());
System.out.println("Message: " + warn.getMessage()); System.out.println("Message: " + warn.getMessage());
System.out.println("Error : " + warn.getErrorCode()); System.out.println("Error : " + warn.getErrorCode());
} }
   
// Get a statement from the connection // Get a statement from the connection
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
   
// Execute the query // Execute the query
ResultSet rs = stmt.executeQuery("SELECT contractnotice.\"agencyName\", " ResultSet rs = stmt.executeQuery("SELECT contractnotice.\"agencyName\", "
+ " contractnotice.\"supplierABN\",contractnotice.\"supplierName\",sum(value) as sum " + " contractnotice.\"supplierABN\",contractnotice.\"supplierName\",sum(value) as sum "
+ "FROM public.contractnotice where contractnotice.\"agencyName\" != 'Department of Defence'" + "FROM public.contractnotice where contractnotice.\"agencyName\" != 'Department of Defence'"
+ " AND contractnotice.\"agencyName\" != 'Defence Materiel Organisation' GROUP BY contractnotice.\"agencyName\", " + " AND contractnotice.\"agencyName\" != 'Defence Materiel Organisation' GROUP BY contractnotice.\"agencyName\", "
+ " contractnotice.\"supplierABN\",contractnotice.\"supplierName\""); + " contractnotice.\"supplierABN\",contractnotice.\"supplierName\"");
String previousAgency = ""; String previousAgency = "";
GraphDatabaseService gds = inserter.getGraphDbService(); GraphDatabaseService gds = inserter.getGraphDbService();
HashMap<String,Long> supplierIDs = new HashMap<String,Long>(); HashMap<String, Long> supplierIDs = new HashMap<String, Long>();
HashMap<String,Long> agencyIDs = new HashMap<String,Long>(); HashMap<String, Long> agencyIDs = new HashMap<String, Long>();
   
// Loop through the result set // Loop through the result set
while (rs.next()) { while (rs.next()) {
long supplierID, agencyID; long supplierID, agencyID;
String supplierKey; String supplierKey;
if (agencyIDs.get(rs.getString("agencyName")) == null) { if (agencyIDs.get(rs.getString("agencyName")) == null) {
Node myNode = gds.createNode(); Node myNode = gds.createNode();
myNode.setProperty("Label", rs.getString("agencyName")); myNode.setProperty("Label", rs.getString("agencyName"));
myNode.setProperty("type", "agency"); myNode.setProperty("type", "agency");
agencyIDs.put(rs.getString("agencyName"), myNode.getId()); agencyIDs.put(rs.getString("agencyName"), myNode.getId());
if (myNode.getId() %100 == 0) { if (myNode.getId() % 100 == 0) {
System.out.println("Agency "+myNode.getId()); System.out.println("Agency " + myNode.getId());
} }
} }
agencyID = agencyIDs.get(rs.getString("agencyName")); agencyID = agencyIDs.get(rs.getString("agencyName"));
   
   
if (rs.getString("supplierABN") != "0" && rs.getString("supplierABN") != "") { if (rs.getString("supplierABN") != "0" && rs.getString("supplierABN") != "") {
supplierKey = rs.getString("supplierABN"); supplierKey = rs.getString("supplierABN");
} else { } else {
supplierKey = rs.getString("supplierName"); supplierKey = rs.getString("supplierName");
} }
// inject some data // inject some data
if (supplierIDs.get(supplierKey) == null) { if (supplierIDs.get(supplierKey) == null) {
Node myNode = gds.createNode(); Node myNode = gds.createNode();
myNode.setProperty("Label", rs.getString("supplierName")); myNode.setProperty("Label", rs.getString("supplierName"));
myNode.setProperty("type", "supplier"); myNode.setProperty("type", "supplier");
supplierIDs.put(supplierKey, myNode.getId()); supplierIDs.put(supplierKey, myNode.getId());
if (myNode.getId() %1000 == 0) { if (myNode.getId() % 1000 == 0) {
System.out.println("Supplier "+myNode.getId()); System.out.println("Supplier " + myNode.getId());
} }
} }
supplierID = supplierIDs.get(supplierKey); supplierID = supplierIDs.get(supplierKey);
   
   
long rel = inserter.createRelationship(agencyID, supplierID, long rel = inserter.createRelationship(agencyID, supplierID,
DynamicRelationshipType.withName("KNOWS"), null); DynamicRelationshipType.withName("KNOWS"), null);
inserter.setRelationshipProperty(rel, "Weight", rs.getDouble("sum")); inserter.setRelationshipProperty(rel, "Weight", rs.getDouble("sum"));
   
} }
// Close the result set, statement and the connection // Close the result set, statement and the connection
rs.close(); rs.close();
stmt.close(); stmt.close();
conn.close(); conn.close();
} catch (SQLException se) { } catch (SQLException se) {
System.out.println("SQL Exception:"); System.out.println("SQL Exception:");
   
// Loop through the SQL Exceptions // Loop through the SQL Exceptions
while (se != null) { while (se != null) {
System.out.println("State : " + se.getSQLState()); System.out.println("State : " + se.getSQLState());
System.out.println("Message: " + se.getMessage()); System.out.println("Message: " + se.getMessage());
System.out.println("Error : " + se.getErrorCode()); System.out.println("Error : " + se.getErrorCode());
   
se = se.getNextException(); se = se.getNextException();
} }
} }
//make the changes visible for reading, use this sparsely, requires IO! //make the changes visible for reading, use this sparsely, requires IO!
labels.flush(); labels.flush();
   
// Make sure to shut down the index provider // Make sure to shut down the index provider
indexProvider.shutdown(); indexProvider.shutdown();
inserter.shutdown(); inserter.shutdown();
} }
   
   
} }
 Binary files a/admin/neo4jimporter/target/classes/Importer.class and b/admin/neo4jimporter/target/classes/Importer.class differ
<?php <?php
include_once("./lib/common.inc.php"); include_once("./lib/common.inc.php");
include_header("Months and Years"); include_header("Months and Years");
if ($_REQUEST['month']) { if ($_REQUEST['month']) {
echo "<center><h1>" . $_REQUEST['month'] . "</h1></center>"; echo "<center><h1>" . $_REQUEST['month'] . "</h1></center>";
$monthParts = explode("-", $_REQUEST['month']); $monthParts = explode("-", $_REQUEST['month']);
$query = 'SELECT "CNID", "description", "value", "agencyName", "category", "contractStart", "supplierName" $query = 'SELECT "CNID", "description", "value", "agencyName", "category", "contractStart", "supplierName"
FROM contractnotice FROM contractnotice
WHERE "childCN" is null WHERE "childCN" is null
AND extract(year from "contractStart") = :year AND extract(year from "contractStart") = :year
AND extract(month from "contractStart") = :month AND extract(month from "contractStart") = :month
ORDER BY value DESC'; ORDER BY value DESC';
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->bindParam(":month", $monthParts[0]); $query->bindParam(":month", $monthParts[0]);
$query->bindParam(":year", $monthParts[1]); $query->bindParam(":year", $monthParts[1]);
$query->execute(); $query->execute();
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
MethodCountGraph($supplier); //MethodCountGraph($supplier);
CnCGraph($supplier); //CnCGraph($supplier);
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 year split by year
todo: todo:
Year/Month drilldown - largest contracts, agencies, suppliers Year/Month drilldown - largest contracts, agencies, suppliers
count per month count per month
big picture graphs? */ big picture graphs? */
echo '<img src="graphs/displayContractStartingGraph.php">'; echo '<img src="graphs/displayContractStartingGraph.php">';
echo '<img src="graphs/displayContractPublishedGraph.php">'; echo '<img src="graphs/displayContractPublishedGraph.php">';
$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 WHERE "childCN" is null GROUP BY extract(year from "contractStart"), extract(month from "contractStart") ORDER BY extract(year from "contractStart"), extract(month from "contractStart") '; SUM(value) as val, count(1) as count FROM contractnotice WHERE "childCN" is null GROUP 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());
echo "<table> <thead> echo "<table> <thead>
<tr> <tr>
<th>Month/Year</th> <th>Month/Year</th>
<th>Total Contracts Value</th> <th>Total Contracts Value</th>
<th>Number of Contracts</th> <th>Number of Contracts</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["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]));
echo ("<tr><td><b><a href=\"?month=$row[1]-$row[0]\">$month_name {$row[0]}</a></b></td><td>\$$value</td><td>({$row['count']} contracts)</td></tr>"); echo ("<tr><td><b><a href=\"?month=$row[1]-$row[0]\">$month_name {$row[0]}</a></b></td><td>\$$value</td><td>({$row['count']} contracts)</td></tr>");
} }
echo "</table>"; echo "</table>";
} }
include_footer(); include_footer();
?> ?>
   
<?php <?php
   
include_once("./lib/common.inc.php"); include_once("./lib/common.inc.php");
setlocale(LC_CTYPE, 'C'); setlocale(LC_CTYPE, 'C');
// source: http://stackoverflow.com/questions/81934/easy-way-to-export-a-sql-table-without-access-to-the-server-or-phpmyadmin#81951 // source: http://stackoverflow.com/questions/81934/easy-way-to-export-a-sql-table-without-access-to-the-server-or-phpmyadmin#81951
   
$unspsc = Array(); $unspsc = Array();
$unspscresult = $conn->prepare('select * from "UNSPSCcategories" where "UNSPSC"::text like \'%00000\';'); $unspscresult = $conn->prepare('select * from "UNSPSCcategories" where "UNSPSC"::text like \'%00000\';');
$unspscresult->execute(); $unspscresult->execute();
foreach ($unspscresult->fetchAll() as $row) { foreach ($unspscresult->fetchAll() as $row) {
$unspsc[$row['UNSPSC']] = $row['Title']; $unspsc[$row['UNSPSC']] = $row['Title'];
} }
  /*SELECT count(*), extract("week" from "publishDate") as week,extract("year" from "publishDate") as year
  FROM contractnotice
  where "childCN" is null group by week, year order by year, week*/
$query = $conn->prepare(' $query = $conn->prepare('
SELECT "CNID",contractnotice."agencyName",agency_nametoabn.abn as "agencyABN", SELECT "CNID",contractnotice."agencyName",agency_nametoabn.abn as "agencyABN",
EXTRACT(EPOCH FROM "publishDate") as "publishDate", EXTRACT(EPOCH FROM "publishDate") as "publishDate",
EXTRACT(EPOCH FROM "contractStart") as "contractStart", EXTRACT(EPOCH FROM "contractStart") as "contractStart",
EXTRACT(EPOCH FROM "contractEnd") as "contractEnd", EXTRACT(EPOCH FROM "contractEnd") as "contractEnd",
value,description,category, value,description,category,
"supplierName",(case when "supplierABN" != 0 THEN "supplierABN"::text ELSE "supplierName" END) as supplierID, "supplierName",(case when "supplierABN" != 0 THEN "supplierABN"::text ELSE "supplierName" END) as supplierID,
(\'https://www.tenders.gov.au/?event=public.advancedsearch.keyword&keyword=CN\'::text || "CNID"::text) as sourceURL (\'https://www.tenders.gov.au/?event=public.advancedsearch.keyword&keyword=CN\'::text || "CNID"::text) as sourceURL
FROM contractnotice join agency_nametoabn on contractnotice."agencyName"=agency_nametoabn."agencyName" FROM contractnotice join agency_nametoabn on contractnotice."agencyName"=agency_nametoabn."agencyName"
where "childCN" is null' where "childCN" is null'
, array(PDO::ATTR_CURSOR => PDO::FETCH_ORI_NEXT)); , array(PDO::ATTR_CURSOR => PDO::FETCH_ORI_NEXT));
$query->execute(); $query->execute();
$errors = $conn->errorInfo(); $errors = $conn->errorInfo();
if ($errors[2] != "") { if ($errors[2] != "") {
die("Export terminated, db error" . print_r($errors, true)); die("Export terminated, db error" . print_r($errors, true));
} }
   
$num_fields = $query->columnCount(); $num_fields = $query->columnCount();
$headers = Array(); $headers = Array();
for ($i = 0; $i < $num_fields; $i++) { // for each column in query, make a CSV header for ($i = 0; $i < $num_fields; $i++) { // for each column in query, make a CSV header
$meta = $query->getColumnMeta($i); $meta = $query->getColumnMeta($i);
$headers[] = $meta['name']; $headers[] = $meta['name'];
} }
$fp = fopen('php://output', 'w'); $fp = fopen('php://output', 'w');
if ($fp && $query) { if ($fp && $query) {
header('Content-Type: text/csv'); header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.' . date("c") . '.csv"'); header('Content-Disposition: attachment; filename="export.' . date("c") . '.csv"');
header('Pragma: no-cache'); header('Pragma: no-cache');
header('Expires: 0'); header('Expires: 0');
fputcsv($fp, $headers); fputcsv($fp, $headers);
while ($row = $query->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) { while ($row = $query->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
foreach ($row as $key => &$colvalue) { foreach ($row as $key => &$colvalue) {
   
$colvalue = preg_replace('/[^[:print:]]/', '', utf8_encode($colvalue)); $colvalue = preg_replace('/[^[:print:]]/', '', utf8_encode($colvalue));
if ($headers[$key] == "publishDate" || $headers[$key] == "contractStart" if ($headers[$key] == "publishDate" || $headers[$key] == "contractStart"
|| $headers[$key] == "contractEnd") { || $headers[$key] == "contractEnd") {
$colvalue = date("Y-m-d", $colvalue); $colvalue = date("Y-m-d", $colvalue);
} }
/* if ($headers[$key] == "CNID") { /* if ($headers[$key] == "CNID") {
$colvalue = str_replace("A","", $colvalue); $colvalue = str_replace("A","", $colvalue);
}*/ }*/
if ($headers[$key] == "cat1" || $headers[$key] == "cat2" if ($headers[$key] == "cat1" || $headers[$key] == "cat2"
|| $headers[$key] == "cat3") { || $headers[$key] == "cat3") {
$colvalue = $unspsc[$colvalue]; $colvalue = $unspsc[$colvalue];
} }
} }
fputcsv($fp, array_values($row)); fputcsv($fp, array_values($row));
} }
die; die;
} }
?> ?>
   
<?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 (select ("CNID" - MOD("CNID",100)) as cnid from contractnotice where "CNID" < 999999 and "parentCN" is null) as a group by cnid order by cnid'; $query = 'select cnid, count(*) from (select ("CNID" - MOD("CNID",100)) as cnid from contractnotice where "CNID" < 999999 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" - MOD("CNID",100)) as cnid from contractnotice where "CNID" < 999999 and "parentCN" is not null) as a group by cnid order by cnid'; $query = 'select cnid, count(*) from (select ("CNID" - MOD("CNID",100)) as cnid from contractnotice where "CNID" < 999999 and "parentCN" is not 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 "d2.push([ " . intval($delta['cnid']) . ", " . intval($delta['count']) . "]); \n"; echo "d2.push([ " . intval($delta['cnid']) . ", " . intval($delta['count']) . "]); \n";
}; };
?> ?>
   
var data = [ var data = [
{ {
data: d1, data: d1,
series: { series: {
lines: { show: true }, lines: { show: true },
points: { show: true } points: { show: true }
}, },
bars: { show: true } bars: { show: true }
}, },
{ {
data: d2, data: d2,
series: { series: {
lines: { show: true }, lines: { show: true },
points: { show: true } points: { show: true }
}, },
bars: { show: true } bars: { show: true }
}, },
]; ];
var options = var options =
{ {
series: { series: {
stack: true, stack: true,
}, },
grid: { hoverable: true, clickable: true, labelMargin: 17 }, grid: { hoverable: true, clickable: true, labelMargin: 17 },
selection: { mode: "x" } selection: { mode: "x" }
}; };
   
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 on contractnotice."agencyName"=agency."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;
$agency = "AusAid"; $agency = "AusAid";
$topX = 15; $topX = 15;
$query = 'SELECT SUM(value) as val, supplierName FROM `contractnotice` WHERE (YEAR(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" = :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(":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 (YEAR(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" = :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(":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() {
$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"; global $conn;
  $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';
$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;
$query = 'SELECT YEAR(publishDate), MONTH(publishDate), $query = 'SELECT YEAR(publishDate), MONTH(publishDate),
SUM(value) as val, count(1) as count FROM `contractnotice` SUM(value) as val, count(1) as count FROM contractnotice
WHERE (YEAR(publishDate) >= 2008) WHERE (YEAR(publishDate) >= 2008)
AND "childCN" is null AND "childCN" is null
GROUP BY MONTH(publishDate), YEAR(publishDate) GROUP BY MONTH(publishDate), YEAR(publishDate)
ORDER BY YEAR(publishDate), MONTH(publishDate)'; ORDER BY YEAR(publishDate), MONTH(publishDate)';
   
$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;
$query = 'SELECT YEAR(contractStart), MONTH(contractStart), $query = 'SELECT YEAR(contractStart), MONTH(contractStart),
SUM(value) as val, count(1) as count FROM `contractnotice` SUM(value) as val, count(1) as count FROM contractnotice
WHERE (YEAR(contractStart) >= 2008) WHERE (YEAR(contractStart) >= 2008)
AND "childCN" is null AND "childCN" is null
GROUP BY MONTH(contractStart), YEAR(contractStart) GROUP BY MONTH(contractStart), YEAR(contractStart)
ORDER BY YEAR(contractStart), MONTH(contractStart)'; ORDER BY YEAR(contractStart), MONTH(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 MethodCountGraph() { function MethodCountGraph() {
$query = 'select procurementMethod, count(1) as count, SUM(value) as value, MONTH(contractStart) as month, YEAR(contractStart) as year from `contractnotice`  
  global $conn;
  $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() {
$query = "select procurementMethod, SUM(value) as value, MONTH(contractStart) as month, YEAR(contractStart) as year from `contractnotice`  
  global $conn;
  $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
} }
?> ?>