Browse Source

Merge branch 'develop'

Alan Lam 7 years ago
parent
commit
89875e315d
100 changed files with 6495 additions and 3489 deletions
  1. 2 0
      .gitignore
  2. 12 16
      Gulpfile.js
  3. 13 6
      composer.json
  4. 1010 19
      composer.lock
  5. 2 3
      config.template.php
  6. 3 2
      controllers/account.php
  7. 3 1
      controllers/customer_ajax.php
  8. 48 41
      controllers/location_edit.php
  9. 1 23
      controllers/location_view.php
  10. 3 1
      controllers/map_overview_ajax.php
  11. 2 1
      controllers/practice.php
  12. 24 7
      controllers/project_export.php
  13. 12 83
      controllers/project_invoice.php
  14. 27 9
      controllers/projects.php
  15. 35 44
      controllers/reports.php
  16. 11 5
      controllers/test.php
  17. 16 4
      controllers/test_file.php
  18. 1 4
      controllers/test_invoice.php
  19. 16 0
      controllers/test_results_customer_list.php
  20. 26 0
      controllers/test_results_project_list.php
  21. 53 0
      controllers/test_results_test_list.php
  22. 2 0
      controllers/tests_admin_list.php
  23. 1 1
      engine/account_icon.php
  24. 28 8
      engine/chart.php
  25. 1026 0
      engine/chart_generator.php
  26. 6 3
      engine/constraint.php
  27. 28 6
      engine/core.php
  28. 50 3
      engine/customer.php
  29. 134 49
      engine/db.php
  30. 77 20
      engine/email.php
  31. 4 2
      engine/email_builder.php
  32. 54 12
      engine/form.php
  33. 1 1
      engine/form_exception.php
  34. 6 1
      engine/geolocation.php
  35. 0 2
      engine/geolocation_bounds.php
  36. 1 3
      engine/html.php
  37. 47 36
      engine/http.php
  38. 8 9
      engine/image.php
  39. 62 0
      engine/invoice.php
  40. 74 0
      engine/invoice_line_item.php
  41. 0 2
      engine/json.php
  42. 137 6
      engine/location.php
  43. 16 4
      engine/location_file.php
  44. 42 0
      engine/location_update_log_entry.php
  45. 7 0
      engine/location_venue_type.php
  46. 133 31
      engine/model.php
  47. 22 6
      engine/practice_test.php
  48. 376 34
      engine/project.php
  49. 18 4
      engine/project_location.php
  50. 18 5
      engine/session.php
  51. 22 3
      engine/site_session_handler.php
  52. 102 22
      engine/template.php
  53. 274 40
      engine/test.php
  54. 5 1
      engine/test_pdf.php
  55. 0 7
      engine/test_value.php
  56. 160 28
      engine/user.php
  57. 33 8
      engine/user_address.php
  58. 18 4
      engine/user_customer.php
  59. 9 4
      engine/user_file.php
  60. 123 161
      engine/util.php
  61. 13 1
      engine/venue_type.php
  62. 14 3
      engine/view.php
  63. 73 0
      export_processing/project_quickbooks_customer_csv.php
  64. 60 0
      export_processing/project_quickbooks_tester_csv.php
  65. 35 0
      json/age_verification.json
  66. 37 0
      json/age_verification_mitchells_and_butlers.json
  67. BIN
      locales/en_GB/LC_MESSAGES/en_GB.mo
  68. 290 295
      locales/en_GB/LC_MESSAGES/en_GB.po
  69. BIN
      locales/es_ES/LC_MESSAGES/es_ES.mo
  70. 246 270
      locales/es_ES/LC_MESSAGES/es_ES.po
  71. BIN
      locales/nl_NL/LC_MESSAGES/nl_NL.mo
  72. 218 251
      locales/nl_NL/LC_MESSAGES/nl_NL.po
  73. 365 201
      package-lock.json
  74. 14 8
      package.json
  75. 3 3
      public/css/bootstrap.min.css
  76. BIN
      public/img/markers/closed.png
  77. BIN
      public/img/markers/do_not_test.png
  78. 4 7
      public/js/Chart.bundle.min.js
  79. 1 1
      public/js/all.min.js
  80. 120 85
      public/js/app-map-overview.js
  81. 19 0
      public/js/app-projects.js
  82. 10 0
      public/js/app-test-list.js
  83. 2 2
      public/js/bootstrap.min.js
  84. 0 0
      public/js/bootstrap.min.js.map
  85. 1 1
      public/js/popper.min.js
  86. 0 0
      public/js/popper.min.js.map
  87. 8 2
      routes.php
  88. 22 587
      template_processing/age_verification/reports_build_charts.php
  89. 6 0
      template_processing/age_verification/reports_create_empty_objects.php
  90. 42 0
      template_processing/age_verification/reports_process_test.php
  91. 24 587
      template_processing/age_verification_mitchells_butlers/reports_build_charts.php
  92. 12 0
      template_processing/age_verification_mitchells_butlers/reports_create_empty_objects.php
  93. 48 0
      template_processing/age_verification_mitchells_butlers/reports_process_test.php
  94. 13 249
      template_processing/mystery_shop/reports_build_charts.php
  95. 12 1
      views/customer_select.php
  96. 16 92
      views/location.php
  97. 66 48
      views/location_form.php
  98. 57 0
      views/location_log_tab.php
  99. 38 0
      views/location_photos_tab.php
  100. 162 0
      views/location_tests_tab.php

+ 2 - 0
.gitignore

@@ -12,3 +12,5 @@ tasks/data/
 backups/
 files/countries.json
 scrap/
+tmp/
+/phinx.yml

+ 12 - 16
Gulpfile.js

@@ -1,29 +1,25 @@
-var gulp = require("gulp");
-var sass = require("gulp-sass");
-var autoprefixer = require("gulp-autoprefixer");
-var cleancss = require("gulp-clean-css");
-var rename = require("gulp-rename");
+let gulp = require("gulp");
+let sass = require("gulp-sass");
+let autoprefixer = require("gulp-autoprefixer");
+let cleancss = require("gulp-clean-css");
+let rename = require("gulp-rename");
 
-var input = "scss/*.scss";
-var output = "public/css";
+let input = "scss/*.scss";
+let output = "public/css";
 
-var sassOptions = {
+let sassOptions = {
 	"errLogToConsole": true,
 	"outputStyle": "expanded"
 };
 
-var autoprefixerOptions = {
-	"browsers": ["last 2 versions", "ie >= 9", "and_chr >= 2.3"]
-};
-
-var vendorCssFiles = [
+let vendorCssFiles = [
 	"./node_modules/datatables.net-bs4/css/dataTables.bootstrap4.min.css",
 	"./node_modules/datatables.net-buttons-bs4/css/buttons.bootstrap4.min.css",
 	"./node_modules/datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css",
 	"./node_modules/daterangepicker/daterangepicker.css",
 ];
 
-var jsFiles = [
+let jsFiles = [
 	"./node_modules/jquery/dist/jquery.min.*",
 	"./node_modules/bootstrap/dist/js/bootstrap.min.*",
 	"./node_modules/popper.js/dist/umd/popper.min.*",
@@ -57,7 +53,7 @@ gulp.task("sass", function() {
 	return gulp
 		.src(input)
 		.pipe(sass(sassOptions).on("error", sass.logError))
-		.pipe(autoprefixer(autoprefixerOptions))
+		.pipe(autoprefixer())
 		.pipe(cleancss())
 		.pipe(rename({
 			"suffix": ".min"
@@ -81,4 +77,4 @@ gulp.task("watch", function() {
 });
 
 
-gulp.task("default", gulp.series("sass", "copy-vendor-css", "copy-js", "watch"));
+gulp.task("default", gulp.series("sass", "copy-vendor-css", "copy-js", "watch"));

+ 13 - 6
composer.json

@@ -1,8 +1,15 @@
 {
-    "require": {
-        "phpmailer/phpmailer": "^6.0",
-		"phpoffice/phppresentation": "dev-master",
-        "mpdf/mpdf": "^7.1",
-        "gettext/gettext": "^4.6"
-    }
+  "require": {
+    "phpmailer/phpmailer": "^6.0",
+    "phpoffice/phppresentation": "dev-master",
+    "mpdf/mpdf": "^7.1",
+    "gettext/gettext": "^4.6",
+    "ext-mysqli": "*",
+    "ext-json": "*",
+    "ext-curl": "*",
+    "ext-gd": "*",
+    "ext-exif": "*",
+    "ext-mbstring": "*",
+    "robmorgan/phinx": "^0.11.1"
+  }
 }

File diff suppressed because it is too large
+ 1010 - 19
composer.lock


+ 2 - 3
config.template.php

@@ -29,7 +29,8 @@ define("DOMAIN", "");
 
 define("PRODUCTION", false);
 define("REGISTRATION_ENABLED", true);
-define("DEBUG_MODE", false);
+
+define("MAILER", "smtp"); // mail / smtp / sendmail
 
 define("SMTP_HOST", "");
 define("SMTP_PORT", 587);
@@ -59,5 +60,3 @@ define("FPDF_FONTPATH", __DIR__ . "/fonts");
 
 define("TIMEZONE", "Europe/London");
 define("DEFAULT_COUNTRY", "United Kingdom");
-
-?>

+ 3 - 2
controllers/account.php

@@ -25,7 +25,6 @@ if($user->level >= User::LEVEL_ADMIN) {
 	$tests_pending_verification = count($tests);
 
 	$icons[] = new AccountIcon(__("Projects"), "/account/projects", "list");
-	$icons[] = new AccountIcon(__("Locations"), "/account/locations", "map-marker");
 	$icons[] = new AccountIcon(__("Templates"), "/account/templates", "file-alt");
 	$icons[] = new AccountIcon(__("Venue Types"), "/account/venue-types", "list-alt");
 
@@ -39,7 +38,9 @@ if($user->level >= User::LEVEL_ADMIN) {
 }
 
 if($user->level >= User::LEVEL_CUSTOMER) {
+	$icons[] = new AccountIcon(__("Locations"), "/account/locations", "map-marker");
 	$icons[] = new AccountIcon(__("Reports"), "/account/reports", "chart-pie");
+	$icons[] = new AccountIcon(__("Test Results"), "/account/test-results", "clipboard-list-check");
 }
 
 if($user->isTester() || $user->isAdmin()) {
@@ -104,4 +105,4 @@ View::includeOnce("header", compact("page_title"));
 View::include("account", compact("icons", "actions", "to_do", "referrals"));
 View::includeOnce("footer");
 
-?>
+?>

+ 3 - 1
controllers/customer_ajax.php

@@ -5,6 +5,8 @@ JSON::header();
 $customer = Customer::get($id);
 if(!$customer) JSON::fail("Customer not found.");
 
+if(!Core::$user->hasPermission($customer)) throw new Exception(__("No permission."));
+
 switch($action) {
 	case "get-locations":
 
@@ -43,4 +45,4 @@ switch($action) {
 		]);
 
 		break;
-}
+}

+ 48 - 41
controllers/location_edit.php

@@ -6,6 +6,8 @@ $location = Location::get($id);
 if(!$location) throw new Exception("Location not found.");
 if(!Core::$user->hasPermission($location)) throw new Exception("You do not have have permission to access this page.");
 
+$original_data = $location->getModelData();
+
 $customer = $location->getCustomer();
 
 $submit = http::value("submit");
@@ -39,7 +41,8 @@ if($submit) {
 		$location->area_manager = http::value("area_manager", "trim");
 		$location->area_manager_email = http::value("area_manager_email", "email");
 
-		$location->closed = http::value("closed", "int");
+		$location->do_not_test = http::value("do_not_test", "int") ? 1 : 0;
+		$location->closed = http::value("closed", "int") ? 1 : 0;
 
 		if(empty($location->name)) $form_exception->addError("Name is required.");
 		if(empty($location->address_1)) $form_exception->addError("Location line 1 is required.");
@@ -51,56 +54,62 @@ if($submit) {
 		else if(empty($location->longitude)) $form_exception->addError("Map location is required.");
 
 		// Photo
-		$photo = (object) $_FILES["photo"];
-		if($photo->error != UPLOAD_ERR_NO_FILE) {
-			try {
-				if($photo->error != UPLOAD_ERR_OK) throw new Exception(HTTP::getUploadErrorString($photo->error));
-				if(!Image::isJPEG($photo->tmp_name)) throw new Exception("Photo is not a JPEG image.");
-
-				// Photo OK
-				$file = new LocationFile;
-				$file->location_id = $id;
-				$file->type = LocationFile::TYPE_PHOTO;
-				$file->dts_uploaded = Util::getDateTime();
-				$file->commit();
-
-				$id = $file->id;
 
-				$directory = $location->getDirectory();
-				$file_path = $directory . "/$id.jpg";
-
-				$output_image = Image::normalise($photo->tmp_name);
-				$success = imagejpeg($output_image, $file_path);
-				imagedestroy($output_image);
-				if(!$success) throw new Exception("Failed to save photo.");
-			}
-			catch(Exception $e) {
-				$form_exception->addError($e->getMessage());
+		if(Core::$user->isAdmin()) {
+			$photo = (object) $_FILES["photo"];
+			if($photo->error != UPLOAD_ERR_NO_FILE) {
+				try {
+					if($photo->error != UPLOAD_ERR_OK) throw new Exception(HTTP::getUploadErrorString($photo->error));
+					if(!Image::isJPEG($photo->tmp_name)) throw new Exception("Photo is not a JPEG image.");
+
+					// Photo OK
+					$file = new LocationFile;
+					$file->location_id = $id;
+					$file->type = LocationFile::TYPE_PHOTO;
+					$file->dts_uploaded = Util::getDateTime();
+					$file->commit();
+
+					$id = $file->id;
+
+					$directory = $location->getDirectory();
+					$file_path = $directory . "/$id.jpg";
+
+					$output_image = Image::normalise($photo->tmp_name);
+					$success = imagejpeg($output_image, $file_path);
+					imagedestroy($output_image);
+					if(!$success) throw new Exception("Failed to save photo.");
+				}
+				catch(Exception $e) {
+					$form_exception->addError($e->getMessage());
+				}
 			}
-		}
 
-		// Delete Photos
-		$delete_file_ids = http::value("delete_file_ids", "int");
-		$files = LocationFile::query([
-			"id" => $delete_file_ids,
-			"location_id" => $id,
-		]);
-		if($files) {
-			$directory = $location->getDirectory();
-			foreach($files as $file) {
-				$pattern = $directory . "/$file->id.*";
-				foreach(glob($pattern) as $path) {
-					unlink($path);
+			// Delete Photos
+			$delete_file_ids = http::value("delete_file_ids", "int");
+			$files = LocationFile::query([
+				"id" => $delete_file_ids,
+				"location_id" => $id,
+			]);
+			if($files) {
+				$directory = $location->getDirectory();
+				foreach($files as $file) {
+					$pattern = $directory . "/$file->id.*";
+					foreach(glob($pattern) as $path) {
+						unlink($path);
+					}
+					$file->delete();
 				}
-				$file->delete();
 			}
 		}
 
+		$modified_fields = $location->getModifiedFields();
 
 		if($form_exception->hasErrors()) throw $form_exception;
 		$success = $location->commit();
 		if(!$success) throw new Exception("Failed to edit location at this time. Please try again later.");
 
+		$location->logUpdate($original_data, $modified_fields);
+
 		// Venue types
 		$venue_type_ids = http::value("venue_type_ids", "int");
 		$venue_types = VenueType::query(["id" => $venue_type_ids]);
@@ -132,5 +141,3 @@ Core::addBreadcrumb("/account/locations/$id/edit", $page_title);
 View::includeOnce("header", compact("page_title"));
 View::include("location_form", compact("location", "photos"));
 View::includeOnce("footer");
-
-?>

+ 1 - 23
controllers/location_view.php

@@ -13,28 +13,6 @@ Core::addBreadcrumb("/account/locations", "Locations");
 Core::addBreadcrumb("/account/locations?customer_id=$customer->id", "$customer->name Locations");
 Core::addBreadcrumb("/account/locations/$location->id", $page_title);
 
-$status_constraint = new Constraint("BETWEEN");
-
-if(Core::$user->level >= User::LEVEL_ADMIN) {
-	$status_constraint->setValues(Test::STATUS_UNASSIGNED, Test::STATUS_COMPLETED);
-}
-else {
-	$status_constraint->setValues(Test::STATUS_COMPLETED, Test::STATUS_COMPLETED);
-}
-
-$tests = Test::query([
-	"location_id" => $location->id,
-	"status" => $status_constraint,
-], [
-	"sort" => "status",
-	"order" => "asc",
-]);
-
-$projects = Project::load(array_column($tests, "project_id"));
-
-
 View::includeOnce("header", compact("page_title"));
-View::include("location", compact("location", "tests"));
+View::include("location", compact("location"));
 View::includeOnce("footer");
-
-?>

+ 3 - 1
controllers/map_overview_ajax.php

@@ -123,6 +123,8 @@ if($submit) {
 						"longitude" => (float) $location->longitude,
 						"icon" => $icon,
 						"test" => null,
+						"doNotTest" => (bool) $location->do_not_test,
+						"closed" => (bool) $location->closed,
 					];
 
 					if($test) {
@@ -250,4 +252,4 @@ if($submit) {
 
 JSON::fail("Invalid request.");
 
-?>
+?>

+ 2 - 1
controllers/practice.php

@@ -23,6 +23,7 @@ if(!$test || $reset) {
 	$test = new PracticeTest;
 	$test->tester_id = Core::$user->id;
 	$test->status = Test::STATUS_CONFIRMED;
+	$test->setTemplateId($template->id);
 	$tests[$id] = $test;
 	$_SESSION["practice_tests"] = $tests;
 
@@ -198,4 +199,4 @@ View::includeOnce("header", compact("page_title"));
 View::include("practice_form", compact("test", "template", "fields"));
 View::includeOnce("footer");
 
-?>
+?>

+ 24 - 7
controllers/project_export.php

@@ -11,12 +11,23 @@ else {
 $projects = Project::query(["id" => $ids]);
 if(!$projects) throw new Exception("No projects to export.");
 
-$template_ids = array_column($projects, "template_id");
-$template_ids = array_unique($template_ids);
-if(count($template_ids) != 1) throw new Exception("Cannot create export with different templates.");
+$template_processing = false;
 
-$template = Template::get($template_ids[0]);
-if(!$template) throw new Exception("Template cannot be found.");
+switch($type) {
+	case "admin":
+	case "customer":
+		$template_processing = true;
+		break;
+}
+
+if($template_processing) {
+	$template_ids = array_column($projects, "template_id");
+	$template_ids = array_unique($template_ids);
+	if(count($template_ids) != 1) throw new Exception("Cannot create export with different templates.");
+
+	$template = Template::get($template_ids[0]);
+	if(!$template) throw new Exception("Template cannot be found.");
+}
 
 $tests = Test::query([
 	"project_id" => $ids,
@@ -33,10 +44,16 @@ switch($type) {
 		$template->exportTestsCSV("project_customer_csv.php", $tests);
 		break;
 
+	case "quickbooks-customer":
+		Project::exportCSV("project_quickbooks_customer_csv.php", $projects);
+		break;
+
+	case "quickbooks-tester":
+		Test::exportCSV("project_quickbooks_tester_csv.php", $tests);
+		break;
+
 	case "kml":
 		// TODO
 		break;
 
 }
-
-

+ 12 - 83
controllers/project_invoice.php

@@ -7,55 +7,19 @@ if(!$project) throw new Exception(__("Project not found."));
 if(!$project->dts_finished) throw new Exception(__("An invoice cannot be generated for this project as it has not been marked as finished."));
 if(!Core::$user->canAdmin()) throw new Exception(__("You do not have permission to access this resource."));
 
-$customer = $project->getCustomer();
-$template = $project->getTemplate();
-$invoice_fields = $template->getCustomerInvoiceFields();
-
-// Calculation
-$default_customer_fee = $project->default_customer_fee;
-$tests = $project->getTests();
-
-$invoice_field_totals = [];
-$test_fee_invoice_counts = [];
-
-$test_costs = 0;
-foreach($tests as $test) {
-
-	$values = $test->getValues(true);
-
-	$fee = $test->customer_fee ?? $default_customer_fee;
-	$test_costs += $fee;
-
-	$count = $test_fee_invoice_counts[$fee] ?? 0;
-	++$count;
-	$test_fee_invoice_counts[$fee] = $count;
+$invoice = $project->getCustomerInvoice();
 
-	foreach($invoice_fields as $field) {
-		if(!isset($invoice_field_totals[$field->name])) {
-			$invoice_field_totals[$field->name] = 0;
-		}
+$line_items = $invoice->getLineItems();
 
-		$invoice_field_totals[$field->name] += (float) ($values[$field->name] ?? 0);
-	}
-}
-
-$total_ex_vat = $test_costs + array_sum($invoice_field_totals);
-$vat = round($total_ex_vat * 0.20, 2);
-
-$total_inc_vat = $total_ex_vat + $vat;
+$customer = $project->getCustomer();
 
-// Processing
-usort($tests, function($a, $b) {
-	return $a->dts_start <=> $b->dts_start;
-});
+$total_ex_vat = $invoice->getTotal();
+$vat = $invoice->getTax();
 
-Location::load(array_column($tests, "location_id"));
-Template::load(array_column($tests, "template_id"));
+$total_inc_vat = $invoice->getTotalIncTax();
 
 // Filename
-$reference =
-	"P" . str_pad($project->id, 3, "0", STR_PAD_LEFT) .
-	"/C" . str_pad($customer->id, 3, "0", STR_PAD_LEFT);
+$reference = $invoice->getReference();
 
 $download_filename = str_replace("/", "_", $reference) . " - " . $project->name . " - Invoice.pdf";
 
@@ -190,53 +154,18 @@ ob_start();
 				</tr>
 
 				<?php
-				/*
-				foreach($tests as $test) {
-					$location = $test->getLocation();
-					$location_address = $location->getDisplayAddress(["address_1", "address_2", "city", "county", "postal_code"]);
-					?>
-
-					<tr>
-						<td>
-							<strong><?=htmlspecialchars($location->name)?></strong><br />
-							<?=nl2br(htmlspecialchars("{$location_address}\n" . date("d/m/Y H:i", strtotime($test->dts_start . " UTC"))))?>
-						</td>
-						<td align="right" valign="top">1</td>
-						<td align="right" valign="top">£<?=number_format($default_customer_fee, 2)?></td>
-						<td align="right" valign="top">£<?=number_format($default_customer_fee, 2)?></td>
-					</tr>
-					<?php
-				}
-				*/
-
-				foreach($test_fee_invoice_counts as $fee => $count) {
-					?>
-					<tr>
-						<td>
-							<strong><?=htmlspecialchars($template->name)?> Testing</strong>
-						</td>
-						<td align="right" valign="top"><?=number_format($count)?></td>
-						<td align="right" valign="top">£<?=number_format($fee, 2)?></td>
-						<td align="right" valign="top">£<?=number_format($fee * $count, 2)?></td>
-					</tr>
-					<?php
-				}
-
-				foreach($invoice_fields as $field) {
-					$total = $invoice_field_totals[$field->name] ?? 0;
-					if(!$total) continue;
+				foreach($line_items as $item) {
 					?>
 					<tr>
 						<td>
-							<strong><?=htmlspecialchars($field->label)?></strong>
+							<strong><?=htmlspecialchars($item->getName())?></strong>
 						</td>
-						<td align="center" valign="top">-</td>
-						<td align="center" valign="top">-</td>
-						<td align="right" valign="top">£<?=number_format($total, 2)?></td>
+						<td align="right" valign="top"><?=htmlspecialchars($item->getDisplayQuantity())?></td>
+						<td align="right" valign="top"><?=htmlspecialchars($item->getDisplayPrice())?></td>
+						<td align="right" valign="top"><?=htmlspecialchars($item->getDisplayTotal())?></td>
 					</tr>
 					<?php
 				}
-
 				?>
 
 				<tr>

+ 27 - 9
controllers/projects.php

@@ -1,26 +1,43 @@
-<?php
+<?php /** @noinspection PhpUnhandledExceptionInspection */
 
 Core::addBreadcrumb("/account", "Account");
 Core::addBreadcrumb("/account/projects", "Projects");
 
 Core::addScript("public/js/app-projects.js");
 
-$customer = Customer::getForAdmin();
+Core::$allow_all_customers = true;
 
-$page_title = "$customer->name Projects";
+$customer_id = http::value("customer_id");
+if(Core::$user->isAdmin() && $customer_id == "ALL") {
 
-Core::addBreadcrumb("/account/projects?customer_id=$customer->id", $page_title);
+	$page_title = "All Projects";
+	Core::addBreadcrumb("/account/projects?customer_id=ALL", $page_title);
 
-$nvp = ["customer_id" => $customer->id];
+	$nvp = [];
+
+	$customer = new Customer;
+	$customer->id = "ALL";
+	$customer->name = "All";
+
+}
+else {
+	$customer = Customer::getForAdmin();
+	$page_title = "$customer->name Projects";
+	Core::addBreadcrumb("/account/projects?customer_id=$customer->id", $page_title);
+
+	$nvp = ["customer_id" => $customer->id];
+}
 
 $id = http::value("id", "int");
 $name = http::value("name", "trim");
 $year = http::value("year", "int");
+$report_month = http::value("report_month", "db");
 
 if($year === false) {
 	$year = date("Y");
 }
 
+
 if($id) $nvp["id"] = $id;
 if($name) $nvp["name"] = (new Constraint("CONTAINS"))->setValues($name);
 if($year) {
@@ -28,14 +45,15 @@ if($year) {
 	$max_dts = "{$year}-12-31 23:59:59";
 	$nvp["dts_start"] = (new Constraint("BETWEEN"))->setValues($min_dts, $max_dts);
 }
+if($report_month) {
+	$nvp["dts_report"] = (new Constraint("BEGINS_WITH"))->setValues($report_month);
+}
 
 $projects = Project::query($nvp, ["sort" => "dts_start", "order" => "desc"]);
 $templates = Template::load(array_column($projects, "template_id"));
 
-$filter_count = count($nvp) - 1;
+$filter_count = count($nvp);
 
 View::includeOnce("header", compact("page_title"));
-View::include("projects", compact("customer", "filter_count", "projects", "year"));
+View::include("projects", compact("customer", "filter_count", "projects", "year", "report_month"));
 View::includeOnce("footer");
-
-?>

+ 35 - 44
controllers/reports.php

@@ -1,4 +1,5 @@
-<?php
+<?php /** @noinspection PhpIncludeInspection */
+/** @noinspection PhpUnhandledExceptionInspection */
 
 Core::addScript("public/js/Chart.bundle.min.js");
 Core::addScript("public/js/chartjs-plugin-datalabels.min.js");
@@ -47,7 +48,7 @@ $all_projects = Project::query([
 
 if(Core::$user->isCustomer()) {
 	// Filter to only projects that have past the deadline
-	$all_projects = array_filter($all_projects, function($project) {
+	$all_projects = array_filter($all_projects, function(Project $project) {
 		return $project->isPastDeadline();
 	});
 }
@@ -61,7 +62,7 @@ foreach($all_projects as $p) {
 $data = [];
 $region_data = [];
 $area_manager_data = [];
-$total_data = false;
+$total_data = new stdClass;
 
 $locations_missing_region = [];
 $locations_missing_area_manager = [];
@@ -214,7 +215,7 @@ if($submit) {
 		$same_year = ($min_year == $max_year);
 
 		// Filter tests based on date range
-		$tests = array_filter($tests, function($test) use ($min_unix, $max_unix) {
+		$tests = array_filter($tests, function(Test $test) use ($min_unix, $max_unix) {
 
 			$project = $test->getProject();
 
@@ -223,12 +224,8 @@ if($submit) {
 			$dt = new DateTime($dts . " UTC");
 			$unix = $dt->format("U");
 
-			if($unix < $min_unix) {
-				return false;
-			}
-			if($unix > $max_unix) {
-				return false;
-			}
+			if($unix < $min_unix) return false;
+			if($unix > $max_unix) return false;
 
 			return true;
 		});
@@ -249,26 +246,12 @@ if($submit) {
 					$resolution_name = "Month";
 
 					foreach(range(1, 12) as $month) {
-
 						if(!$same_year) $label = date("M Y", mktime(0, 0, 0, $month, 1, date("Y")));
 						else $label = date("M", mktime(0, 0, 0, $month, 1, date("Y")));
 
 						$month = str_pad($month, 2, "0", STR_PAD_LEFT);
-						$key = "$year-$month";
-						$data[$key] = clone $empty_data;
-						$data[$key]->label = $label;
-
-						foreach($region_data as &$r) {
-							$r[$key] = clone $empty_data;
-							$r[$key]->label = $label;
-						}
 
-						foreach($area_manager_data as &$a) {
-							$a[$key] = clone $empty_data;
-							$a[$key]->label = $label;
-						}
-
-						$keys[] = $key;
+						$keys[] = "$year-$month";
 						$key_labels[] = $label;
 					}
 
@@ -280,30 +263,34 @@ if($submit) {
 					$resolution_name = "Quarter";
 
 					foreach(range(1, 4) as $quarter) {
-
 						if(!$same_year) $label = "Q$quarter $year";
 						else $label = "Q$quarter";
 
-						$key = "$year-$quarter";
-						$data[$key] = clone $empty_data;
-						$data[$key]->label = $label;
-
-						foreach($region_data as &$r) {
-							$r[$key] = clone $empty_data;
-							$r[$key]->label = $label;
-						}
-
-						foreach($area_manager_data as &$a) {
-							$a[$key] = clone $empty_data;
-							$a[$key]->label = $label;
-						}
-
-						$keys[] = $key;
+						$keys[] = "$year-$quarter";
 						$key_labels[] = $label;
 					}
 
 					break;
 			}
+
+
+		}
+
+		foreach($keys as $index => $key) {
+			$label = $key_labels[$index];
+
+			$data[$key] = clone $empty_data;
+			$data[$key]->label = $label;
+
+			foreach($region_data as &$r) {
+				$r[$key] = clone $empty_data;
+				$r[$key]->label = $label;
+			}
+
+			foreach($area_manager_data as &$a) {
+				$a[$key] = clone $empty_data;
+				$a[$key]->label = $label;
+			}
 		}
 
 		$max_unix = 0;
@@ -364,9 +351,13 @@ if($submit) {
 		$current_month = date("m", $max_unix);
 		$current_quarter = ceil(date("n", $max_unix) / 3);
 
-		$x_data_labels = array_values(array_map(function($d) {
-			return $d->label;
-		}, $data));
+		// Initialise generator
+		$generator = new ChartGenerator($total_data, $data);
+		$generator->setDateRangeLabel($date_range_label);
+		$generator->setResolutionName($resolution_name);
+		$generator->setPeriodKeysAndLabels($keys, $key_labels);
+		$generator->setRegionData($region_data);
+		$generator->setAreaManagerData($area_manager_data);
 
 		// Build charts hook
 		require $template->getProcessingFilePath("reports_build_charts.php");

+ 11 - 5
controllers/test.php

@@ -1,5 +1,9 @@
 <?php
 
+/**
+ * @var Test $test
+ */
+
 Core::addScript("public/js/app-test.js");
 
 $test = Test::get($id);
@@ -187,7 +191,11 @@ if(Core::$user->level == User::LEVEL_TESTER) {
 					}
 				}
 
-				$test->pass = ($test->challenge_stage <= $template->pass_stage) ? 1 : 0; // Pass = Challenged during browsing or before
+				$test->pass = 1;
+				if($template->hasPassFail()) {
+					$test->pass = ($test->challenge_stage <= $template->getPassStage()) ? 1 : 0; // Pass = Challenged during browsing or before
+				}
+
 				$test->dts_updated = Util::getDateTime();
 
 				$success = $test->commit();
@@ -241,8 +249,6 @@ else if(Core::$user->level >= User::LEVEL_ADMIN) {
 
 	$directory = $test->getDirectory();
 
-	$has_pdf = file_exists($directory . "/pdf.pdf");
-
 	$submit = http::value("submit");
 	$tester_message = http::value("tester_message", "trim");
 	if($submit) {
@@ -447,7 +453,7 @@ else if(Core::$user->level >= User::LEVEL_ADMIN) {
 	});
 
 	View::includeOnce("header", compact("page_title"));
-	View::include("test_verify_form", compact("test", "has_pdf", "tester", "location", "project", "future_projects", "customer", "template", "fields", "values", "tester_message"));
+	View::include("test_verify_form", compact("test", "tester", "location", "project", "future_projects", "customer", "template", "fields", "values", "tester_message"));
 	View::includeOnce("footer");
 	return;
 }
@@ -460,4 +466,4 @@ else {
 	throw new Exception(__("Invalid request."));
 }
 
-?>
+?>

+ 16 - 4
controllers/test_file.php

@@ -3,10 +3,24 @@
 $test = Test::get($id);
 if(!$test) throw new Exception(__("Test not found."));
 
-if(Core::$user->level < User::LEVEL_ADMIN) {
-	if(Core::$user->id != $test->tester_id) throw new Exception(__("You do not have permission to access this resource."));
+$is_pdf = $name == "pdf";
+
+if($is_pdf) {
+	$project = $test->getProject();
+
+	$customers = Core::$user->getCustomers();
+	$customer_ids = array_column($customers, "id");
+
+	if(!in_array($project->customer_id, $customer_ids)) throw new Exception(__("You do not have permission to access this resource."));
 }
 
+if(!$is_pdf) {
+	if(Core::$user->level < User::LEVEL_ADMIN) {
+		if(Core::$user->id != $test->tester_id) throw new Exception(__("You do not have permission to access this resource."));
+	}
+}
+
+
 $directory = $test->getDirectory();
 $path_jpg = $directory . "/" . $name . ".jpg";
 $path_pdf = $directory . "/" . $name . ".pdf";
@@ -23,5 +37,3 @@ else {
 	header("Content-Type: image/png");
 	readfile("public/img/blank.png");
 }
-
-?>

+ 1 - 4
controllers/test_invoice.php

@@ -36,10 +36,7 @@ if(!$address) throw new Exception(__("Invoice address not found. Please set an a
 if(!$tester->hasValidPaymentMethod()) throw new Exception(__("No valid payment method found. Please go to the Settings page and make sure all respective fields are filled in and then try again."));
 
 // Filename
-$reference =
-	"T" . str_pad($test->id, 3, "0", STR_PAD_LEFT) .
-	"/L" . str_pad($location->id, 3, "0", STR_PAD_LEFT) .
-	"/U" . str_pad($tester->id, 3, "0", STR_PAD_LEFT);
+$reference = $test->getTesterInvoiceReference();
 
 $download_filename = str_replace("/", "_", $reference) . " - " . $tester->getDisplayName() . " - Invoice.pdf";
 

+ 16 - 0
controllers/test_results_customer_list.php

@@ -0,0 +1,16 @@
+<?php
+
+$customers = Core::$user->getCustomers();
+if(count($customers) == 1) {
+	$customer = $customers[0];
+	http::redirect($customer->getTestResultsUrl());
+}
+
+$page_title = __("Test Results");
+
+Core::addBreadcrumb("/account", __("Account"));
+Core::addBreadcrumb("/account/test-results", $page_title);
+
+View::includeOnce("header", compact("page_title"));
+View::include("test_results_customer_list", compact("customers"));
+View::includeOnce("footer");

+ 26 - 0
controllers/test_results_project_list.php

@@ -0,0 +1,26 @@
+<?php
+
+$customers = Core::$user->getCustomers();
+if(!$customers) throw new Exception(__("An unexpected error has occurred. Please try again later."));
+
+$customer_ids = array_column($customers, "id");
+if(!in_array($customer_id, $customer_ids)) throw new Exception(__("You do not have permission to access this page."));
+
+$customer = Customer::get($customer_id);
+$projects = $customer->getProjects();
+
+$projects = array_filter($projects, function($project) {
+    return $project->isFinished();
+});
+
+$test_results_url = $customer->getTestResultsUrl();
+
+$page_title = $customer->name;
+
+Core::addBreadcrumb("/account", __("Account"));
+Core::addBreadcrumb("/account/test-results", __("Test Results"));
+Core::addBreadcrumb($test_results_url, $customer->name);
+
+View::includeOnce("header", compact("page_title"));
+View::include("test_results_project_list", compact("projects"));
+View::includeOnce("footer");

+ 53 - 0
controllers/test_results_test_list.php

@@ -0,0 +1,53 @@
+<?php
+
+$customers = Core::$user->getCustomers();
+if(!$customers) throw new Exception(__("An unexpected error has occurred. Please try again later."));
+
+$project = Project::get($project_id);
+if(!$project) throw new Exception(__("Project not found."));
+
+$template = $project->getTemplate();
+$has_pass_fail = $template->hasPassFail();
+
+$customer_ids = array_column($customers, "id");
+if(!in_array($project->customer_id, $customer_ids)) throw new Exception(__("You do not have permission to access this page."));
+
+$customer = $project->getCustomer();
+$tests = $project->getTests();
+
+$location_ids = array_column($tests, "location_id");
+Location::load($location_ids);
+
+usort($tests, function($a, $b) {
+    $a_location = $a->getLocation();
+    $b_location = $b->getLocation();
+
+    return strnatcasecmp($a_location->name, $b_location->name);
+});
+
+$test_count = $project->getTestCount();
+$pass_count = $project->getPassCount();
+$fail_count = $project->getFailCount();
+
+$pass_percentage = 0;
+$fail_percentage = 0;
+
+$pass_fail_count = $pass_count + $fail_count;
+if($pass_fail_count > 0) {
+    $pass_percentage = number_format($pass_count / $pass_fail_count, 4) * 100;
+    $fail_percentage = 100 - $pass_percentage;
+}
+
+$project_list_url = $customer->getTestResultsUrl();
+$test_list_url = $project->getTestResultsUrl();
+
+$page_title = __("Test Results %s Test List", $project->name);
+
+Core::addBreadcrumb("/account", __("Account"));
+Core::addBreadcrumb("/account/test-results", __("Test Results"));
+Core::addBreadcrumb($project_list_url, $customer->name);
+Core::addBreadcrumb($test_list_url, $project->name);
+
+View::includeOnce("header", compact("page_title"));
+View::include("test_results_test_list", compact("project", "has_pass_fail", "tests", "test_count", "pass_count", "fail_count", "pass_percentage", "fail_percentage"));
+View::includeOnce("footer");

+ 2 - 0
controllers/tests_admin_list.php

@@ -171,5 +171,7 @@ $sorts = [
 	"due" => "Due",
 ];
 
+Core::addScript("public/js/app-test-list.js");
+
 View::includeOnce("header", compact("page_title"));
 View::include("test_list", compact("tests", "pagination_object", "sort", "sorts", "projects", "customers", "customer_id", "project_id", "location_id", "location_internal_id", "pass", "custom", "test_id", "tester_id", "filter_count", "status", "status_tester_invoice"));

+ 1 - 1
engine/account_icon.php

@@ -18,4 +18,4 @@ class AccountIcon {
 		$this->counter = $counter;
 	}
 
-}
+}

+ 28 - 8
engine/chart.php

@@ -1,8 +1,10 @@
-<?php
+<?php /** @noinspection DuplicatedCode */
+/** @noinspection PhpUnused */
+/** @noinspection PhpUndefinedMethodInspection */
+/** @noinspection PhpUnusedLocalVariableInspection */
 
-use PhpOffice\PhpPresentation\Style\Color;
+use PhpOffice\PhpPresentation\Slide;
 use PhpOffice\PhpPresentation\Style\Alignment;
-use PhpOffice\PhpPresentation\Shape\Drawing\Base64;
 
 class Chart {
 
@@ -59,6 +61,10 @@ class Chart {
 	public $printPercentages = false;
 	public $printTotalColumn = false;
 
+	/**
+	 * Chart constructor.
+	 * @throws Exception
+	 */
 	public function __construct() {
 		$this->id = bin2hex(random_bytes(8));
 	}
@@ -324,7 +330,17 @@ class Chart {
 					<?php
 					foreach($data as $value) {
 						?>
-						<td class="text-right"><?=number_format($value)?><?=htmlspecialchars($suffix)?></td>
+						<td class="text-right">
+                            <?php
+                            if($value === null) {
+                                ?>
+                                <small class="text-muted"><?=htmlspecialchars(__("N/A"))?></small>
+                                <?php
+                                continue;
+                            }
+                            ?>
+                            <?=number_format($value)?><?=htmlspecialchars($suffix)?>
+                        </td>
 						<?php
 					}
 
@@ -383,7 +399,7 @@ class Chart {
 	}
 
 	// Presentation methods
-	public function addChart($slide, $path) {
+	public function addChart(Slide $slide, string $path) {
 
 		$chart_offset_y = 100;
 		if($this->print) {
@@ -401,7 +417,13 @@ class Chart {
 		return true;
 	}
 
-	public function addDataTable($slide, $offset_x = 30, $offset_y = 540) {
+	/**
+	 * @param Slide $slide
+	 * @param int $offset_x
+	 * @param int $offset_y
+	 * @throws Exception
+	 */
+	public function addDataTable(Slide $slide, int $offset_x = 30, int $offset_y = 540) {
 
 		$labels = $this->getLabels();
 		$datasets = array_merge($this->getDatasets(), $this->getPrintDatasets());
@@ -506,5 +528,3 @@ class Chart {
 	}
 
 }
-
-?>

+ 1026 - 0
engine/chart_generator.php

@@ -0,0 +1,1026 @@
+<?php
+
+/**
+ * Class ChartGenerator
+ */
+
+class ChartGenerator {
+
+	const COLOUR_GREEN = "#4CAF50";
+	const COLOUR_RED = "#F44336";
+	const COLOUR_YELLOW = "#FFEB3B";
+	const COLOUR_LIGHT_GREY = "#CCCCCC";
+	const COLOUR_LIGHT_RED = "#FFAB91";
+	const COLOUR_ORANGE = "#FBC02D";
+	const COLOUR_BLUE = "#2196F3";
+	const COLOUR_MAGENTA = "#E91E63";
+	const COLOUR_DARK_BLUE = "#3F51B5";
+	const COLOUR_PURPLE = "#9C27B0";
+	const COLOUR_GREY = "#9E9E9E";
+	const COLOUR_CYAN = "#00BCD4";
+
+	/** @var object $totalData */
+	private $totalData;
+
+	/** @var array $periodicData */
+	private $periodicData;
+
+	/** @var string $dateRangeLabel */
+	private $dateRangeLabel;
+
+	/** @var string $resolutionName */
+	private $resolutionName;
+
+	/** @var string[] $xDataLabels */
+	private $xDataLabels;
+
+	/** @var string[] $periodKeys */
+	private $periodKeys;
+
+	/** @var string[] $periodLabels */
+	private $periodLabels;
+
+	/** @var array $regionData */
+	private $regionData;
+
+	/** @var array $areaManagerData */
+	private $areaManagerData;
+
+	public function __construct(object $total_data, array $periodic_data) {
+		$this->totalData = $total_data;
+		$this->periodicData = $periodic_data;
+
+		$this->xDataLabels = array_values(array_map(function($d) {
+			return $d->label;
+		}, $this->periodicData));
+	}
+
+	public function setDateRangeLabel(string $label) {
+		$this->dateRangeLabel = $label;
+	}
+
+	public function setResolutionName(string $name) {
+		$this->resolutionName = $name;
+	}
+
+	public function setPeriodKeysAndLabels(array $keys, array $labels) {
+		$this->periodKeys = $keys;
+		$this->periodLabels = $labels;
+	}
+
+	public function setRegionData(array $data) {
+		ksort($data, SORT_NATURAL);
+		$this->regionData = $data;
+	}
+
+	public function setAreaManagerData(array $data) {
+		ksort($data, SORT_NATURAL);
+		$this->areaManagerData = $data;
+	}
+
+	// Charts
+	public function getTestsByStageChart(): Chart {
+		$chart = new Chart;
+		$chart->setType("doughnut");
+		$chart->setTitle("Tests by Stage {$this->dateRangeLabel}");
+		$chart->setLabels(["1 - On Entry", "2 - While Browsing", "3 - During Play", "4 - On Exit", "5 - No Challenge"]);
+		$chart->addDataset("Tests", [
+			$this->totalData->stage1Count,
+			$this->totalData->stage2Count,
+			$this->totalData->stage3Count,
+			$this->totalData->stage4Count,
+			$this->totalData->stage5Count,
+		], [
+			"background_colours" => [
+				self::COLOUR_GREEN,
+				self::COLOUR_YELLOW,
+				self::COLOUR_ORANGE,
+				self::COLOUR_LIGHT_RED,
+				self::COLOUR_RED,
+			],
+			"datalabels" => Chart::DATALABELS_BOX,
+		]);
+		$chart->setPrintSuffixes("");
+		$chart->print = true;
+		$chart->printPercentages = true;
+		$chart->printTotalColumn = true;
+		$chart->setPrintLabels(["Stage 1", "Stage 2", "Stage 3", "Stage 4", "Stage 5"]);
+		return $chart;
+	}
+
+	public function getChallengerGenderChart(): Chart {
+		$chart = new Chart;
+		$chart->setType("pie");
+		$chart->setTitle("Staff Gender {$this->dateRangeLabel}");
+		$chart->setLabels(["Male", "Female", "Unspecified"]);
+		$chart->addDataset("Counts", [
+			$this->totalData->maleChallengerCount,
+			$this->totalData->femaleChallengerCount,
+			$this->totalData->unspecifiedChallengerCount,
+		], [
+			"background_colours" => [
+				self::COLOUR_BLUE,
+				self::COLOUR_MAGENTA,
+				self::COLOUR_GREY,
+			],
+			"datalabels" => Chart::DATALABELS_BOX,
+		]);
+		return $chart;
+	}
+
+	public function getTesterGenderChart(): Chart {
+		$chart = new Chart;
+		$chart->setType("pie");
+		$chart->setTitle("Tester Gender {$this->dateRangeLabel}");
+		$chart->setLabels(["Male", "Female"]);
+		$chart->addDataset("Counts", [
+			$this->totalData->maleTesterCount,
+			$this->totalData->femaleTesterCount,
+		], [
+			"background_colours" => [
+				self::COLOUR_BLUE,
+				self::COLOUR_MAGENTA,
+			],
+			"datalabels" => Chart::DATALABELS_BOX,
+		]);
+		return $chart;
+	}
+
+	public function getPassFailCountChart(): Chart {
+		$chart = new Chart;
+		$chart->setType("pie");
+		$chart->setTitle("Pass / Fail {$this->dateRangeLabel}");
+		$chart->setLabels(["Pass", "Fail"]);
+		$chart->addDataset("Counts", [
+			$this->totalData->passCount,
+			$this->totalData->failCount,
+		], [
+			"background_colours" => [
+				self::COLOUR_GREEN,
+				self::COLOUR_RED,
+			],
+			"datalabels" => Chart::DATALABELS_BOX,
+		]);
+		return $chart;
+	}
+
+	public function getPeriodicPassFailRateChart(): Chart {
+
+		$chart = new Chart;
+		$chart->addXAxis([
+			"type" => "category",
+			"stacked" => true,
+		]);
+		$chart->addYAxis([
+			"id" => "y-axis-1",
+			"tick_config" => ["min" => 0, "max" => 100],
+			"stacked" => true,
+		]);
+
+		$chart->setType("bar");
+		$chart->setTitle("Pass / Fail by {$this->resolutionName}");
+		$chart->setLabels($this->xDataLabels);
+		$chart->addDataset("Pass Rate (%)", $this->getPeriodicPassRates(), [
+			"background_colours" => self::COLOUR_GREEN
+		]);
+		$chart->addDataset("Fail Rate (%)", $this->getPeriodicFailRates(), [
+			"background_colours" => self::COLOUR_RED
+		]);
+		$chart->setDatalabelSuffixes("%", "%");
+		return $chart;
+	}
+
+	public function getPeriodicDoorSensorAlertPassRateChart(): Chart {
+		return $this->getPeriodicPassRateChart(
+			"Pass Rate by Door Sensor Alert",
+			$this->getPeriodicPassRateByDoorSensorAlert(1),
+			$this->getPeriodicPassRateByDoorSensorAlert(0),
+			$this->getPeriodicPassRateByDoorSensorAlert(2)
+		);
+	}
+
+	public function getPeriodicEyeContactPassRateChart(): Chart {
+		return $this->getPeriodicPassRateChart(
+			"Pass Rate by Eye Contact",
+			$this->getPeriodicPassRateByEyeContact(1),
+			$this->getPeriodicPassRateByEyeContact(0),
+			$this->getPeriodicPassRateByEyeContact(2)
+		);
+	}
+
+	public function getPeriodicLineOfSightPassRateChart(): Chart {
+
+		return $this->getPeriodicPassRateChart(
+			"Pass Rate by Line of Sight",
+			$this->getPeriodicPassRateByLineOfSight(1),
+			$this->getPeriodicPassRateByLineOfSight(0),
+			$this->getPeriodicPassRateByLineOfSight(2)
+		);
+
+	}
+
+	public function getPeriodicBarPurchasePassRateChart(): Chart {
+
+		return $this->getPeriodicPassRateChart(
+			"Pass Rate by Bar Purchase",
+			$this->getPeriodicPassRateByBarPurchase(1),
+			$this->getPeriodicPassRateByBarPurchase(0),
+			$this->getPeriodicPassRateByBarPurchase(2)
+		);
+
+	}
+
+	public function getPeriodicEyeContactChart(): Chart {
+
+		$rates = $this->getEyeContactRates();
+
+		$chart = new Chart;
+		$chart->addXAxis([
+			"type" => "category",
+			"stacked" => true,
+		]);
+		$chart->addYAxis([
+			"id" => "y-axis-1",
+			"tick_config" => ["min" => 0, "max" => 100],
+			"stacked" => true,
+		]);
+		$chart->setType("bar");
+		$chart->setTitle("Eye Contact by {$this->resolutionName}");
+		$chart->setLabels($this->xDataLabels);
+		$chart->addDataset("Yes (%)", array_column($rates, 0), [
+			"background_colours" => self::COLOUR_GREEN
+		]);
+		$chart->addDataset("No (%)", array_column($rates, 1), [
+			"background_colours" => self::COLOUR_RED
+		]);
+		$chart->setDatalabelSuffixes("%", "%");
+		return $chart;
+	}
+
+	public function getPeriodicTotalsChart(): Chart {
+
+		$test_counts = $this->getPeriodicTestCounts();
+		$pass_rates = $this->getPeriodicPassRates();
+		$pass_counts = $this->getPeriodicPassCounts();
+		$fail_counts = $this->getPeriodicFailCounts();
+
+		$chart = new Chart;
+		$chart->setType("bar");
+		$chart->setTitle("Totals by {$this->resolutionName}");
+		$chart->setLabels($this->xDataLabels);
+		$chart->addYAxis([
+			"id" => "y-axis-1",
+			"tick_config" => ["min" => 0, "max" => ceil(max($test_counts) / 10) * 10]
+		]);
+		$chart->addYAxis([
+			"position" => "right",
+			"id" => "y-axis-2",
+			"grid_lines" => false,
+			"tick_config" => ["min" => 0, "max" => 100]
+		]);
+
+		$chart->addDataset("Pass Rate (%)", $pass_rates, [
+			"border_colours" => self::COLOUR_YELLOW,
+			"background_colours" => "transparent",
+			"type" => "line",
+			"y_axis_id" => "y-axis-2",
+			"datalabels" => [
+				"display" => false
+			],
+			"line_tension" => 0,
+		]);
+		$chart->addDataset("Test Count", $test_counts, [
+			"background_colours" => self::COLOUR_BLUE,
+			"type" => "bar",
+			"y_axis_id" => "y-axis-1",
+			"datalabels" => [
+				"display" => false
+			],
+		]);
+		$chart->addDataset("Pass", $pass_counts, [
+			"background_colours" => self::COLOUR_GREEN,
+			"type" => "bar",
+			"y_axis_id" => "y-axis-1",
+			"datalabels" => [
+				"display" => false
+			],
+		]);
+		$chart->addDataset("Fail", $fail_counts, [
+			"background_colours" => self::COLOUR_RED,
+			"type" => "bar",
+			"y_axis_id" => "y-axis-1",
+			"datalabels" => [
+				"display" => false
+			],
+		]);
+		$chart->setDatalabelSuffixes("%", "", "", "");
+		$chart->print = true;
+		return $chart;
+	}
+
+	/**
+	 * @return Chart[]
+	 * @throws Exception
+	 */
+	public function getPointOfChallengeCharts(): array {
+		$charts = [];
+
+		foreach($this->periodKeys as $index => $key) {
+			$key_label = $this->periodLabels[$index];
+
+			$period_data = $this->periodicData[$key];
+
+			if($period_data->testCount == 0) continue;
+
+			$chart = new Chart;
+			$chart->setType("pie");
+			$chart->setTitle("$key_label Point of Challenge");
+			$chart->setLabels(["On Entry", "While Browsing", "During Play", "On Exit", "No Challenge"]);
+			$chart->addDataset("Counts", [
+				$period_data->stage1Count,
+				$period_data->stage2Count,
+				$period_data->stage3Count,
+				$period_data->stage4Count,
+				$period_data->stage5Count,
+			], [
+				"background_colours" => [
+					self::COLOUR_GREEN,
+					self::COLOUR_YELLOW,
+					self::COLOUR_ORANGE,
+					self::COLOUR_LIGHT_RED,
+					self::COLOUR_RED,
+				],
+				"datalabels" => Chart::DATALABELS_BOX,
+			]);
+			$charts[] = $chart;
+		}
+
+		return $charts;
+	}
+
+	public function getPeriodicTesterGenderChart(): Chart {
+
+		$male_counts = $this->getPeriodicMaleTesterCount();
+		$female_counts = $this->getPeriodicFemaleTesterCount();
+
+		$chart = new Chart;
+		$chart->addYAxis([
+			"id" => "y-axis-1",
+			"tick_config" => ["min" => 0, "max" => ceil(max(max($male_counts), max($female_counts)) / 10) * 10]
+		]);
+
+		$chart->setType("bar");
+		$chart->setTitle("Tester Gender by {$this->resolutionName}");
+		$chart->setLabels($this->xDataLabels);
+		$chart->addDataset("Male", $male_counts, [
+			"background_colours" => self::COLOUR_BLUE
+		]);
+		$chart->addDataset("Female", $female_counts, [
+			"background_colours" => self::COLOUR_MAGENTA
+		]);
+		return $chart;
+	}
+
+	public function getPeriodicTestCountChart(): Chart {
+		$test_counts = $this->getPeriodicTestCounts();
+
+		$chart = new Chart;
+		$chart->addYAxis([
+			"id" => "y-axis-1",
+			"tick_config" => ["min" => 0, "max" => ceil(max($test_counts) / 10) * 10]
+		]);
+		$chart->setType("bar");
+		$chart->setTitle("Tests by {$this->resolutionName}");
+		$chart->setLabels($this->xDataLabels);
+		$chart->addDataset("Tests", $test_counts, [
+			"background_colours" => self::COLOUR_BLUE
+		]);
+		$charts[] = $chart;
+		return $chart;
+	}
+
+	public function getGenderComparisonCharts(): array {
+
+		$charts = [];
+
+		$gender_keys = [
+			"maleChallengeMale" => [
+				"title" => "Male Challenge Male",
+				"label" => "M Cha. M",
+			],
+			"maleChallengeFemale" => [
+				"title" => "Male Challenge Female",
+				"label" => "M Cha. F",
+			],
+			"femaleChallengeMale" => [
+				"title" => "Female Challenge Male",
+				"label" => "F Cha. M",
+			],
+			"femaleChallengeFemale" => [
+				"title" => "Female Challenge Female",
+				"label" => "F Cha. F",
+			],
+			"unknownChallenge" => [
+				"title" => "Gender Not Specified",
+				"label" => "Gender Not Specified",
+			],
+		];
+
+		$gender_test_counts = [];
+		foreach($gender_keys as $gk => $gv) {
+			$gender_test_counts[] = array_sum(array_column($this->periodicData, "{$gk}Count"));
+		}
+
+		// Gender Comparison by Date Range
+		$chart = new Chart;
+		$chart->addYAxis([
+			"id" => "y-axis-1",
+			"tick_config" => ["min" => 0, "max" => ceil(max($gender_test_counts) / 10) * 10]
+		]);
+		$chart->setType("bar");
+		$chart->setTitle("Gender Comparison {$this->dateRangeLabel}");
+		$chart->setLabels(array_column($gender_keys, "label"));
+		$chart->addDataset("Tests", $gender_test_counts, [
+			"background_colours" => self::COLOUR_BLUE
+		]);
+		$charts[] = $chart;
+
+		// Gender Comparison by Resolution
+		$mcm_counts = array_column($this->periodicData, "maleChallengeMaleCount");
+		$mcf_counts = array_column($this->periodicData, "maleChallengeFemaleCount");
+		$fcm_counts = array_column($this->periodicData, "femaleChallengeMaleCount");
+		$fcf_counts = array_column($this->periodicData, "femaleChallengeFemaleCount");
+		$ns_counts = array_column($this->periodicData, "unknownChallengeCount");
+
+		$chart = new Chart;
+		$chart->addYAxis([
+			"id" => "y-axis-1",
+			"tick_config" => ["min" => 0, "max" => ceil(max(max($mcm_counts), max($mcf_counts), max($fcm_counts), max($fcf_counts)) / 10) * 10]
+		]);
+		$chart->setType("bar");
+		$chart->setTitle("Gender Comparison by {$this->resolutionName}");
+		$chart->setLabels($this->xDataLabels);
+		$chart->addDataset("M Cha. M", $mcm_counts, ["background_colours" => self::COLOUR_BLUE]);
+		$chart->addDataset("M Cha. F", $mcf_counts, ["background_colours" => self::COLOUR_DARK_BLUE]);
+		$chart->addDataset("F Cha. M", $fcm_counts, ["background_colours" => self::COLOUR_PURPLE]);
+		$chart->addDataset("F Cha. F", $fcf_counts, ["background_colours" => self::COLOUR_MAGENTA]);
+		$chart->addDataset("Not Specified", $ns_counts, ["background_colours" => self::COLOUR_GREY]);
+		$chart->print = true;
+		$charts[] = $chart;
+
+		// Gender Comparison Pass Rate by Resolution
+		/** @noinspection PhpUnusedLocalVariableInspection */
+		{
+			$mcm_pass_counts = array_column($this->periodicData, "maleChallengeMalePassCount");
+			$mcf_pass_counts = array_column($this->periodicData, "maleChallengeFemalePassCount");
+			$fcm_pass_counts = array_column($this->periodicData, "femaleChallengeMalePassCount");
+			$fcf_pass_counts = array_column($this->periodicData, "femaleChallengeFemalePassCount");
+			$ns_pass_counts = array_column($this->periodicData, "unknownChallengePassCount");
+		}
+
+		/**
+		 * @var float $mcm_pass_rates
+		 * @var float $mcf_pass_rates
+		 * @var float $fcm_pass_rates
+		 * @var float $fcf_pass_rates
+		 * @var float $ns_pass_rates
+		 */
+
+		foreach(["mcm", "mcf", "fcm", "fcf", "ns"] as $prefix) {
+			$pass_rates = [];
+			$pass_counts = ${$prefix . "_pass_counts"};
+			$test_counts = ${$prefix . "_counts"};
+
+			foreach($test_counts as $index => $test_count) {
+				if($test_count == 0) {
+					$pass_rates[] = 0;
+					continue;
+				}
+				$pass_rates[] = number_format(($pass_counts[$index] * 100) / $test_count, 2);
+			}
+
+			${$prefix . "_pass_rates"} = $pass_rates;
+		}
+
+		$chart = new Chart;
+		$chart->addYAxis([
+			"id" => "y-axis-1",
+			"tick_config" => ["min" => 0, "max" => 100],
+		]);
+		$chart->setType("bar");
+		$chart->setTitle("Gender Comparison Pass Rate by {$this->resolutionName}");
+		$chart->setLabels($this->xDataLabels);
+		$chart->addDataset("M Cha. M", $mcm_pass_rates, ["background_colours" => self::COLOUR_BLUE, "datalabels" => ["display" => false],  "line_tension" => 0]);
+		$chart->addDataset("M Cha. F", $mcf_pass_rates, ["background_colours" => self::COLOUR_DARK_BLUE, "datalabels" => ["display" => false], "line_tension" => 0]);
+		$chart->addDataset("F Cha. M", $fcm_pass_rates, ["background_colours" => self::COLOUR_PURPLE, "datalabels" => ["display" => false], "line_tension" => 0]);
+		$chart->addDataset("F Cha. F", $fcf_pass_rates, ["background_colours" => self::COLOUR_MAGENTA, "datalabels" => ["display" => false], "line_tension" => 0]);
+		$chart->addDataset("Not Specified", $ns_pass_rates, ["background_colours" => self::COLOUR_GREY, "datalabels" => ["display" => false], "line_tension" => 0]);
+		$chart->print = true;
+		$chart->setDatalabelSuffixes("%", "%", "%", "%", "%");
+		$charts[] = $chart;
+
+		// Gender Comparison Point of Challenge
+		foreach($this->periodKeys as $index => $key) {
+			$key_label = $this->periodLabels[$index];
+			$period_data = $this->periodicData[$key];
+
+			foreach($gender_keys as $prefix => $gv) {
+
+				$title = $gv["label"];
+				$test_count = $period_data->{$prefix . "Count"};
+				$stage_data = $period_data->{$prefix . "Stages"};
+
+				if($test_count == 0) continue;
+
+				$chart = new Chart;
+				$chart->setType("pie");
+				$chart->setTitle("$key_label $title Point of Challenge");
+				$chart->setLabels(["On Entry", "While Browsing", "During Play", "On Exit", "No Challenge"]);
+				$chart->addDataset("Counts", $stage_data, [
+					"background_colours" => [
+						self::COLOUR_GREEN,
+						self::COLOUR_YELLOW,
+						self::COLOUR_ORANGE,
+						self::COLOUR_LIGHT_RED,
+						self::COLOUR_RED,
+					],
+					"datalabels" => Chart::DATALABELS_BOX,
+				]);
+				$charts[] = $chart;
+			}
+		}
+
+		return $charts;
+	}
+
+	public function hasRegionData(): bool {
+		return $this->regionData !== null;
+	}
+
+	public function getRegionPassRateChart(): Chart {
+
+		$data_values = [];
+
+		$test_counts = [];
+		$pass_counts = [];
+		$fail_counts = [];
+
+		foreach($this->regionData as $region => $r_data) {
+			$total_region_test_count = array_sum(array_column($r_data, "testCount"));
+			$total_region_pass_count = array_sum(array_column($r_data, "passCount"));
+
+			$test_counts[] = $total_region_test_count;
+			$pass_counts[] = $total_region_pass_count;
+			$fail_counts[] = $total_region_test_count - $total_region_pass_count;
+
+			$data_values[] = ($total_region_test_count == 0) ? 0 : round(($total_region_pass_count * 100) / $total_region_test_count);
+		}
+
+		$chart = new Chart;
+		$chart->addYAxis([
+			"id" => "y-axis-1",
+			"tick_config" => ["min" => 0, "max" => 100]
+		]);
+		$chart->setType("bar");
+		$chart->setTitle("Region Pass Rate {$this->dateRangeLabel}");
+		$chart->setLabels($this->getRegionXDataLabels());
+		$chart->addDataset("Pass %", $data_values , [
+			"background_colours" => self::COLOUR_BLUE
+		]);
+		$chart->addPrintDataset("Tests", $test_counts);
+		$chart->addPrintDataset("Pass", $pass_counts);
+		$chart->addPrintDataset("Fail", $fail_counts);
+
+		$chart->setDatalabelSuffixes("%");
+		$chart->print = true;
+		$chart->printTotalColumn = true;
+
+		return $chart;
+	}
+
+	public function getPeriodicRegionPassRateChart(): Chart {
+		$chart = new Chart;
+		$chart->addYAxis([
+			"id" => "y-axis-1",
+			"tick_config" => ["min" => 0, "max" => 100]
+		]);
+		$chart->setType("bar");
+		$chart->setTitle("Region Pass Rate by {$this->resolutionName}");
+		$chart->setLabels($this->getRegionXDataLabels());
+
+		foreach($this->periodKeys as $index => $key) {
+			$data_values = [];
+			foreach($this->getRegionKeys() as $region) {
+				$r_data = $this->regionData[$region][$key];
+				$data_values[] = ($r_data->testCount == 0) ? 0 : round(($r_data->passCount * 100) / $r_data->testCount);
+			}
+			$chart->addDataset($this->periodLabels[$index], $data_values, ["background_colours" => Chart::COLOURS[$index]]);
+		}
+		$chart->setDatalabelSuffixes(...array_fill(0, count($this->periodKeys), "%"));
+		return $chart;
+	}
+
+	public function hasAreaManagerData(): bool {
+		return $this->areaManagerData !== null;
+	}
+
+	public function getAreaManagerPassRateChart(): Chart {
+
+		// Area Pass Rate (Selected Date Range)
+		$data_values = [];
+
+		$test_counts = [];
+		$pass_counts = [];
+		$fail_counts = [];
+
+		foreach($this->areaManagerData as $area_manager => $a_data) {
+			$total_area_manager_test_count = array_sum(array_column($a_data, "testCount"));
+			$total_area_manager_pass_count = array_sum(array_column($a_data, "passCount"));
+			$total_area_manager_fail_count = array_sum(array_column($a_data, "failCount"));
+
+			$test_counts[] = $total_area_manager_test_count;
+			$pass_counts[] = $total_area_manager_pass_count;
+			$fail_counts[] = $total_area_manager_fail_count;
+
+			$data_values[] = ($total_area_manager_test_count == 0) ? 0 : round(($total_area_manager_pass_count * 100) / $total_area_manager_test_count);
+		}
+
+		$chart = new Chart;
+		$chart->addXAxis([
+			"type" => "category",
+			"scale_label_config" => [
+				"display" => true,
+				"labelString" => "Area Manager",
+			]
+		]);
+		$chart->addYAxis([
+			"id" => "y-axis-1",
+			"tick_config" => ["min" => 0, "max" => 100]
+		]);
+		$chart->setType("bar");
+		$chart->setTitle("Area Manager Pass Rate {$this->dateRangeLabel}");
+		$chart->setLabels($this->getAreaManagerXDataLabels());
+		$chart->addDataset("Pass %", $data_values , [
+			"background_colours" => self::COLOUR_BLUE
+		]);
+		$chart->addPrintDataset("Tests", $test_counts);
+		$chart->addPrintDataset("Pass", $pass_counts);
+		$chart->addPrintDataset("Fail", $fail_counts);
+		$chart->setDatalabelSuffixes("%");
+		$chart->print = true;
+		$chart->printTotalColumn = true;
+		return $chart;
+	}
+
+	public function getPeriodicAreaManagerPassRateChart(): Chart {
+
+		$chart = new Chart;
+		$chart->addXAxis([
+			"type" => "category",
+			"scale_label_config" => [
+				"display" => true,
+				"labelString" => "Area Manager",
+			]
+		]);
+		$chart->addYAxis([
+			"id" => "y-axis-1",
+			"tick_config" => ["min" => 0, "max" => 100]
+		]);
+		$chart->setType("bar");
+		$chart->setTitle("Area Manager Pass Rate by {$this->resolutionName}");
+		$chart->setLabels($this->getAreaManagerXDataLabels());
+
+		foreach($this->periodKeys as $index => $key) {
+			$data_values = [];
+			foreach($this->getAreaManagerKeys() as $area_manager) {
+				$a_data = $this->areaManagerData[$area_manager][$key];
+				$data_values[] = ($a_data->testCount == 0) ? 0 : round(($a_data->passCount * 100) / $a_data->testCount);
+			}
+			$chart->addDataset($this->periodLabels[$index], $data_values, [
+				"background_colours" => Chart::COLOURS[$index],
+				"datalabels" => [
+					"display" => false,
+				],
+			]);
+		}
+		$chart->setDatalabelSuffixes(...array_fill(0, count($this->periodKeys), "%"));
+		return $chart;
+	}
+
+	public function getCleanlinessChart(): Chart {
+
+		$chart = new Chart;
+		$chart->setType("doughnut");
+		$chart->setTitle("Tests by Cleanliness {$this->dateRangeLabel}");
+		$chart->setLabels(["Very dirty", "Dirty", "Adequate", "Clean", "Very Clean"]);
+		$chart->addDataset("Tests", [
+			$this->totalData->cleanlinessCounts[0],
+			$this->totalData->cleanlinessCounts[1],
+			$this->totalData->cleanlinessCounts[2],
+			$this->totalData->cleanlinessCounts[3],
+			$this->totalData->cleanlinessCounts[4],
+		], [
+			"background_colours" => [
+				self::COLOUR_RED,
+				self::COLOUR_LIGHT_RED,
+				self::COLOUR_ORANGE,
+				self::COLOUR_YELLOW,
+				self::COLOUR_GREEN,
+			],
+			"datalabels" => Chart::DATALABELS_BOX,
+		]);
+		$chart->setPrintSuffixes("");
+		$chart->print = true;
+		$chart->printTotalColumn = true;
+		$chart->printPercentages = true;
+		return $chart;
+	}
+
+	/**
+	 * @return Chart[]
+	 * @throws Exception
+	 */
+	public function getPeriodicCleanlinessCharts(): array {
+		$charts = [];
+
+		foreach($this->periodKeys as $index => $key) {
+			$key_label = $this->periodLabels[$index];
+
+			$period_data = $this->periodicData[$key];
+
+			if($period_data->testCount == 0) continue;
+
+			$chart = new Chart;
+			$chart->setType("pie");
+			$chart->setTitle("$key_label Cleanliness");
+			$chart->setLabels(["Very dirty", "Dirty", "Adequate", "Clean", "Very Clean"]);
+			$chart->addDataset("Counts", [
+				$period_data->cleanlinessCounts[0],
+				$period_data->cleanlinessCounts[1],
+				$period_data->cleanlinessCounts[2],
+				$period_data->cleanlinessCounts[3],
+				$period_data->cleanlinessCounts[4],
+			], [
+				"background_colours" => [
+					self::COLOUR_RED,
+					self::COLOUR_LIGHT_RED,
+					self::COLOUR_ORANGE,
+					self::COLOUR_YELLOW,
+					self::COLOUR_GREEN,
+				],
+				"datalabels" => Chart::DATALABELS_BOX,
+			]);
+			$charts[] = $chart;
+		}
+
+		return $charts;
+	}
+
+	public function getPeriodicStaffBadgeWornChart(): Chart {
+		$staff_badge_worn_counts = array_column($this->periodicData, "staffBadgeWornCounts");
+
+		$unknown_counts = array_column($staff_badge_worn_counts, 0);
+		$no_counts = array_column($staff_badge_worn_counts, 1);
+		$yes_counts = array_column($staff_badge_worn_counts, 2);
+
+		$chart = new Chart;
+		$chart->setType("bar");
+		$chart->setTitle("Staff Badge Worn by {$this->resolutionName}");
+		$chart->setLabels($this->xDataLabels);
+		$chart->addDataset("Don't know", $unknown_counts, [
+			"background_colours" => self::COLOUR_LIGHT_GREY
+		]);
+		$chart->addDataset("No", $no_counts, [
+			"background_colours" => self::COLOUR_RED
+		]);
+		$chart->addDataset("Yes", $yes_counts, [
+			"background_colours" => self::COLOUR_GREEN
+		]);
+		return $chart;
+	}
+
+	public function getPeriodicStaffOfferedDrinkChart(): Chart {
+		$counts = array_column($this->periodicData, "staffOfferedDrinkCounts");
+		return $this->getPeriodicBooleanChart("Staff Offered Drink", $counts);
+	}
+
+	public function getPeriodicStaffOfferedPromotionChart(): Chart {
+		$counts = array_column($this->periodicData, "staffOfferedPromotionCounts");
+		return $this->getPeriodicBooleanChart("Staff Offered Promotion", $counts);
+	}
+
+	public function getPeriodicStaffOfferedHelpChart(): Chart {
+		$counts = array_column($this->periodicData, "staffOfferedHelpCounts");
+		return $this->getPeriodicBooleanChart("Staff Offered Help", $counts);
+	}
+
+	public function getPeriodicStaffBehaviourCharts(): array {
+
+		$charts = [];
+
+		foreach($this->periodKeys as $index => $key) {
+			$key_label = $this->periodLabels[$index];
+
+			$period_data = $this->periodicData[$key];
+
+			if($period_data->testCount == 0) continue;
+
+			$chart = new Chart;
+			$chart->setType("pie");
+			$chart->setTitle("$key_label Staff Behaviour");
+			$chart->setLabels(["N/A", "Rude", "Slightly rude", "Neither rude or polite", "Polite", "Very polite"]);
+			$chart->addDataset("Counts", [
+				$period_data->staffBehaviourCounts[0],
+				$period_data->staffBehaviourCounts[1],
+				$period_data->staffBehaviourCounts[2],
+				$period_data->staffBehaviourCounts[3],
+				$period_data->staffBehaviourCounts[4],
+				$period_data->staffBehaviourCounts[5],
+			], [
+				"background_colours" => [
+					self::COLOUR_LIGHT_GREY,
+					self::COLOUR_RED,
+					self::COLOUR_LIGHT_RED,
+					self::COLOUR_ORANGE,
+					self::COLOUR_YELLOW,
+					self::COLOUR_GREEN,
+				],
+				"datalabels" => Chart::DATALABELS_BOX,
+			]);
+			$charts[] = $chart;
+		}
+
+		return $charts;
+	}
+
+	public function getPeriodicStaffUniformChart(): Chart {
+		$counts = array_column($this->periodicData, "staffUniformCounts");
+		return $this->getPeriodicBooleanChart("Staff Uniform", $counts);
+	}
+
+	// Private methods
+
+	private function getPeriodicPassRates() {
+		return array_values(array_map(function($d) {
+			if($d->testCount == 0) return 0;
+			return round(($d->passCount / $d->testCount) * 100);
+		}, $this->periodicData));
+	}
+
+	private function getPeriodicFailRates() {
+		return array_values(array_map(function($d) {
+			if($d->testCount == 0) return 0;
+			$pass_rate = round(($d->passCount / $d->testCount) * 100);
+			return 100 - $pass_rate;
+		}, $this->periodicData));
+	}
+
+	private function getPeriodicPassRateByDoorSensorAlert(int $index) {
+		return array_values(array_map(function($data) use ($index) {
+			$test_count = $data->doorSensorAlertPassCounts[$index] + $data->doorSensorAlertFailCounts[$index];
+			if($test_count == 0) return null;
+
+			return round(($data->doorSensorAlertPassCounts[$index] / $test_count) * 100);
+		}, $this->periodicData));
+	}
+
+	private function getPeriodicPassRateByEyeContact(int $index) {
+		return array_values(array_map(function($data) use ($index) {
+			$test_count = $data->eyeContactPassCounts[$index] + $data->eyeContactFailCounts[$index];
+			if($test_count == 0) return null;
+			return round(($data->eyeContactPassCounts[$index] / $test_count) * 100);
+		}, $this->periodicData));
+	}
+
+	private function getPeriodicPassRateByLineOfSight(int $index) {
+		return array_values(array_map(function($data) use ($index) {
+			$test_count = $data->lineOfSightPassCounts[$index] + $data->lineOfSightFailCounts[$index];
+			if($test_count == 0) return null;
+			return round(($data->lineOfSightPassCounts[$index] / $test_count) * 100);
+		}, $this->periodicData));
+	}
+
+	private function getPeriodicPassRateByBarPurchase(int $index) {
+		return array_values(array_map(function($data) use ($index) {
+			$test_count = $data->barPurchasePassCounts[$index] + $data->barPurchaseFailCounts[$index];
+			if($test_count == 0) return null;
+			return round(($data->barPurchasePassCounts[$index] / $test_count) * 100);
+		}, $this->periodicData));
+	}
+
+	private function getEyeContactRates(): array {
+		return array_values(array_map(function($period) {
+			if($period->testCount == 0) return [0, 0, 0];
+
+			$yes = round(($period->eyeContactCounts[0] / $period->testCount) * 100);
+			$no = 100 - $yes;
+			$na = 0;
+
+			return [$yes, $no, $na];
+		}, $this->periodicData));
+	}
+
+	private function getPeriodicTestCounts(): array {
+		return array_column($this->periodicData, "testCount");
+	}
+
+	private function getPeriodicPassCounts(): array {
+		return array_column($this->periodicData, "passCount");
+	}
+
+	private function getPeriodicFailCounts(): array {
+		return array_column($this->periodicData, "failCount");
+	}
+
+	private function getPeriodicMaleTesterCount(): array {
+		return array_values(array_map(function($d) {
+			return $d->maleTesterCount;
+		}, $this->periodicData));
+	}
+
+	private function getPeriodicFemaleTesterCount(): array {
+		return array_values(array_map(function($d) {
+			return $d->femaleTesterCount;
+		}, $this->periodicData));
+	}
+
+	private function getRegionKeys(): array {
+		if(!$this->regionData) return [];
+		return array_keys($this->regionData);
+	}
+
+	private function getRegionXDataLabels(): array {
+		return array_map(function($key) {
+			return "Region $key";
+		}, $this->getRegionKeys());
+	}
+
+	private function getAreaManagerKeys(): array {
+		if(!$this->areaManagerData) return [];
+		return array_keys($this->areaManagerData);
+	}
+
+	private function getAreaManagerXDataLabels(): array {
+		return $this->getAreaManagerKeys();
+	}
+
+	private function getPeriodicBooleanChart(string $title, array $values): Chart {
+
+		$no_counts = array_column($values, 0);
+		$yes_counts = array_column($values, 1);
+
+		$chart = new Chart;
+		$chart->setType("bar");
+		$chart->setTitle("{$title} by {$this->resolutionName}");
+		$chart->setLabels($this->xDataLabels);
+		$chart->addDataset("No", $no_counts, [
+			"background_colours" => self::COLOUR_RED
+		]);
+		$chart->addDataset("Yes", $yes_counts, [
+			"background_colours" => self::COLOUR_GREEN
+		]);
+		return $chart;
+	}
+
+	private function getPeriodicPassRateChart(string $title, array $yes_rates, array $no_rates, ?array $null_rates = null) {
+
+		$chart = new Chart;
+		$chart->addYAxis([
+			"tick_config" => ["min" => 0, "max" => 100],
+		]);
+
+		$chart->setType("bar");
+		$chart->setTitle($title);
+		$chart->setLabels($this->xDataLabels);
+
+		$chart->setDatalabelSuffixes("%", "%");
+
+		$chart->addDataset("Yes", $yes_rates, [
+			"background_colours" => self::COLOUR_GREEN,
+			"border_colours" => self::COLOUR_GREEN,
+			"line_tension" => 0,
+			"datalabels" => ["display" => false],
+		]);
+
+		$chart->addDataset("No", $no_rates, [
+			"background_colours" => self::COLOUR_RED,
+			"border_colours" => self::COLOUR_RED,
+			"line_tension" => 0,
+			"datalabels" => ["display" => false],
+		]);
+
+		if($null_rates !== null) {
+			$chart->addDataset("Don't Know", $null_rates, [
+				"background_colours" => self::COLOUR_CYAN,
+				"border_colours" => self::COLOUR_CYAN,
+				"line_tension" => 0,
+				"datalabels" => ["display" => false],
+			]);
+			$chart->setDatalabelSuffixes("%", "%", "%");
+		}
+
+		$chart->print = true;
+		return $chart;
+	}
+
+}

+ 6 - 3
engine/constraint.php

@@ -22,7 +22,12 @@ class Constraint {
 	private $type;
 	private $values = [];
 
-	public function __construct($type) {
+	/**
+	 * Constraint constructor.
+	 * @param string $type
+	 * @throws Exception
+	 */
+	public function __construct(string $type) {
 		$type = "TYPE_" . strtoupper($type);
 		if(!defined("Constraint::$type")) throw new Exception("Constraint::$type is not defined.");
 		$this->type = constant("Constraint::$type");
@@ -73,5 +78,3 @@ class Constraint {
 	}
 
 }
-
-?>

+ 28 - 6
engine/core.php

@@ -1,7 +1,11 @@
-<?php
+<?php /** @noinspection PhpUnused */
+
 
 class Core {
 
+	/**
+	 * @var User $user
+	 */
 	public static $user = null;
 	public static $admin = false;
 
@@ -13,6 +17,8 @@ class Core {
 	public static $show_alerts = true;
 	public static $show_footer_content = true;
 
+	public static $allow_all_customers = false;
+
 	public static $page = 1;
 	public static $page_count = 1;
 
@@ -42,8 +48,11 @@ class Core {
 		Core::$breadcrumbs[] = [$url, $name];
 	}
 
-	public static function addScript($path) {
-		Core::$scripts[] = $path; // Path is relative to root directory
+	/**
+	 * @param string $path Path relative to root directory
+	 */
+	public static function addScript(string $path) {
+		Core::$scripts[] = $path;
 	}
 
 	public static function addStylesheet($path) {
@@ -79,6 +88,9 @@ class Core {
 		}
 	}
 
+	/**
+	 * @throws Exception
+	 */
 	public static function requireAdmin() {
 		Core::requireLogIn();
 		if(Core::$user->canAdmin() === false) {
@@ -86,6 +98,10 @@ class Core {
 		}
 	}
 
+	/**
+	 * @param $level
+	 * @throws Exception
+	 */
 	public static function requireUserLevel($level) {
 		Core::requireLogIn();
 		if(Core::$user->level < $level) {
@@ -97,11 +113,19 @@ class Core {
 		return !empty($_SESSION["user_id"]);
 	}
 
-	public static function validateCSRFToken($token) {
+	/**
+	 * @param string $token
+	 * @return bool
+	 * @throws Exception
+	 */
+	public static function validateCSRFToken(string $token) {
 		if($_SESSION["csrf_token"] !== $token) throw new Exception("CSRF attempt blocked.");
 		return true;
 	}
 
+	/**
+	 * @throws Exception
+	 */
 	public static function refuseAJAX() {
 		if(HTTP::isAJAX()) {
 			header("HTTP/1.1 403 Forbidden");
@@ -110,5 +134,3 @@ class Core {
 	}
 
 }
-
-?>

+ 50 - 3
engine/customer.php

@@ -1,5 +1,24 @@
 <?php
 
+/**
+ * @property int $id
+ * @property string $name
+ * @property string $address_1
+ * @property string $address_2
+ * @property string $city
+ * @property string $county
+ * @property string $postal_code
+ * @property string $country
+ * @property string $email
+ * @property string $phone
+ * @property string $invoice_contact_name
+ * @property bool $email_after_test
+ * @property bool $email_locations_after_test
+ * @property string $internal_id_field_name
+ * @property string $region_field_name
+ * @property string $area_manager_field_name
+ */
+
 class Customer extends Model {
 
 	protected static $table = "customer";
@@ -12,7 +31,12 @@ class Customer extends Model {
 	];
 
 	// Static methods
-	public static function getForAdmin() {
+
+	/**
+	 * @return Customer
+	 * @throws Exception
+	 */
+	public static function getForAdmin(): ?Customer {
 		$customers = Core::$user->getCustomers();
 		if(count($customers) == 0) throw new Exception("At least one customer must exist before this page can be accessed.");
 		else if(count($customers) == 1) {
@@ -33,7 +57,7 @@ class Customer extends Model {
 			// Enforce restriction if CUSTOMER or lower
 			if(Core::$user->level < User::LEVEL_ADMIN) {
 				$link = UserCustomer::get(Core::$user->id, $customer_id);
-				if(!$link) $customer = false;
+				if(!$link) $customer = null;
 			}
 		}
 
@@ -43,17 +67,40 @@ class Customer extends Model {
 	}
 
 	// Object methods
-	public function getLocations($query = []) {
+
+	/**
+	 * @param array $query
+	 * @return Location[]
+	 * @throws Exception
+	 */
+	public function getLocations(array $query = []): array {
 		$nvp = array_merge(["customer_id" => $this->id], $query);
 		return Location::query($nvp, ["sort" => "name"]);
 	}
 
+	/**
+	 * @return Project[]
+	 * @throws Exception
+	 */
 	public function getProjects() {
 		return Project::query(["customer_id" => $this->id], ["sort" => "dts_deadline", "order" => "desc"]);
 	}
 
+	/**
+	 * @return Template[]
+	 * @throws Exception
+	 */
 	public function getTemplates() {
 		return Template::query(["customer_id" => $this->id], ["sort" => "name"]);
 	}
 
+	/**
+	 * @return string
+	 */
+	public function getTestResultsUrl(): string {
+		$slug = Util::slugWithId($this->name, $this->id);
+		$url = "/account/test-results/{$slug}";
+		return $url;
+	}
+
 }

+ 134 - 49
engine/db.php

@@ -1,4 +1,4 @@
-<?php
+<?php /** @noinspection PhpUnused */
 
 class db {
 
@@ -9,69 +9,112 @@ class db {
 
 	public static $DB = null;
 
-	public static function affected_rows($link = null) {
+	public static function affected_rows(mysqli $link = null): int {
 		if(empty($link)) $link = db::$DB;
 		return mysqli_affected_rows($link);
 	}
 
-	public static function cast_all_rows($result, $class_name) {
-		$objects = [];
-		while($row = db::fetch_object($result)) {
-			$objects[] = new $class_name($row);
+	/**
+	 * @param string $host
+	 * @param string $username
+	 * @param string $password
+	 * @param string $database
+	 * @param int $port
+	 * @return mysqli
+	 * @throws Exception
+	 */
+	public static function connect(string $host, string $username, string $password, string $database = "", int $port = 3306): mysqli {
+		$link = @new mysqli($host, $username, $password, $database, $port);
+		db::$DB = $link;
+
+		if(!is_null($link->connect_error)) {
+			throw new Exception("Connect Error: " . $link->connect_error);
 		}
-		return $objects;
+		db::query("SET NAMES utf8mb4");
+		return $link;
 	}
 
-	public static function connect($host, $username, $password, $database = "", $port = 3306) {
-		db::$DB = @new mysqli($host, $username, $password, $database, $port);
-		if(!is_null(db::$DB->connect_error)) {
-			throw new Exception("Connect Error: " . db::$DB->connect_error);
-		}
-		db::query("SET NAMES utf8mb4");
-		return db::$DB;
+	/**
+	 * @param mysqli_result $result
+	 * @param int $row_number
+	 * @return bool
+	 */
+	public static function data_seek(mysqli_result $result, int $row_number): bool {
+		return mysqli_data_seek($result, $row_number);
 	}
 
-	public static function data_seek($result, $row_number) {
-		mysqli_data_seek($result, $row_number);
+	/**
+	 * @param $value
+	 * @return string
+	 */
+	public static function escape($value): string {
+		return mysqli_real_escape_string(db::$DB, $value);
 	}
 
-	public static function escape($string) {
-		return mysqli_real_escape_string(db::$DB, $string);
+	public static function escape_nvp(array $nvp): array {
+		foreach($nvp as $name => $value) {
+			$nvp[$name] = db::escape($value);
+		}
+		return $nvp;
 	}
 
-	public static function error() {
+	/**
+	 * @return string
+	 */
+	public static function error(): string {
 		return mysqli_error(db::$DB);
 	}
 
-	public static function fetch_array($result) {
+	/**
+	 * @param mysqli_result $result
+	 * @return array|null
+	 */
+	public static function fetch_array(mysqli_result $result): ?array {
 		return mysqli_fetch_array($result);
 	}
 
-	public static function fetch_assoc($result) {
+	/**
+	 * @param mysqli_result $result
+	 * @return array|null
+	 */
+	public static function fetch_assoc(mysqli_result $result): ?array {
 		return mysqli_fetch_assoc($result);
 	}
 
-	public static function fetch_object($result) {
+	/**
+	 * @param mysqli_result $result
+	 * @return object|null
+	 */
+	public static function fetch_object(mysqli_result $result): ?object {
 		return mysqli_fetch_object($result);
 	}
 
-	public static function fetch_row($result) {
+	/**
+	 * @param mysqli_result $result
+	 * @return array|null
+	 */
+	public static function fetch_row(mysqli_result $result): ?array {
 		return mysqli_fetch_row($result);
 	}
 
-	public static function free_result($result) {
+	public static function free_result(mysqli_result $result): void {
 		mysqli_free_result($result);
 	}
 
-	public static function get_value_string($pairs, $escape=false) {
+	/**
+	 * @param array $nvp
+	 * @param bool $escape
+	 * @return string
+	 */
+	public static function get_value_string(array $nvp, bool $escape = false): string {
 
 		if($escape) {
-			$pairs = array_map(array("db", "escape"), $pairs);
+			$nvp = db::escape_nvp($nvp);
 		}
 
-		$string_array = array();
+		$string_array = [];
 
-		foreach($pairs as $field => $value) {
+		foreach($nvp as $field => $value) {
 			if(is_null($value)) {
 				$string_array[] = "`$field`=NULL";
 			}
@@ -85,7 +128,12 @@ class db {
 		return implode(", ", $string_array);
 	}
 
-	public static function get_where_string($pairs, $options = []) {
+	/**
+	 * @param array $nvp
+	 * @param array|bool $options
+	 * @return string
+	 */
+	public static function get_where_string(array $nvp, $options = []): string {
 
 		$escape = false;
 		$fuzzy = false;
@@ -99,15 +147,14 @@ class db {
 			$fuzzy = $options["fuzzy"] ?? false;
 		}
 
-
 		if($escape) {
-			$pairs = array_map(array("db", "escape"), $pairs);
+			$nvp = db::escape_nvp($nvp);
 		}
 
-		$string_array = array();
+		$string_array = [];
 
-		foreach($pairs as $field => $value) {
-			if(is_null($value)) {
+		foreach($nvp as $field => $value) {
+			if($value === null) {
 				$string_array[] = "`$field` IS NULL";
 			}
 			else if(is_array($value)) {
@@ -128,17 +175,30 @@ class db {
 		return implode(" AND ", $string_array);
 	}
 
-	public static function has_index($table, $index_name) {
+	/**
+	 * @param string $table
+	 * @param string $index_name
+	 * @return bool
+	 * @throws Exception
+	 */
+	public static function has_index(string $table, string $index_name): bool {
 		$sql = "SHOW INDEX FROM `$table` WHERE `Key_name`='$index_name'";
 		$result = db::query($sql);
 		return db::num_rows($result)==1;
 	}
 
-	public static function insert_id() {
+	/**
+	 * @return int
+	 */
+	public static function insert_id(): int {
 		return mysqli_insert_id(db::$DB);
 	}
 
-	public static function num_rows($result) {
+	/**
+	 * @param mysqli_result $result
+	 * @return int
+	 */
+	public static function num_rows(mysqli_result $result): int {
 
 		if(is_bool($result)) {
 			return 0;
@@ -147,21 +207,40 @@ class db {
 		return mysqli_num_rows($result);
 	}
 
-	public static function object_or_false($result) {
-		return mysqli_num_rows($result)>0 ? db::fetch_object($result) : false;
+	/**
+	 * @param mysqli_result $result
+	 * @return object|null
+	 */
+	public static function object_or_null(mysqli_result $result): ?object {
+		return mysqli_num_rows($result)>0 ? db::fetch_object($result) : null;
 	}
 
-	public static function object_with_id($table, $field, $id) {
+	/**
+	 * @param string $table
+	 * @param string $field
+	 * @param int $id
+	 * @return object|null
+	 * @throws Exception
+	 */
+	public static function object_with_id(string $table, string $field, int $id): ?object {
 		$sql = "SELECT * FROM `$table` WHERE `$field`='$id'";
 		$result = db::query($sql);
-		return db::object_or_false($result);
+		return db::object_or_null($result);
 	}
 
-	public static function ping() {
+	/**
+	 * @return bool
+	 */
+	public static function ping(): bool {
 		return mysqli_ping(db::$DB);
 	}
 
-	public static function query($sql) {
+	/**
+	 * @param string $sql
+	 * @return bool|mysqli_result
+	 * @throws Exception
+	 */
+	public static function query(string $sql) {
 		if(!is_string($sql)) return false;
 
 		self::$last_query = $sql;
@@ -182,18 +261,24 @@ class db {
 		return $result;
 	}
 
-	public static function select_db($name, $link_identifier=NULL) {
+	/**
+	 * @param string $name
+	 * @param mysqli|null $link_identifier
+	 * @return bool
+	 */
+	public static function select_db(string $name, mysqli $link_identifier = null): bool {
 		if(is_null($link_identifier)) {
-			mysqli_select_db(db::$DB, $name);
+			return mysqli_select_db(db::$DB, $name);
 		}
 		else {
-			mysqli_select_db($link_identifier, $name);
+			return mysqli_select_db($link_identifier, $name);
 		}
 	}
 
-	public static function thread_id() {
+	/**
+	 * @return int
+	 */
+	public static function thread_id(): int {
 		return mysqli_thread_id(db::$DB);
 	}
 }
-
-?>

+ 77 - 20
engine/email.php

@@ -1,9 +1,10 @@
-<?php
+<?php /** @noinspection PhpUnused */
 
 use PHPMailer\PHPMailer\PHPMailer;
 
 class Email {
 
+    /** @var PHPMailer $instance */
 	private $instance;
 
 	private $htmlContent = "";
@@ -11,13 +12,25 @@ class Email {
 	// Static functions
 	public static function getPHPMailerInstance() {
 		$mail = new PHPMailer(true);
-		$mail->isSMTP();
-		$mail->Host = SMTP_HOST;
-		$mail->SMTPAuth = true;
-		$mail->Username = SMTP_USERNAME;
-		$mail->Password = SMTP_PASSWORD;
-		$mail->SMTPSecure = SMTP_AUTHENTICATION_TYPE;
-		$mail->Port = SMTP_PORT;
+
+		switch(MAILER) {
+            case "smtp":
+				$mail->isSMTP();
+				$mail->Host = SMTP_HOST;
+				$mail->SMTPAuth = true;
+				$mail->Username = SMTP_USERNAME;
+				$mail->Password = SMTP_PASSWORD;
+				$mail->SMTPSecure = SMTP_AUTHENTICATION_TYPE;
+				$mail->Port = SMTP_PORT;
+                break;
+            case "mail":
+				$mail->isMail();
+                break;
+            case "sendmail":
+                $mail->isSendmail();
+                break;
+        }
+
 		$mail->CharSet = 'UTF-8';
 		$mail->Encoding = 'base64';
 		return $mail;
@@ -41,7 +54,11 @@ class Email {
 		$this->instance = Email::getPHPMailerInstance();
 	}
 
-	public function loadHtmlTemplate($template_name) {
+	/**
+	 * @param string $template_name
+	 * @throws Exception
+	 */
+	public function loadHtmlTemplate(string $template_name) {
 
 		$this->instance->IsHTML(true);
 
@@ -53,41 +70,81 @@ class Email {
 		$this->htmlContent = $content;
 	}
 
-	public function setValues($values = []) {
+	/**
+	 * @param array $values
+	 * @return bool
+	 */
+	public function setValues(array $values = []) {
 		foreach($values as $key => $value) {
 			$this->htmlContent = str_replace("{" . $key . "}", $value, $this->htmlContent);
 		}
 		return true;
 	}
 
-	public function addAttachment($path, $name = "", $encoding = "base64", $type = "", $disposition = "attachment") {
+	/**
+	 * @param string $path
+	 * @param string $name
+	 * @param string $encoding
+	 * @param string $type
+	 * @param string $disposition
+	 * @return bool
+	 * @throws \PHPMailer\PHPMailer\Exception
+	 */
+	public function addAttachment(string $path, string $name = "", string $encoding = "base64", string $type = "", string $disposition = "attachment") {
 		return $this->instance->addAttachment($path, $name, $encoding, $type, $disposition);
 	}
 
-	public function setFrom($email, $name="") {
+	/**
+	 * @param string $email
+	 * @param string $name
+	 * @return bool
+	 * @throws \PHPMailer\PHPMailer\Exception
+	 */
+	public function setFrom(string $email, string $name = "") {
 		return $this->instance->setFrom($email, $name);
 	}
 
-	public function addAddress($email, $name="") {
+	/**
+	 * @param string $email
+	 * @param string $name
+	 * @return bool
+	 */
+	public function addAddress(string $email, string $name = "") {
 		return $this->instance->addAddress($email, $name);
 	}
 
-	public function addReplyTo($email, $name="") {
+	/**
+	 * @param string $email
+	 * @param string $name
+	 * @return bool
+	 */
+	public function addReplyTo(string $email, string $name = "") {
 		return $this->instance->addReplyTo($email, $name);
 	}
 
-	public function setSubject($subject) {
+	/**
+	 * @param string $subject
+	 * @return bool
+	 */
+	public function setSubject(string $subject) {
 		$this->instance->Subject = $subject;
 		return true;
 	}
 
-	public function setHtmlContent($string) {
+	/**
+	 * @param string $string
+	 */
+	public function setHtmlContent(string $string) {
 		$this->instance->IsHTML(true);
 
 		$this->htmlContent = $string;
 	}
 
-	public function send() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function send(): bool {
 		// Does our sanity checks and then send email
 		$instance = $this->instance;
 
@@ -97,7 +154,7 @@ class Email {
 		if(empty($this->htmlContent)) throw new Exception("No content is set.");
 
 		// Embed images
-		$match_count = preg_match_all("/src\=\"(\.\.\/public\/img\/[^\"]*)\"/i", $this->htmlContent, $all_matches);
+		$match_count = preg_match_all("/src=\"(\.\.\/public\/img\/[^\"]*)\"/i", $this->htmlContent, $all_matches);
 		if($match_count > 0) {
 
 			$paths = $all_matches[1];
@@ -114,7 +171,7 @@ class Email {
 			}
 		}
 
-		$count = preg_match_all("/\{([a-z\-]+)\}/", $this->htmlContent, $matches);
+		$count = preg_match_all("/{([a-z\-]+)}/", $this->htmlContent, $matches);
 		if($count > 0) {
 			$missing_keys = [];
 			foreach($matches[1] as $key) {
@@ -125,7 +182,7 @@ class Email {
 
 		$instance->Body = $this->htmlContent;
 
-		if(PRODUCTION || DEBUG_MODE) {
+		if(PRODUCTION || defined("DEBUG_MODE")) {
 			return $this->instance->send();
 		}
 		else {

+ 4 - 2
engine/email_builder.php

@@ -1,4 +1,6 @@
-<?php
+<?php /** @noinspection HtmlRequiredLangAttribute */
+/** @noinspection HtmlDeprecatedTag */
+/** @noinspection HtmlDeprecatedAttribute */
 
 class EmailBuilder {
 
@@ -135,4 +137,4 @@ EOD;
 
 	}
 
-}
+}

+ 54 - 12
engine/form.php

@@ -1,4 +1,4 @@
-<?php
+<?php /** @noinspection DuplicatedCode */
 
 class Form {
 
@@ -7,11 +7,20 @@ class Form {
 		1 => YES,
 	];
 
-	public static function checked($value) {
+	/**
+	 * @param $value
+	 * @return string
+	 */
+	public static function checked($value): string {
 		return !empty($value) ? "checked" : "";
 	}
 
-	public static function checkRecaptcha($required_score = 0.5) {
+	/**
+	 * @param float $required_score
+	 * @return bool
+	 * @throws Exception
+	 */
+	public static function checkRecaptcha(float $required_score = 0.5) {
 
 		if(!defined("GOOGLE_RECAPTCHA_SECRET")) return true;
 
@@ -124,7 +133,7 @@ class Form {
 			}
 		}
 
-		if(!$countries) return false;
+		if(!$countries) return;
 
 		$country_pairs = get_object_vars($countries);
 		sort($country_pairs);
@@ -142,7 +151,11 @@ class Form {
 		}
 	}
 
-	public static function renderField($options) {
+	/**
+	 * @param object $options
+	 * @throws Exception
+	 */
+	public static function renderField(object $options) {
 
 		switch($options->type) {
 
@@ -170,6 +183,11 @@ class Form {
 			case "file":
 				self::renderFileField($options);
 				break;
+
+            case "hr":
+                self::renderHorizontalBar($options);
+                break;
+
 		}
 
 	}
@@ -180,7 +198,11 @@ class Form {
 		<?php
 	}
 
-	private static function renderTextField($options) {
+	/**
+	 * @param object $options
+	 * @throws Exception
+	 */
+	private static function renderTextField(object $options) {
 		$id = str_replace("_", "-", $options->name);
 		$placeholder = "Enter " . strtolower($options->label);
 		$value = $options->value ?? http::value($options->name);
@@ -204,7 +226,11 @@ class Form {
 		<?php
 	}
 
-	private static function renderNumberField($options) {
+	/**
+	 * @param object $options
+	 * @throws Exception
+	 */
+	private static function renderNumberField(object $options) {
 		$id = str_replace("_", "-", $options->name);
 		$placeholder = "Enter " . strtolower($options->label);
 		$value = $options->value ?? http::value($options->name);
@@ -244,7 +270,11 @@ class Form {
 		<?php
 	}
 
-	private static function renderSelectField($options) {
+	/**
+	 * @param object $options
+	 * @throws Exception
+	 */
+	private static function renderSelectField(object $options) {
 		$id = str_replace("_", "-", $options->name);
 		$selected_value = $options->value ?? http::value($options->name);
 		$required = ($options->required ?? false) ? "required" : "";
@@ -277,9 +307,11 @@ class Form {
 		<?php
 	}
 
-	private static function renderFileField($options) {
+	/**
+	 * @param object $options
+	 */
+	private static function renderFileField(object $options) {
 		$id = str_replace("_", "-", $options->name);
-		$placeholder = "Enter " . strtolower($options->label);
 		$required = ($options->required ?? false) ? "required" : "";
 		$help_text = $options->helpText ?? false;
 		?>
@@ -299,7 +331,11 @@ class Form {
 		<?php
 	}
 
-	private static function renderTextareaField($options) {
+	/**
+	 * @param object $options
+	 * @throws Exception
+	 */
+	private static function renderTextareaField(object $options) {
 		$id = str_replace("_", "-", $options->name);
 		$placeholder = "Enter " . strtolower($options->label);
 		$value = $options->value ?? http::value($options->name);
@@ -323,6 +359,12 @@ class Form {
 		<?php
 	}
 
+	private static function renderHorizontalBar(object $options) {
+	    ?>
+        <hr />
+        <?php
+    }
+
 }
 
-?>
+?>

+ 1 - 1
engine/form_exception.php

@@ -30,4 +30,4 @@ class FormException extends Exception {
 		]);
 	}
 
-}
+}

+ 6 - 1
engine/geolocation.php

@@ -8,7 +8,6 @@ class Geolocation {
 	const MILES_IN_KM = 0.621371;
 	const KMS_IN_MILE = 1.60934;
 
-
 	public static function getBounds($lat_lng, $distance, $units = Geolocation::UNIT_MILES) {
 
 		list($latitude, $longitude) = $lat_lng;
@@ -65,6 +64,12 @@ class Geolocation {
 		}
 	}
 
+	/**
+	 * @param $address
+	 * @param string $region
+	 * @return array
+	 * @throws Exception
+	 */
 	public static function geocode($address, $region = "uk") {
 		$query = [
 			"address" =>  $address,

+ 0 - 2
engine/geolocation_bounds.php

@@ -40,5 +40,3 @@ class GeolocationBounds {
 	}
 
 }
-
-?>

+ 1 - 3
engine/html.php

@@ -15,9 +15,7 @@ class HTML {
 		$modified_time = filemtime($path);
 		$src = preg_replace("/^public\//", "/", $path);
 		?>
-		<link rel="stylesheet" type="text/css" href="<?=htmlspecialchars($src)?>?<?=$modified_time?>"></link>
+        <link rel="stylesheet" type="text/css" href="<?=htmlspecialchars($src)?>?<?=$modified_time?>" />
 		<?php
 	}
 }
-
-?>

+ 47 - 36
engine/http.php

@@ -8,7 +8,14 @@ class HTTP {
 		return (!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest");
 	}
 
-	public static function post($url, $fields_or_data, $curl_options = []) {
+	/**
+	 * @param string $url
+	 * @param $fields_or_data
+	 * @param array $curl_options
+	 * @return bool|string
+	 * @throws Exception
+	 */
+	public static function post(string $url, $fields_or_data, $curl_options = []) {
 
 		$curl_handle = curl_init($url);
 
@@ -38,7 +45,12 @@ class HTTP {
 		header("Pragma: public");
 	}
 
-	public static function getDateFromFields($prefix = "") {
+	/**
+	 * @param string $prefix
+	 * @return string
+	 * @throws Exception
+	 */
+	public static function getDateFromFields(string $prefix = ""): string {
 		$date = false;
 
 		if(empty($prefix)) {
@@ -66,7 +78,12 @@ class HTTP {
 		return $date;
 	}
 
-	public static function getDateTimeFromFields($prefix = "") {
+	/**
+	 * @param string $prefix
+	 * @return bool|string
+	 * @throws Exception
+	 */
+	public static function getDateTimeFromFields(string $prefix = "") {
 		$date = http::getDateFromFields($prefix);
 		if($date === false) return false;
 
@@ -96,9 +113,17 @@ class HTTP {
 		return "$date $hour:$minute:$second";
 	}
 
-	public static function value($key, $validation = "none", $request_type = "request") {
+	/**
+	 * @param string $key
+	 * @param string $validation
+	 * @param string $request_type
+	 * @return mixed
+	 * @throws Exception
+	 */
+	public static function value(string $key, string $validation = "none", string $request_type = "request") {
 
 		$request_type = strtolower($request_type);
+		$array = [];
 
 		switch($request_type) {
 
@@ -182,16 +207,16 @@ class HTTP {
 
 	public static function getUploadErrorString($error, $name = "file") {
 		switch($error) {
-			case UPLOAD_ERR_OK: return "The $name uploaded successfully.";
-			case UPLOAD_ERR_INI_SIZE: return "The $name uploaded was too large.";
-			case UPLOAD_ERR_FORM_SIZE: return "The $name uploaded was too large.";
-			case UPLOAD_ERR_PARTIAL: return "The $name uploaded was only partially uploaded.";
-			case UPLOAD_ERR_NO_FILE: return "No $name was uploaded.";
-			case UPLOAD_ERR_NO_TMP_DIR: return "The $name cannot be uploaded as the temporary folder is missing.";
-			case UPLOAD_ERR_CANT_WRITE: return "The $name cannot be written to disk.";
-			case UPLOAD_ERR_EXTENSION: return "The $name uploaded was blocked by an extension.";
+			case UPLOAD_ERR_OK: return sprintf(__("The %s uploaded successfully."), $name);
+			case UPLOAD_ERR_FORM_SIZE:
+			case UPLOAD_ERR_INI_SIZE: return sprintf(__("The %s uploaded was too large."), $name);
+			case UPLOAD_ERR_PARTIAL: return sprintf(__("The %s uploaded was only partially uploaded."), $name);
+			case UPLOAD_ERR_NO_FILE: return sprintf(__("No %s was uploaded."), $name);
+			case UPLOAD_ERR_NO_TMP_DIR: return sprintf(__("The %s cannot be uploaded as the temporary folder is missing."), $name);
+			case UPLOAD_ERR_CANT_WRITE: return sprintf(__("The %s cannot be written to disk."), $name);
+			case UPLOAD_ERR_EXTENSION: return sprintf(__("The %s uploaded was blocked by an extension."), $name);
 		}
-		return "Unknown error.";
+		return __("Unknown error.");
 	}
 
 	public static function setStatusCode($code) {
@@ -209,36 +234,22 @@ class HTTP {
 		header("HTTP/1.1 $string");
 	}
 
-	public static function validateUploadedFile($file) {
+	/**
+	 * @param array $file
+	 * @return bool
+	 * @throws Exception
+	 */
+	public static function validateUploadedFile(array $file) {
 		$file = (object) $file;
 		if($file->error > 0) {
 			switch($file->error) {
-				case UPLOAD_ERR_NO_FILE: throw new Exception("No file was submitted."); break;
-				case UPLOAD_ERR_INI_SIZE: throw new Exception("The uploaded file was too large."); break;
+				case UPLOAD_ERR_NO_FILE: throw new Exception(__("No file was submitted.")); break;
+				case UPLOAD_ERR_INI_SIZE: throw new Exception(__("The uploaded file was too large.")); break;
 			}
-			throw new Exception("The uploaded file could not be stored. Please try again later.");
+			throw new Exception(__("The uploaded file could not be stored. Please try again later."));
 		}
 		return true;
 	}
 
-	public static function sendFile($path) {
-		$modified_time = filemtime($path);
-		$mime_type = Picture::getFileMIMEType($path);
-
-		$max_age = 7 * 86400;
-
-		header("Cache-Control: public, max-age=$max_age");
-
-		header("Expires: " . date("r", time() + $max_age));
-		header("Pragma: cache");
-
-		header("Last-Modified: " . date("r", $modified_time));
-
-		header("X-Sendfile: " . $path);
-		header("Content-Type: " . $mime_type);
-	}
-
-
 }
 
-?>

+ 8 - 9
engine/image.php

@@ -7,19 +7,18 @@ class Image {
 	public static function isJPEG($path) {
 		$size = @getimagesize($path);
 		if(!$size) return false;
-		list($width, $height, $type) = $size;
+		list(, , $type) = $size;
 		if($type != IMAGETYPE_JPEG) return false;
 		return true;
 	}
 
-	public static function normalise($path, $size = 1920) {
+	public static function normalise($path, $max_width = 1920) {
 
 		$size = getimagesize($path);
 
-		list($width, $height, $type) = $size;
+		list($width, $height) = $size;
 
 		$exif = exif_read_data($path);
-		$orientation = 0;
 		$rotate_angle = 0;
 		$is_flipped = false;
 		if($exif !== false) {
@@ -33,13 +32,13 @@ class Image {
 		$original_image = imagecreatefromjpeg($path);
 
 		if($width > $height) {
-			if($width > 1920) {
-				$width = 1920;
+			if($width > $max_width) {
+				$width = $max_width;
 			}
 		}
 		else {
-			if($height > 1920) {
-				$ratio = $height / 1920;
+			if($height > $max_width) {
+				$ratio = $height / $max_width;
 				$width = floor($width / $ratio);
 			}
 		}
@@ -67,4 +66,4 @@ class Image {
 
 	}
 
-}
+}

+ 62 - 0
engine/invoice.php

@@ -0,0 +1,62 @@
+<?php
+
+/**
+ * @property InvoiceLineItem[] $lineItems
+ */
+
+class Invoice {
+
+    private $lineItems = [];
+    private $taxRate = 0.2;
+    private $reference = "";
+
+    public function addLineItem(InvoiceLineItem $item) {
+        $this->lineItems[] = $item;
+    }
+
+    public function addLineItems(array $items) {
+        foreach($items as $item) {
+            $this->addLineItem($item);
+        }
+    }
+
+    /**
+     * @return InvoiceLineItem[]
+     */
+    public function getLineItems(): array {
+        return $this->lineItems;
+    }
+
+    public function getTotal() {
+        $total = 0;
+        foreach($this->lineItems as $item) {
+            $total += $item->getTotal();
+        }
+        return $total;
+    }
+
+    public function getTaxRate(): float {
+        return $this->taxRate;
+    }
+
+    public function setTaxRate(float $tax_rate): void {
+        $this->taxRate = $tax_rate;
+    }
+
+    public function getTax() {
+        return round($this->getTotal() * $this->taxRate);
+    }
+
+    public function getTotalIncTax() {
+        return $this->getTotal() + $this->getTax();
+    }
+
+    public function setReference(string $reference): void {
+        $this->reference = $reference;
+    }
+
+    public function getReference(): string {
+        return $this->reference;
+    }
+
+}

+ 74 - 0
engine/invoice_line_item.php

@@ -0,0 +1,74 @@
+<?php
+
+/**
+ * @property string $name
+ * @property int $quantity
+ * @property float $price
+ */
+
+class InvoiceLineItem {
+
+    private $name = "Untitled Item";
+    private $quantity = 0;
+    private $price = 0;
+
+    // Static methods
+
+    // Object methods
+    public function __construct(string $name) {
+        $this->name = $name;
+    }
+
+    public function getName(): string {
+        return $this->name;
+    }
+
+    public function setName(string $name): void {
+        $this->name = $name;
+    }
+
+    public function incrementQuantity(): void {
+        ++$this->quantity;
+    }
+
+    public function getQuantity(): int {
+        return $this->quantity;
+    }
+
+    public function setQuantity(int $quantity): void {
+        $this->quantity = $quantity;
+    }
+
+    public function getDisplayQuantity(): string {
+        if($this->quantity == 0) return "-";
+        return $this->quantity;
+    }
+
+    public function addPrice(float $price): void {
+        $this->price += $price;
+    }
+
+    public function getPrice(): float {
+        return $this->price;
+    }
+
+    public function setPrice(float $price): void {
+        $this->price = $price;
+    }
+
+    public function getDisplayPrice(): string {
+        if($this->quantity == 0) return "-";
+        return "£" . number_format($this->getPrice(), 2);
+    }
+
+    public function getTotal(): float {
+        if($this->quantity == 0) return $this->price;
+        return $this->quantity * $this->price;
+    }
+
+    public function getDisplayTotal(): string {
+        return "£" . number_format($this->getTotal(), 2);
+    }
+
+
+}

+ 0 - 2
engine/json.php

@@ -41,5 +41,3 @@ class JSON {
 	}
 
 }
-
-?>

+ 137 - 6
engine/location.php

@@ -1,13 +1,51 @@
 <?php
 
+/**
+ * @property int $id
+ * @property int $customer_id
+ * @property string $name
+ * @property string $legal_entity_name
+ * @property string $address_1
+ * @property string $address_2
+ * @property string $city
+ * @property string $county
+ * @property string $postal_code
+ * @property string $state
+ * @property string $country
+ * @property string $email
+ * @property string $phone
+ * @property string $opening_hours
+ * @property string $shop_left
+ * @property string $shop_right
+ * @property string $brand
+ * @property string $region
+ * @property string $region_name
+ * @property string $internal_id
+ * @property string $area_manager
+ * @property string $area_manager_name
+ * @property string $area_manager_email
+ * @property string $operations_manager_name
+ * @property bool $do_not_test
+ * @property bool $closed
+ * @property double $latitude
+ * @property double $longitude
+ * @property string $dts_verified
+ */
+
 class Location extends Model {
 
 	protected static $table = "location";
 	protected static $id_field = "id";
-	protected static $fillable_fields = ["customer_id", "name", "legal_entity_name", "address_1", "address_2", "city", "county", "postal_code", "state", "country", "email", "phone", "opening_hours", "shop_left", "shop_right", "brand", "region", "region_name", "internal_id", "area_manager", "area_manager_name", "area_manager_email", "operations_manager_name", "closed", "latitude", "longitude", "dts_verified"];
+	protected static $fillable_fields = ["customer_id", "name", "legal_entity_name", "address_1", "address_2", "city", "county", "postal_code", "state", "country", "email", "phone", "opening_hours", "shop_left", "shop_right", "brand", "region", "region_name", "internal_id", "area_manager", "area_manager_name", "area_manager_email", "operations_manager_name", "do_not_test", "closed", "latitude", "longitude", "dts_verified"];
 
 	// Object methods
-	public function assignVenueTypes($types) {
+
+	/**
+	 * @param array $types
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function assignVenueTypes(array $types): bool {
 		$links = LocationVenueType::query(["location_id" => $this->id]);
 		foreach($links as $link) {
 			$link->delete();
@@ -23,14 +61,22 @@ class Location extends Model {
 		return true;
 	}
 
-	public function getVenueTypes() {
+	/**
+	 * @return VenueType[]
+	 * @throws Exception
+	 */
+	public function getVenueTypes(): array {
 		$links = LocationVenueType::query(["location_id" => $this->id]);
 		$ids = array_column($links, "venue_type_id");
 
 		return VenueType::query(["id" => $ids]);
 	}
 
-	public function getCustomer() {
+	/**
+	 * @return Customer|null
+	 * @throws Exception
+	 */
+	public function getCustomer(): ?Customer {
 		return Customer::get($this->customer_id);
 	}
 
@@ -57,6 +103,10 @@ class Location extends Model {
 		];
 	}
 
+	/**
+	 * @return LocationFile[]
+	 * @throws Exception
+	 */
 	public function getPhotos() {
 		return LocationFile::query([
 			"location_id" => $this->id,
@@ -64,6 +114,87 @@ class Location extends Model {
 		]);
 	}
 
-}
+	/**
+	 * @return Test[]
+	 * @throws Exception
+	 */
+	public function getTests() {
+		return Test::query([
+			"location_id" => $this->id,
+			"status" => (new Constraint("MORE_THAN_OR_EQUAL"))->setValues(Test::STATUS_UNASSIGNED),
+		], [
+			"sort" => "dts_start",
+			"order" => "desc",
+		]);
+	}
+
+	/**
+	 * @return Test[]
+	 * @throws Exception
+	 */
+	public function getCompletedTests() {
+		return Test::query([
+			"location_id" => $this->id,
+			"status" => Test::STATUS_COMPLETED,
+		], [
+			"sort" => "dts_start",
+			"order" => "desc",
+		]);
+	}
+
+	/**
+	 * @param object $old_data
+	 * @param array $modified_fields
+	 * @return bool
+	 * @throws Exception
+	 */
+    public function logUpdate(object $old_data, array $modified_fields): bool {
+
+		if(empty($modified_fields)) return true;
+
+        $entry = new LocationUpdateLogEntry;
+        $entry->location_id = $this->id;
+        $entry->user_id = Core::$user->id;
+        $entry->modifications_json = json_encode($this->getModifiedArray($old_data, $modified_fields));
+        $entry->dts = Util::getDateTime();
+        return $entry->commit();
+	}
 
-?>
+	/**
+	 * @return LocationUpdateLogEntry[]
+	 * @throws Exception
+	 */
+	public function getUpdateLogEntries() {
+
+		return LocationUpdateLogEntry::query([
+			"location_id" => $this->id,
+		], [
+			"sort" => "dts",
+			"order" => "desc",
+		]);
+
+	}
+
+	/**
+	 * @param object $old_data
+	 * @param array $modified_fields
+	 * @return array
+	 */
+    private function getModifiedArray(object $old_data, array $modified_fields): array {
+
+		$new_data = $this->getModelData();
+
+        $modified = [];
+
+        foreach($modified_fields as $field) {
+            $modified[] = [
+				"field" => $field,
+                "before" => $old_data->$field,
+                "after" => $new_data->$field,
+            ];
+        }
+
+        return $modified;
+    }
+
+}

+ 16 - 4
engine/location_file.php

@@ -1,5 +1,14 @@
 <?php
 
+/**
+ * Class LocationFile
+ *
+ * @property int $id
+ * @property int $location_id
+ * @property int $type
+ * @property string $dts_uploaded
+ */
+
 class LocationFile extends Model {
 
 	protected static $table = "location_file";
@@ -9,9 +18,12 @@ class LocationFile extends Model {
 	const TYPE_PHOTO = 1;
 
 	// Object methods
-	public function getLocation() {
-		return Location::get($location_id);
+
+	/**
+	 * @return Location|null
+	 * @throws Exception
+	 */
+	public function getLocation(): ?Location {
+		return Location::get($this->location_id);
 	}
 }
-
-?>

+ 42 - 0
engine/location_update_log_entry.php

@@ -0,0 +1,42 @@
+<?php
+
+/**
+ * @property int $id
+ * @property int $location_id
+ * @property int $user_id
+ * @property string $modifications_json
+ * @property string $dts
+ */
+
+class LocationUpdateLogEntry extends Model {
+
+	protected static $table = "location_update_log_entry";
+	protected static $id_field = "id";
+	protected static $fillable_fields = ["location_id", "user_id", "modifications_json", "dts"];
+
+	// Object methods
+
+	/**
+	 * @return Location
+	 * @throws Exception
+	 */
+	public function getLocation(): ?Location {
+		return Location::get($this->location_id);
+	}
+
+	/**
+	 * @return User
+	 * @throws Exception
+	 */
+	public function getUser(): ?User {
+		return User::get($this->user_id);
+	}
+
+	/**
+	 * @return array
+	 */
+	public function getModifications(): array {
+		return json_decode($this->modifications_json) ?: [];
+	}
+
+}

+ 7 - 0
engine/location_venue_type.php

@@ -1,5 +1,12 @@
 <?php
 
+/**
+ * Class LocationVenueType
+ *
+ * @property int $location_id
+ * @property int $venue_type_id
+ */
+
 class LocationVenueType extends Model {
 
 	protected static $table = "location_venue_type";

+ 133 - 31
engine/model.php

@@ -1,4 +1,4 @@
-<?php
+<?php /** @noinspection PhpUnused */
 
 abstract class Model {
 
@@ -17,7 +17,12 @@ abstract class Model {
 	protected $in_db;
 
 	// Magic methods
-	public function __get($name) {
+
+	/**
+	 * @param string $name
+	 * @return mixed
+	 */
+	public function __get(string $name) {
 
 		if(in_array($name, static::$object_fields)) {
 			return $this->$name ?? null;
@@ -30,7 +35,12 @@ abstract class Model {
 		return isset($this->model_data->$name) ? $this->model_data->$name : null;
 	}
 
-	public function __set($name, $value) {
+	/**
+	 * @param string $name
+	 * @param string $value
+	 * @throws Exception
+	 */
+	public function __set(string $name, $value): void {
 
 		if(in_array($name, static::$object_fields)) {
 			$this->$name = $value;
@@ -68,14 +78,23 @@ abstract class Model {
 		}
 	}
 
-	public function __isset($name) {
+	/**
+	 * @param string $name
+	 * @return bool
+	 */
+	public function __isset(string $name) {
 		$value = $this->$name;
 		return !is_null($value);
 	}
 
 	// Static method
 
-	public static function get($id) {
+	/**
+	 * @param $id
+	 * @return static|null
+	 * @throws Exception
+	 */
+	public static function get($id): ?object {
 
 		$table = static::$table;
 		$is_compound_key = is_array(static::$id_field);
@@ -86,13 +105,13 @@ abstract class Model {
 		}
 
 		$id_field = static::$id_field;
-		$class = get_called_class();
+		$nvp = [];
 
-		if($is_compound_key) { // Compound key
+		if($is_compound_key && is_array($id_field)) { // Compound key
 			$args = func_get_args();
 			$fields = $id_field;
 
-			if(count($args) != count($fields)) return false;
+			if(count($args) != count($fields)) return null;
 
 			foreach($fields as $index => $field) {
 				$nvp[$field] = $args[$index];
@@ -106,10 +125,10 @@ abstract class Model {
 
 		$sql = "SELECT * FROM `$table` WHERE $where";
 		$result = db::query($sql);
-		$object = db::object_or_false($result);
+		$object = db::object_or_null($result);
 
 		if($object) {
-			$object = new $class($object);
+			$object = new static($object);
 			if(!$is_compound_key) {
 				static::$repositories[$table][$id] = $object;
 			}
@@ -118,7 +137,13 @@ abstract class Model {
 		return $object;
 	}
 
-	public static function getOrException($id, $exception_message = false) {
+	/**
+	 * @param int $id
+	 * @param bool $exception_message
+	 * @return static|null
+	 * @throws Exception
+	 */
+	public static function getOrException(int $id, bool $exception_message = false): ?object {
 
 		if(!$exception_message) $exception_message = get_called_class() . " not found.";
 
@@ -127,7 +152,11 @@ abstract class Model {
 		return $object;
 	}
 
-	public static function getAll() {
+	/**
+	 * @return static[]
+	 * @throws Exception
+	 */
+	public static function getAll(): array {
 		$objects = [];
 
 		$table = static::$table;
@@ -141,7 +170,12 @@ abstract class Model {
 		return $objects;
 	}
 
-	public static function load(...$id_sets) {
+	/**
+	 * @param array ...$id_sets
+	 * @return static[]
+	 * @throws Exception
+	 */
+	public static function load(...$id_sets): array {
 
 		$table = static::$table;
 
@@ -162,7 +196,11 @@ abstract class Model {
 		return $items;
 	}
 
-	public static function loadAll() {
+	/**
+	 * @return static[]
+	 * @throws Exception
+	 */
+	public static function loadAll(): array {
 		$table = static::$table;
 
 		$items = static::query([], ["id_as_key" => true]);
@@ -173,7 +211,12 @@ abstract class Model {
 		return $items;
 	}
 
-	public static function deleteMultiple($nvp = []) {
+	/**
+	 * @param array $nvp
+	 * @return int
+	 * @throws Exception
+	 */
+	public static function deleteMultiple($nvp = []): int {
 		$table = static::$table;
 
 		$vs = "1";
@@ -182,8 +225,6 @@ abstract class Model {
 			$vs = db::get_where_string($nvp);
 		}
 
-		$objects = [];
-
 		$sql = "DELETE FROM `$table` WHERE $vs";
 		$result = db::query($sql);
 		if(!$result) return false;
@@ -191,7 +232,13 @@ abstract class Model {
 		return db::affected_rows();
 	}
 
-	public static function query($nvp = [], $options = []) {
+	/**
+	 * @param string|array $nvp
+	 * @param array $options
+	 * @return static[]
+	 * @throws Exception
+	 */
+	public static function query($nvp = [], $options = []): array {
 		if(is_array($nvp)) {
 			return static::findByNVP($nvp, $options);
 		}
@@ -200,17 +247,33 @@ abstract class Model {
 		}
 	}
 
-	public static function queryFuzzy($nvp = [], $options = []) {
+	/**
+	 * @param array $nvp
+	 * @param array $options
+	 * @return static[]
+	 * @throws Exception
+	 */
+	public static function queryFuzzy($nvp = [], $options = []): array {
 		$options["fuzzy"] = true;
 		return static::findByNVP($nvp, $options);
 	}
 
-	public static function queryOne($nvp = [], $options = []) {
+	/**
+	 * @param array $nvp
+	 * @param array $options
+	 * @return static|null
+	 * @throws Exception
+	 */
+	public static function queryOne($nvp = [], $options = []): ?object {
 		$rows = static::findByNVP($nvp, $options);
-		return $rows ? $rows[0] : false;
+		return $rows ? $rows[0] : null;
 	}
 
-	private static function getRemappedNVP($nvp = []) {
+	/**
+	 * @param array $nvp
+	 * @return array
+	 */
+	private static function getRemappedNVP($nvp = []): array {
 		$mapped_nvp = [];
 		foreach($nvp as $field => $value) {
 			$field = static::$field_map[$field] ?? $field;
@@ -219,7 +282,12 @@ abstract class Model {
 		return $mapped_nvp;
 	}
 
-	public static function count($nvp = []) {
+	/**
+	 * @param array $nvp
+	 * @return int
+	 * @throws Exception
+	 */
+	public static function count($nvp = []): int {
 		$table = static::$table;
 
 		$vs = "1";
@@ -228,8 +296,6 @@ abstract class Model {
 			$vs = db::get_where_string($nvp);
 		}
 
-		$objects = [];
-
 		$sql = "SELECT COUNT(*) AS `count` FROM `$table` WHERE $vs";
 		$result = db::query($sql);
 		$row = db::fetch_object($result);
@@ -237,7 +303,13 @@ abstract class Model {
 		return $row->count;
 	}
 
-	public static function findByNVP($nvp, $options = []) {
+	/**
+	 * @param array $nvp
+	 * @param array $options
+	 * @return static[]
+	 * @throws Exception
+	 */
+	public static function findByNVP(array $nvp, array $options = []): array {
 
 		if(empty($nvp)) {
 			$vs = "1";
@@ -250,7 +322,13 @@ abstract class Model {
 		return static::findByValueString($vs, $options);
 	}
 
-	private static function findByValueString($vs, $options = []) {
+	/**
+	 * @param string $vs
+	 * @param array $options
+	 * @return static[]
+	 * @throws Exception
+	 */
+	private static function findByValueString(string $vs, array $options = []): array {
 		$table = static::$table;
 
 		$options = (object) $options;
@@ -322,7 +400,7 @@ abstract class Model {
 		$id = $this->getID();
 
 		$nvp = [];
-		if(is_array($id)) {
+		if(is_array($id) && is_array($id_field)) {
 			$nvp = array_combine($id_field, $id);
 		}
 		else {
@@ -334,6 +412,11 @@ abstract class Model {
 		return $where;
 	}
 
+	/**
+	 * @param bool $testing
+	 * @return bool
+	 * @throws Exception
+	 */
 	public final function commit($testing = false) {
 
 		$this->preCommit();
@@ -394,19 +477,36 @@ abstract class Model {
 			$this->in_db = true;
 		}
 
+		if($result) {
+			$this->modified_fields = [];
+		}
+
 		return !empty($result);
 	}
 
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function testCommit() {
 		return $this->commit(true);
 	}
 
+	/**
+	 * @param bool $testing
+	 * @return bool
+	 * @throws Exception
+	 */
 	public final function commitOrException($testing = false) {
 		$success = $this->commit($testing);
 		if(!$success) throw new Exception("Database error.");
 		return $success;
 	}
 
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function delete() {
 		$table = static::$table;
 
@@ -419,9 +519,13 @@ abstract class Model {
 		$sql = "DELETE FROM `$table` WHERE $where";
 		$result = db::query($sql);
 
-		return empty($result) ? false : db::affected_rows() ? true : false;
+		return empty($result) ? false : (db::affected_rows() ? true : false);
 	}
 
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
 	public final function deleteOrException() {
 		$success = $this->delete();
 		if(!$success) throw new Exception("Database error.");
@@ -450,5 +554,3 @@ abstract class Model {
 	}
 
 }
-
-?>

+ 22 - 6
engine/practice_test.php

@@ -2,23 +2,39 @@
 
 class PracticeTest extends Test {
 
-	protected $values = [];
+	private $values = [];
+	private $template_id = null;
 
 	// Constants
-	public function getValues($as_assoc_array = false) {
+
+	/**
+	 * @param bool $as_assoc_array
+	 * @return array
+	 */
+	public function getValues(bool $as_assoc_array = false): array {
 		return $this->values;
 	}
 
-	public function setValue($key, $value) {
+	/**
+	 * @param string $key
+	 * @param string $value
+	 * @return bool
+	 */
+	public function setValue(string $key, string $value): bool {
 		$this->values[$key] = $value;
 		return true;
 	}
 
-	public function getDirectory() {
+	/**
+	 * @return string
+	 */
+	public function getDirectory(): string {
 		$directory = ROOT_DIR . "/files/users/$this->tester_id/practice_tests/$this->template_id";
 		if(!file_exists($directory)) mkdir($directory, 0777, true);
 		return $directory;
 	}
-}
 
-?>
+	public function setTemplateId(int $id) {
+		$this->template_id = $id;
+	}
+}

+ 376 - 34
engine/project.php

@@ -1,34 +1,190 @@
-<?php
+<?php /** @noinspection PhpIncludeInspection */
+
+/**
+ * @property int $id
+ * @property int $customer_id
+ * @property int $template_id
+ * @property string $name
+ * @property int $test_count
+ * @property int $min_age
+ * @property int $max_age
+ * @property float $default_customer_fee
+ * @property float $default_tester_fee
+ * @property int $time_of_day
+ * @property bool $tester_can_claim
+ * @property string $template_overrides_json
+ * @property string $dts_start
+ * @property string $dts_deadline
+ * @property string $dts_created
+ * @property string $dts_updated
+ * @property string $dts_report
+ * @property string $dts_finished
+ * @property int $user_id_finished
+ */
 
 class Project extends Model {
 
+	const TOD_ANYTIME = "A";
+	const TOD_DAYTIME = "D";
+	const TOD_NIGHTTIME = "N";
+
 	protected static $table = "project";
 	protected static $id_field = "id";
 	protected static $fillable_fields = ["customer_id", "template_id", "name", "test_count", "min_age", "max_age", "default_customer_fee", "default_tester_fee", "time_of_day", "tester_can_claim", "template_overrides_json", "dts_start", "dts_deadline", "dts_created", "dts_updated", "dts_report", "dts_finished", "user_id_finished"];
 
-	protected static $field_map = [
-	];
+	/**
+	 * @var Test[] $tests
+	 */
+	protected $tests = null;
+
+	// Static methods
+
+	/**
+	 * @param string $processing_file
+	 * @param array $projects
+	 * @throws Exception
+	 */
+	public static function exportCSV(string $processing_file, /** @noinspection PhpUnusedParameterInspection */ $projects = []) {
+
+		// Get processing file
+		$processing_file_path = ROOT_DIR . "/export_processing/{$processing_file}";
+		if(!file_exists($processing_file_path)) throw new Exception("Processing file not found.");
+
+		// Output
+		HTTP::setDownloadHeaders("export.csv");
+
+		$handle = fopen("php://output", "w");
+		require $processing_file_path;
+		fclose($handle);
+	}
+
+	/**
+	 * @return string[]
+	 * @throws Exception
+	 */
+	public static function getReportMonths(): array {
+
+		$current_report_month = new DateTime("2018-01-01", new DateTimeZone("UTC"));
+
+		$month_interval = new DateInterval("P1M");
+
+		$report_months = [];
+
+		do {
+			$key = $current_report_month->format("Y-m");
+			$report_months[$key] = $current_report_month->format("M Y");
+			$current_report_month->add($month_interval);
+			$time = $current_report_month->format("U");
+			if($time > time()) break;
+		} while(true);
+
+		return $report_months;
+	}
 
 	// Object methods
-	public function getCustomer() {
+
+	/**
+	 * @return Customer
+	 * @throws Exception
+	 */
+	public function getCustomer(): ?Customer {
 		return Customer::get($this->customer_id);
 	}
 
-	public function getTests() {
+	/**
+	 * @return Test[]
+	 * @throws Exception
+	 */
+	public function getTests(): array {
+
+		if(!is_null($this->tests)) return $this->tests;
 
 		$nvp = [];
 		$nvp["project_id"] = $this->id;
 		$nvp["status"] = (new Constraint("MORE_THAN"))->setValues(Test::STATUS_CANCELLED);
 
-		return Test::query($nvp);
+		$this->tests = Test::query($nvp);
+
+		return $this->tests;
+	}
+
+	/**
+	 * @return int
+	 * @throws Exception
+	 */
+	public function getTestCount(): int {
+		if(is_null($this->tests)) $this->getTests();
+		return count($this->tests);
 	}
 
-	public function getLocations() {
+	/**
+	 * @return int
+	 * @throws Exception
+	 */
+	public function getPassCount(): int {
+		$count = 0;
+		$tests = $this->getTests();
+		foreach($tests as $test) {
+			if(!$test->isPass()) continue;
+			++$count;
+		}
+		return $count;
+	}
+
+	/**
+	 * @return int
+	 * @throws Exception
+	 */
+	public function getFailCount(): int {
+		$count = 0;
+		$tests = $this->getTests();
+		foreach($tests as $test) {
+			if(!$test->isFail()) continue;
+			++$count;
+		}
+		return $count;
+	}
+
+	/**
+	 * @return int
+	 * @throws Exception
+	 */
+	public function getPendingCount(): int {
+		$count = 0;
+		$tests = $this->getTests();
+		foreach($tests as $test) {
+			if(!$test->isPending()) continue;
+			++$count;
+		}
+		return $count;
+	}
+
+	/**
+	 * @return string
+	 * @throws Exception
+	 */
+	public function getPassRate(): string {
+		$pass_count = $this->getPassCount();
+		$fail_count = $this->getFailCount();
+		$pass_fail_count = $pass_count + $fail_count;
+		if($pass_fail_count == 0) return "0%";
+
+		return (number_format($pass_count / $pass_fail_count, 4) * 100) . "%";
+	}
+
+	/**
+	 * @return Location[]
+	 * @throws Exception
+	 */
+	public function getLocations(): array {
 		$tests = $this->getTests();
 		return Location::query(["id" => array_column($tests, "location_id")]);
 	}
 
-	public function getDisplayAgeRange() {
+	/**
+	 * @return string
+	 */
+	public function getDisplayAgeRange(): string {
 
 		if($this->min_age && $this->max_age) {
 			return $this->min_age . " to " . $this->max_age;
@@ -44,7 +200,26 @@ class Project extends Model {
 
 	}
 
-	public function getCompletedPercentage() {
+	/**
+	 * @return string
+	 */
+	public function getNameHtml(): string {
+
+		if($this->isAnytime()) {
+			return htmlspecialchars($this->name);
+		}
+
+		$icon = $this->getTimeOfDayIcon();
+		$time_of_day = $this->getTimeOfDayText();
+
+		return htmlspecialchars($this->name) . " <i class=\"fa fa-fw fa-{$icon}\" data-toggle=\"tooltip\" title=\"{$time_of_day}\"></i>";
+	}
+
+	/**
+	 * @return float
+	 * @throws Exception
+	 */
+	public function getCompletedPercentage(): float {
 
 		$test_count = $this->test_count;
 
@@ -58,64 +233,111 @@ class Project extends Model {
 
 	}
 
-	public function getTemplate() {
+	/**
+	 * @return Template
+	 * @throws Exception
+	 */
+	public function getTemplate(): ?Template {
 		return Template::get($this->template_id);
 	}
 
-	public function getTemplateOverrides() {
+	/**
+	 * @return array
+	 */
+	public function getTemplateOverrides(): array {
 		$overrides = json_decode($this->template_overrides_json) ?: [];
 		return $overrides;
 	}
 
-	public function getTimeOfDayText() {
+	/**
+	 * @return string
+	 */
+	public function getTimeOfDayText(): string {
 		switch($this->time_of_day) {
-			case "A": return "Any";
-			case "D": return "Day";
-			case "N": return "Night";
+			default:
+			case self::TOD_ANYTIME: return "Any";
+			case self::TOD_DAYTIME: return "Day";
+			case self::TOD_NIGHTTIME: return "Night";
 		}
 	}
 
-	public function getTimeOfDayIcon() {
+	/**
+	 * @return string
+	 */
+	public function getTimeOfDayIcon(): string {
 		switch($this->time_of_day) {
-			case "A": return "adjust";
-			case "D": return "sun";
-			case "N": return "moon";
+			default:
+			case self::TOD_ANYTIME: return "adjust";
+			case self::TOD_DAYTIME: return "sun";
+			case self::TOD_NIGHTTIME: return "moon";
 		}
 	}
 
-	public function getURL() {
+	/**
+	 * @return string
+	 */
+	public function getURL(): string {
 		return "/account/projects/{$this->id}";
 	}
 
-	public function getDirectory() {
+	/**
+	 * @return string
+	 */
+	public function getDirectory(): string {
 		$directory = ROOT_DIR . "/files/projects/" . $this->id;
 		if(!file_exists($directory)) mkdir($directory, 0777, true);
 		return $directory;
 	}
 
-	public function hasInvoicePDF() {
+	/**
+	 * @return bool
+	 */
+	public function hasInvoicePDF(): bool {
 		$directory = $this->getDirectory();
 		return file_exists($directory . "/invoice.pdf");
 	}
 
-	public function isAnytime() {
-		return $this->time_of_day == "A";
+	/**
+	 * @return bool
+	 */
+	public function isAnytime(): bool {
+		return $this->time_of_day == self::TOD_ANYTIME;
 	}
 
-	public function isDaytime() {
-		return $this->time_of_day == "D";
+	/**
+	 * @return bool
+	 */
+	public function isDaytime(): bool {
+		return $this->time_of_day == self::TOD_DAYTIME;
 	}
 
-	public function isNighttime() {
-		return $this->time_of_day == "N";
+	/**
+	 * @return bool
+	 */
+	public function isNighttime(): bool {
+		return $this->time_of_day == self::TOD_NIGHTTIME;
 	}
 
-	public function isPastDeadline() {
+	/**
+	 * @return bool
+	 */
+	public function isPastDeadline(): bool {
 		$deadline_unix = Util::getUnixTimeFromUTC($this->dts_deadline);
 		return time() > $deadline_unix;
 	}
 
-	public function markFinished() {
+	/**
+	 * @return bool
+	 */
+	public function isFinished(): bool {
+		return $this->dts_finished === null;
+	}
+
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function markFinished(): bool {
 
 		if(!Core::$user) throw new Exception("Trying to mark project as finished while not logged in.");
 		if(!Core::$user->isAdmin()) throw new Exception("Trying to mark project as finished with non-admin account.");
@@ -125,13 +347,21 @@ class Project extends Model {
 		return $this->commit();
 	}
 
-	public function markUnfinished() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function markUnfinished(): bool {
 		$this->dts_finished = null;
 		$this->user_id_finished = null;
 		return $this->commit();
 	}
 
-	public function getDisplayReportMonth() {
+	/**
+	 * @return string
+	 * @throws Exception
+	 */
+	public function getDisplayReportMonth(): string {
 		$report_month = "-";
 		if($this->dts_report) {
 			$dt_report = new DateTime($this->dts_report . " UTC");
@@ -140,7 +370,11 @@ class Project extends Model {
 		return $report_month;
 	}
 
-	public function getDataTableRow() {
+	/**
+	 * @return array
+	 * @throws Exception
+	 */
+	public function getDataTableRow(): array {
 
 		$tests = $this->getTests();
 
@@ -151,11 +385,119 @@ class Project extends Model {
 			"testCount" => count($tests),
 			"timeOfDay" => $this->getTimeOfDayText(),
 			"unixStart" => Util::getUnixTimeFromUTC($this->dts_start),
-			"unixEnd" => Util::getUnixTimeFromUTC($this->dts_end),
+			"unixEnd" => Util::getUnixTimeFromUTC($this->dts_deadline),
 
 			"reportMonth" => $this->getDisplayReportMonth(),
 			"unixReport" => $this->dts_report ? Util::getUnixTimeFromUTC($this->dts_report) : 0,
 		];
 	}
 
+	/**
+	 * @return string
+	 * @throws Exception
+	 */
+	public function getTestResultsUrl(): string {
+		$customer = $this->getCustomer();
+		$customer_slug = Util::slugWithId($customer->name, $customer->id);
+		$project_slug = Util::slugWithId($this->name, $this->id);
+		return "/account/test-results/{$customer_slug}/{$project_slug}";
+	}
+
+	/**
+	 * @return Invoice
+	 * @throws Exception
+	 */
+	public function getCustomerInvoice(): Invoice {
+
+		$invoice = new Invoice;
+		$invoice->setReference($this->getInvoiceReference());
+
+		$test_line_items = $this->getTestInvoiceLineItems();
+		$field_line_items = $this->getFieldInvoiceLineItems();
+
+		$invoice->addLineItems($test_line_items);
+		$invoice->addLineItems($field_line_items);
+
+		return $invoice;
+
+	}
+
+	/**
+	 * @return string
+	 * @throws Exception
+	 */
+	private function getInvoiceReference(): string {
+
+		$customer = $this->getCustomer();
+
+		return
+			"P" . str_pad($this->id, 3, "0", STR_PAD_LEFT) .
+			"/C" . str_pad($customer->id, 3, "0", STR_PAD_LEFT);
+	}
+
+	/**
+	 * @return InvoiceLineItem[]
+	 * @throws Exception
+	 */
+	private function getTestInvoiceLineItems(): array {
+
+		/**
+		 * @var InvoiceLineItem[] $items
+		 */
+
+		$template = $this->getTemplate();
+
+		$default_customer_fee = $this->default_customer_fee;
+		$tests = $this->getTests();
+
+		$items = [];
+
+		foreach($tests as $test) {
+
+			$fee = $test->customer_fee ?? $default_customer_fee;
+
+			$key = "fee_{$fee}";
+
+			$item = $items[$key] ?? null;
+
+			if(!$item) {
+				$item = new InvoiceLineItem(__("%s Testing", $template->name));
+				$item->setPrice($fee);
+			}
+
+			$item->incrementQuantity();
+
+			$items[$key] = $item;
+
+		}
+
+		return array_values($items);
+	}
+
+	/**
+	 * @return InvoiceLineItem[]
+	 * @throws Exception
+	 */
+	private function getFieldInvoiceLineItems(): array {
+
+		$template = $this->getTemplate();
+		$invoice_fields = $template->getCustomerInvoiceFields();
+
+		$tests = $this->getTests();
+
+		$items = [];
+
+		foreach($tests as $test) {
+			$values = $test->getValues(true);
+
+			foreach($invoice_fields as $field) {
+				$item = $items[$field->name] ?? (new InvoiceLineItem($field->label));
+				$item->addPrice((float) $values[$field->name] ?? 0);
+				$items[$field->name] = $item;
+			}
+		}
+
+		return $items;
+	}
+
 }

+ 18 - 4
engine/project_location.php

@@ -1,5 +1,12 @@
 <?php
 
+/**
+ * Class ProjectLocation
+ *
+ * @property int $project_id
+ * @property int $location_id
+ */
+
 class ProjectLocation extends Model {
 
 	protected static $table = "project_location";
@@ -7,14 +14,21 @@ class ProjectLocation extends Model {
 	protected static $fillable_fields = ["project_id", "location_id"];
 
 	// Object methods
-	public function getProject() {
+
+	/**
+	 * @return Project|null
+	 * @throws Exception
+	 */
+	public function getProject(): ?Project {
 		return Project::get($this->project_id);
 	}
 
-	public function getLocation() {
+	/**
+	 * @return Location|null
+	 * @throws Exception
+	 */
+	public function getLocation(): ?Location {
 		return Location::get($this->location_id);
 	}
 
 }
-
-?>

+ 18 - 5
engine/session.php

@@ -1,12 +1,24 @@
 <?php
 
+/**
+ * Class Session
+ *
+ * @property int $id
+ * @property string $data
+ * @property string $dts_last_access
+ */
+
 class Session extends Model {
 
 	protected static $table = "session";
 	protected static $id_field = "id";
 	protected static $fillable_fields = ["id", "data", "dts_last_access"];
 
-	public static function start($name="", $timeout=3600) {
+	/**
+	 * @param string $name
+	 * @param int $timeout
+	 */
+	public static function start(string $name = "", int $timeout = 3600) {
 
 		$handler = new SiteSessionHandler();
 		session_set_save_handler($handler, true);
@@ -19,12 +31,13 @@ class Session extends Model {
 		session_start();
 	}
 
-	public static function extend($timeout) {
+	/**
+	 * @param int $timeout
+	 */
+	public static function extend(int $timeout) {
 		$id = session_id();
 		$name = session_name();
-		setcookie($name, $id, time()+$timeout, "/", "");
+		setcookie($name, $id, time() + $timeout, "/", "");
 	}
 
 }
-
-?>

+ 22 - 3
engine/site_session_handler.php

@@ -6,11 +6,22 @@ class SiteSessionHandler implements SessionHandlerInterface {
 		return true;
 	}
 
+	/**
+	 * @param string $id
+	 * @return string
+	 * @throws Exception
+	 */
 	public function read($id) {
 		$session = Session::get($id);
 		return $session ? $session->data : "";
 	}
 
+	/**
+	 * @param string $id
+	 * @param string $data
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function write($id, $data) {
 
 		$session = Session::get($id);
@@ -28,6 +39,11 @@ class SiteSessionHandler implements SessionHandlerInterface {
 		return true;
 	}
 
+	/**
+	 * @param string $id
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function destroy($id) {
 
 		$session = Session::get($id);
@@ -35,15 +51,18 @@ class SiteSessionHandler implements SessionHandlerInterface {
 		return true;
 	}
 
+	/**
+	 * @param int $lifetime
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function gc($lifetime) {
 		$threshold = time() - $lifetime;
 		$date_time = date("Y-m-d H:i:s", $threshold);
 
 		$sql = "DELETE FROM `session` WHERE `dts_last_access` < '$date_time'";
 		$result = db::query($sql);
-		return $result;
+		return !empty($result);
 	}
 
 }
-
-?>

+ 102 - 22
engine/template.php

@@ -1,17 +1,32 @@
-<?php
+<?php /** @noinspection PhpIncludeInspection */
+
+/**
+ * @property int $id
+ * @property int $customer_id
+ * @property string $name
+ * @property string $json
+ * @property string $json_file
+ * @property bool $practice
+ * @property string $folder
+ * @property int $pass_stage
+ */
 
 class Template extends Model {
 
 	protected static $table = "template";
 	protected static $id_field = "id";
-	protected static $fillable_fields = ["customer_id", "name", "json", "json_file", "practice", "pass_stage"];
+	protected static $fillable_fields = ["customer_id", "name", "json", "json_file", "practice", "folder", "pass_stage"];
 
 	private $overrides = [];
 
 	// Object methods
-	public function exportTestsCSV($processing_file, $tests = []) {
 
-		$template = $this;
+	/**
+	 * @param string $processing_file
+	 * @param Test[] $tests
+	 * @throws Exception
+	 */
+	public function exportTestsCSV(string $processing_file, array $tests = []) {
 
 		// Preload
 		Project::load(array_column($tests, "project_id"));
@@ -32,19 +47,17 @@ class Template extends Model {
 		});
 
 		// Output
-		header("Content-Type: text/plain");
-		header("Content-Disposition: attachment; filename=\"export.csv\"");
-		header("Cache-Control: private, max-age=0, must-revalidate");
-		header("Pragma: public");
+		HTTP::setDownloadHeaders("export.csv");
 
 		$handle = fopen("php://output", "w");
-
 		require $processing_file_path;
-
 		fclose($handle);
 	}
 
-	public function getJSON() {
+	/**
+	 * @return string
+	 */
+	public function getJSON(): string {
 		$json_path = ROOT_DIR . "/json/" . $this->json_file;
 
 		if(!empty($this->json_file) && file_exists($json_path)) {
@@ -54,27 +67,45 @@ class Template extends Model {
 		return $this->json;
 	}
 
-	public function getCustomer() {
+	/**
+	 * @return Customer|null
+	 * @throws Exception
+	 */
+	public function getCustomer(): ?Customer {
 		return Customer::get($this->customer_id);
 	}
 
-	public function getProcessingFilePath($file) {
+	/**
+	 * @param $file
+	 * @return string
+	 * @throws Exception
+	 */
+	public function getProcessingFilePath($file): string {
 		if(!$this->folder) throw new Exception("Template processing folder not set.");
 
 		$folder_path = ROOT_DIR . "/template_processing/" . $this->folder;
 		if(!file_exists($folder_path)) throw new Exception("Template processing folder does not exist.");
 
 		$file_path = $folder_path . "/" . $file;
-		if(!file_exists($file_path)) throw new Exception("Template processing file \"$file\" does not exist.");
+		if(!file_exists($file_path)) {
+			$file_path = ROOT_DIR . "/template_processing/_common/{$file}";
+			if(!file_exists($file_path)) throw new Exception("Template processing file \"$file\" does not exist.");
+		}
 
 		return $file_path;
 	}
 
-	public function getURL() {
+	/**
+	 * @return string
+	 */
+	public function getURL(): string {
 		return "/account/templates/" . $this->id;
 	}
 
-	public function getFields() {
+	/**
+	 * @return array
+	 */
+	public function getFields(): array {
 		$fields = [];
 
 		$json = json_decode($this->getJSON());
@@ -90,25 +121,56 @@ class Template extends Model {
 		return $fields;
 	}
 
-	public function getTesterInvoiceFields() {
+	/**
+	 * @return array
+	 * @throws Exception
+	 */
+	public function getTesterInvoiceFields(): array {
 		$json = json_decode($this->getJSON());
 		if(!$json) throw new Exception("Failed to decode template JSON.");
 
 		return $json->testerInvoiceFields ?? [];
 	}
 
-	public function getCustomerInvoiceFields() {
+	/**
+	 * @return array
+	 * @throws Exception
+	 */
+	public function getCustomerInvoiceFields(): array {
 		$json = json_decode($this->getJSON());
 		if(!$json) throw new Exception("Failed to decode template JSON.");
 
 		return $json->customerInvoiceFields ?? [];
 	}
 
-	public function setOverrides($overrides) {
+	/**
+	 * @param array $values
+	 * @return float
+	 * @throws Exception
+	 */
+	public function getTesterInvoiceCosts(array $values = []): float {
+		$costs = 0;
+
+		$invoice_fields = $this->getTesterInvoiceFields();
+		foreach($invoice_fields as $field) {
+			$costs += (float) $values[$field->name] ?? 0;
+		}
+
+		return $costs;
+	}
+
+	/**
+	 * @param array $overrides
+	 */
+	public function setOverrides(array $overrides) {
 		$this->overrides = $overrides;
 	}
 
-	public function applyOverridesToField($field) {
+	/**
+	 * @param object $field
+	 * @return object
+	 */
+	public function applyOverridesToField(object $field): object {
 		foreach($this->overrides as $override) {
 			if(empty($field->name)) continue;
 			if($override->field == $field->name) {
@@ -122,6 +184,9 @@ class Template extends Model {
 		return $field;
 	}
 
+	/**
+	 * @throws Exception
+	 */
 	public function renderBeforeTestForm() {
 
 		$json = json_decode($this->getJSON());
@@ -154,6 +219,9 @@ class Template extends Model {
 		<?php
 	}
 
+	/**
+	 * @throws Exception
+	 */
 	public function renderDuringTestForm() {
 
 		$json = json_decode($this->getJSON());
@@ -175,6 +243,8 @@ class Template extends Model {
 				}
 				?>
 
+                <hr />
+
 				<h3>Entry/Exit Times</h3>
 
 				<p>Please confirm your entry and exit times below. Please try to be as accurate as possible.</p>
@@ -293,8 +363,18 @@ class Template extends Model {
 		<?php
 	}
 
+	/**
+	 * @return int
+	 */
+	public function getPassStage(): int {
+		return (int) $this->pass_stage;
+	}
 
+	/**
+	 * @return bool
+	 */
+	public function hasPassFail(): bool {
+		return !is_null($this->pass_stage);
+	}
 
 }
-
-?>

+ 274 - 40
engine/test.php

@@ -1,4 +1,45 @@
-<?php
+<?php /** @noinspection HtmlDeprecatedTag */
+/** @noinspection HtmlDeprecatedAttribute */
+
+use Mpdf\Mpdf;
+
+/**
+ * @property int $id
+ * @property int $project_id
+ * @property int $location_id
+ * @property int $tester_id
+ * @property int $status
+ * @property int $status_tester_invoice
+ * @property float $customer_fee
+ * @property float $test_fee
+ * @property string $test_time
+ * @property float $test_travel_cost
+ * @property string $shop_left
+ * @property string $shop_right
+ * @property string $attire
+ * @property int $challenge_stage
+ * @property string $challenge_description
+ * @property string $challenger_name
+ * @property string $challenger_description
+ * @property string $challenger_gender
+ * @property string $challenger_eye_contact
+ * @property string $additional_notes
+ * @property string $dts_due
+ * @property string $dts_start
+ * @property string $dts_end
+ * @property string $dts_tester_invoice_generated
+ * @property string $dts_tester_invoice_paid
+ * @property int $verifier_id
+ * @property string $verifier_notes
+ * @property bool $pass
+ * @property bool $retest
+ * @property string $dts_created
+ * @property string $dts_updated
+ * @property string $dts_assigned
+ * @property string $dts_verified
+ *
+ * @method Test get(int $id)
+ */
 
 class Test extends Model {
 
@@ -52,7 +93,12 @@ class Test extends Model {
 	const TEST_TIME_NIGHT = 3;
 
 	// Static methods
-	public static function getStatusTesterInvoiceText($status) {
+
+	/**
+	 * @param int $status
+	 * @return string
+	 */
+	public static function getStatusTesterInvoiceText(int $status): string {
 		switch($status) {
 			case Test::STATUS_TESTER_INVOICE_NONE:
 				return __("No Invoice Generated");
@@ -64,7 +110,11 @@ class Test extends Model {
 		return __("Unknown");
 	}
 
-	public static function getStatusTesterInvoiceClass($status) {
+	/**
+	 * @param int $status
+	 * @return string
+	 */
+	public static function getStatusTesterInvoiceClass(int $status): string {
 		switch($status) {
 			case Test::STATUS_TESTER_INVOICE_NONE:
 				return "secondary";
@@ -76,8 +126,38 @@ class Test extends Model {
 		return "";
 	}
 
+	/**
+	 * @param string $processing_file
+	 * @param array $tests
+	 * @throws Exception
+	 */
+	public static function exportCSV(string $processing_file, array $tests = []): void {
+
+		// Preload
+		Project::load(array_column($tests, "project_id"));
+		Location::load(array_column($tests, "location_id"));
+		User::load(array_column($tests, "tester_id"));
+
+		// Get processing file
+		$processing_file_path = ROOT_DIR . "/export_processing/{$processing_file}";
+		if(!file_exists($processing_file_path)) throw new Exception("Processing file not found.");
+
+		// Output
+		HTTP::setDownloadHeaders("export.csv");
+
+		$handle = fopen("php://output", "w");
+		require $processing_file_path;
+		fclose($handle);
+	}
+
 	// Object methods
-	public function sendAssignEmail($message) {
+
+	/**
+	 * @param string $message
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function sendAssignEmail(string $message): bool {
 
 		$tester = $this->getTester();
 		$location = $this->getLocation();
@@ -138,9 +218,15 @@ class Test extends Model {
 		$mail->addAddress($tester->email, $tester->getDisplayName());
 		$mail->setSubject(__("You have been allocated a test"));
 		$mail->send();
+
+		return true;
 	}
 
-	public function sendClaimedEmail() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function sendClaimedEmail(): bool {
 
 		$tester = $this->getTester();
 		$location = $this->getLocation();
@@ -170,10 +256,8 @@ class Test extends Model {
 			'<b>', '</b>',
 			'<b>', '</b>'
 		));
-		$builder->addParagraph(sprintf(__("If you have any questions please send them to %s or call %s on %s."),
-			"<a href=\"mailto:tests@check-policy.com\">tests@check-policy.com</a>",
-			"<b>$admin_first_name</b>",
-			"<b>$admin_phone</b>"
+		$builder->addParagraph(sprintf(__("If you have any questions please send them to %s."),
+			"<a href=\"mailto:tests@check-policy.com\">tests@check-policy.com</a>"
 		));
 		$builder->addParagraph(__("If you are unable to submit the results via the web-based app please contact us and we can send you an offline form to complete."));
 		$content = $builder->build();
@@ -185,9 +269,15 @@ class Test extends Model {
 		$mail->addAddress($tester->email, $tester->getDisplayName());
 		$mail->setSubject(__("You have claimed a test"));
 		$mail->send();
+
+		return true;
 	}
 
-	public function sendDeclineEmail() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function sendDeclineEmail(): bool {
 
 		$tester = $this->getTester();
 		$location = $this->getLocation();
@@ -219,9 +309,16 @@ class Test extends Model {
 		$mail->addAddress(EMAIL_CONTACT, APP_NAME . " Contact");
 		$mail->setSubject("Test declined: $project->name / $location->name");
 		$mail->send();
+
+		return true;
 	}
 
-	public function sendResultEmail($to_address) {
+	/**
+	 * @param string $to_address
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function sendResultEmail(string $to_address): bool {
 
 		$location = $this->getLocation();
 		$project = $this->getProject();
@@ -281,9 +378,15 @@ class Test extends Model {
 		$mail->setSubject($subject);
 
 		$mail->send();
+
+		return true;
 	}
 
-	public function decline() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function decline(): bool {
 		$this->sendDeclineEmail();
 
 		$this->status = Test::STATUS_UNASSIGNED;
@@ -294,16 +397,25 @@ class Test extends Model {
 		return $this->commit();
 	}
 
-	public function getChallengeStageText() {
+	/**
+	 * @return string
+	 */
+	public function getChallengeStageText(): string {
 		if(is_null($this->challenge_stage)) return "";
 		return Test::STAGES[$this->challenge_stage];
 	}
 
-	public function getStatusText() {
+	/**
+	 * @return string
+	 */
+	public function getStatusText(): string {
 		return Test::STATUSES[$this->status];
 	}
 
-	public function getStatusClass() {
+	/**
+	 * @return string
+	 */
+	public function getStatusClass(): string {
 		switch($this->status) {
 			case Test::STATUS_CANCELLED:
 				return "secondary";
@@ -318,25 +430,47 @@ class Test extends Model {
 			case Test::STATUS_COMPLETED:
 				return "success";
 		}
+		return "";
 	}
 
-	public function getProject() {
+	/**
+	 * @return Project|null
+	 * @throws Exception
+	 */
+	public function getProject(): ?Project {
 		return Project::get($this->project_id);
 	}
 
-	public function getLocation() {
+	/**
+	 * @return Location
+	 * @throws Exception
+	 */
+	public function getLocation(): ?Location {
 		return Location::get($this->location_id);
 	}
 
-	public function getTester() {
+	/**
+	 * @return User
+	 * @throws Exception
+	 */
+	public function getTester(): ?User {
 		return User::get($this->tester_id);
 	}
 
-	public function getVerifier() {
+	/**
+	 * @return User
+	 * @throws Exception
+	 */
+	public function getVerifier(): ?User {
 		return User::get($this->verifier_id);
 	}
 
-	public function getValues($as_assoc_array = false) {
+	/**
+	 * @param bool $as_assoc_array
+	 * @return array
+	 * @throws Exception
+	 */
+	public function getValues(bool $as_assoc_array = false): array {
 		$rows = TestValue::query(["test_id" => $this->id]);
 
 		if($as_assoc_array) {
@@ -351,22 +485,28 @@ class Test extends Model {
 		return $values;
 	}
 
-	public function getDirectory() {
+	/**
+	 * @return string
+	 */
+	public function getDirectory(): string {
 		$directory = ROOT_DIR . "/files/tests/" . $this->id;
-		if($this->project_id == "PRACTICE") {
-			$directory = ROOT_DIR . "/files/users/$this->tester_id/practice_tests/$this->template_id";
-		}
 		if(!file_exists($directory)) mkdir($directory, 0777, true);
 		return $directory;
 	}
 
+	/**
+	 * @return bool|float|int
+	 */
 	public function getDuration() {
 		if(is_null($this->dts_end)) return false;
 		$seconds = Util::getDurationFromDTS($this->dts_start, $this->dts_end);
 		return $seconds;
 	}
 
-	public function getDisplayDuration() {
+	/**
+	 * @return string
+	 */
+	public function getDisplayDuration(): string {
 		$secs = $this->getDuration();
 		$mins = floor($secs / 60);
 		$secs = $secs % 60;
@@ -374,29 +514,44 @@ class Test extends Model {
 		return "$mins min. $secs sec.";
 	}
 
-	public function getPassClass() {
+	/**
+	 * @return string Bootstrap class name
+	 */
+	public function getPassClass(): string {
 		if(is_null($this->pass)) return "secondary";
 		return $this->pass ? "success" : "danger";
 	}
 
-	public function getPassIcon() {
+	/**
+	 * @return string FA icon name without prefix
+	 */
+	public function getPassIcon(): string {
 		if(is_null($this->pass)) return "clock";
 		return $this->pass ? "check-circle" : "times-circle";
 	}
 
-	public function getPassText() {
-		if(is_null($this->pass)) return "Pending";
+	/**
+	 * @return string Pending, Pass or Fail
+	 */
+	public function getPassText(): string {
+		if(is_null($this->pass)) return __("Pending");
 		return $this->pass ? __("Pass") : __("Fail");
 	}
 
-	public function getMPDF() {
+	public function getMPDF(): Mpdf {
+		/** @var Mpdf $mpdf */
 		$id = $this->id;
 		$output = false;
 		require ROOT_DIR . "/controllers/test_pdf.php";
 		return $mpdf;
 	}
 
-	public function assignTester($tester) {
+	/**
+	 * @param User $tester
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function assignTester(User $tester): bool {
 		$this->tester_id = $tester->id;
 		$this->dts_assigned = Util::getDateTime();
 		$success = $this->commit();
@@ -407,7 +562,11 @@ class Test extends Model {
 
 	}
 
-	public function getPreviousTest() {
+	/**
+	 * @return Test|null
+	 * @throws Exception
+	 */
+	public function getPreviousTest(): ?Test {
 
 		$nvp = [
 			"dts_start" => (new Constraint("LESS_THAN"))->setValues($this->dts_start),
@@ -420,30 +579,87 @@ class Test extends Model {
 			"order" => "desc",
 		]);
 
-		return $tests ? $tests[0] : false;
+		return $tests ? $tests[0] : null;
 
 	}
 
-	public function unassignTester() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function unassignTester(): bool {
 		$this->status = Test::STATUS_UNASSIGNED;
 		$this->tester_id = null;
 		$this->dts_due = null;
 		$this->dts_assigned = null;
-		$success = $this->commit();
+		return $this->commit();
+	}
 
-		return $success;
+	/**
+	 * @return bool
+	 */
+	public function isPass(): bool {
+		if(is_null($this->pass)) return false;
+		return !empty($this->pass);
+	}
+
+	/**
+	 * @return bool
+	 */
+	public function isPending(): bool {
+		return is_null($this->pass);
+	}
+
+	/**
+	 * @return bool
+	 */
+	public function isFail(): bool {
+		if(is_null($this->pass)) return false;
+		return empty($this->pass);
+	}
+
+	/**
+	 * @return bool
+	 */
+	public function isCompleted() {
+		return $this->status == Test::STATUS_COMPLETED;
 	}
 
+	/**
+	 * @return bool
+	 */
 	public function isPendingVerification() {
 		return $this->status == Test::STATUS_PENDING_VERIFICATION;
 	}
 
-	public function hasTesterInvoicePDF() {
+	/**
+	 * @return bool
+	 */
+	public function hasPDF(): bool {
+		$directory = $this->getDirectory();
+		return file_exists($directory . "/pdf.pdf");
+	}
+
+	/**
+	 * @return string
+	 */
+	public function getPDFUrl(): string {
+		return "/account/tests/{$this->id}/files/pdf";
+	}
+
+	/**
+	 * @return bool
+	 */
+	public function hasTesterInvoicePDF(): bool {
 		$directory = $this->getDirectory();
 		return file_exists($directory . "/tester_invoice.pdf");
 	}
 
-	public function markTesterInvoicePaid() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function markTesterInvoicePaid(): bool {
 
 		if($this->status_tester_invoice == Test::STATUS_TESTER_INVOICE_PENDING) {
 			$this->status_tester_invoice = Test::STATUS_TESTER_INVOICE_PAID;
@@ -454,7 +670,11 @@ class Test extends Model {
 		return false;
 	}
 
-	public function rejectTesterInvoice() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function rejectTesterInvoice(): bool {
 		if($this->status_tester_invoice == Test::STATUS_TESTER_INVOICE_PENDING) {
 			$this->status_tester_invoice = Test::STATUS_TESTER_INVOICE_NONE;
 			$this->dts_tester_invoice_generated = null;
@@ -468,5 +688,19 @@ class Test extends Model {
 		return false;
 	}
 
+	/**
+	 * @return string
+	 * @throws Exception
+	 */
+	public function getTesterInvoiceReference(): string {
+
+		$location = $this->getLocation();
+		$tester = $this->getTester();
+
+		return
+		"T" . str_pad($this->id, 3, "0", STR_PAD_LEFT) .
+		"/L" . str_pad($location->id, 3, "0", STR_PAD_LEFT) .
+		"/U" . str_pad($tester->id, 3, "0", STR_PAD_LEFT);
+	}
+
 }
-?>

+ 5 - 1
engine/test_pdf.php

@@ -2,7 +2,11 @@
 
 class TestPDF {
 
-	public static function getValueHtml($value) {
+	/**
+	 * @param string $value
+	 * @return string
+	 */
+	public static function getValueHtml(string $value): string {
 		if(empty($value)) {
 			return "<span class=\"text-muted\">N/A</span>";
 		}

+ 0 - 7
engine/test_value.php

@@ -6,11 +6,4 @@ class TestValue extends Model {
 	protected static $id_field = ["test_id", "name"];
 	protected static $fillable_fields = ["test_id", "name", "value"];
 
-	protected static $field_map = [
-	];
-
-	// Object methods
-
 }
-
-?>

+ 160 - 28
engine/user.php

@@ -1,5 +1,43 @@
 <?php
 
+/**
+ * Class User
+ *
+ * @property int $id
+ * @property string $email
+ * @property int $old_id
+ * @property int $referrer_id
+ * @property string $password
+ * @property bool $activated
+ * @property int $level
+ * @property int $score
+ * @property string $title
+ * @property string $first_name
+ * @property string $last_name
+ * @property string $gender
+ * @property string $date_of_birth
+ * @property string $locale
+ * @property bool $reported
+ * @property string $reported_comment
+ * @property bool $can_claim
+ * @property string $phone
+ * @property string $verify_token
+ * @property string $reset_token
+ * @property bool $terms_accepted
+ * @property bool $newsletter_consent
+ * @property int $preferred_payment_method
+ * @property string $bank_name
+ * @property string $bank_sort_code
+ * @property string $bank_account_number
+ * @property string $paypal_email
+ * @property string $dts_registered
+ * @property string $dts_last_seen
+ * @property string $dts_verified
+ * @property string $dts_deleted
+ * @property int $verifier_id
+ * @property string $verifier_notes
+ */
+
 class User extends Model {
 
 	protected static $table = "user";
@@ -40,7 +78,11 @@ class User extends Model {
 	];
 
 	// Static methods
-	public static function titles() {
+
+	/**
+	 * @return array
+	 */
+	public static function titles(): array {
 		return [
 			"Miss" => MISS,
 			"Mr" => MR,
@@ -49,7 +91,10 @@ class User extends Model {
 		];
 	}
 
-	public static function genders() {
+	/**
+	 * @return array
+	 */
+	public static function genders(): array {
 		return [
 			"Female" => FEMALE,
 			"Male" => MALE,
@@ -57,7 +102,11 @@ class User extends Model {
 		];
 	}
 
-	public static function validatePassword($password) {
+	/**
+	 * @param string $password
+	 * @return bool
+	 */
+	public static function validatePassword(string $password): bool {
 		$lowercase = preg_match("/[a-z]/", $password);
 		$uppercase = preg_match("/[A-Z]/", $password);
 		$number = preg_match("/[0-9]/", $password);
@@ -68,7 +117,11 @@ class User extends Model {
 	}
 
 	// Object methods
-	public function hasValidPaymentMethod() {
+
+	/**
+	 * @return bool
+	 */
+	public function hasValidPaymentMethod(): bool {
 		switch($this->preferred_payment_method) {
 			case User::PAYMENT_METHOD_BANK_TRANSFER: {
 				if(empty($this->bank_name)) return false;
@@ -84,6 +137,10 @@ class User extends Model {
 		return true;
 	}
 
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function sendActivationEmail() {
 
 		$this->verify_token = bin2hex(random_bytes(16));
@@ -114,6 +171,10 @@ class User extends Model {
 		return true;
 	}
 
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function sendWelcomeEmail() {
 
 		// Content
@@ -140,6 +201,10 @@ class User extends Model {
 
 	}
 
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function sendIDPassEmail() {
 
 		// Content
@@ -175,6 +240,11 @@ class User extends Model {
 
 	}
 
+	/**
+	 * @param string $reason
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function sendIDFailEmail($reason = "No reason given.") {
 
 		// Content
@@ -202,6 +272,10 @@ class User extends Model {
 		return true;
 	}
 
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function sendPasswordResetEmail() {
 
 		$this->reset_token = bin2hex(random_bytes(16));
@@ -235,12 +309,19 @@ class User extends Model {
 
 	}
 
+	/**
+	 * @return bool
+	 */
 	public function canAdmin() {
 		return $this->level >= User::LEVEL_ADMIN;
 	}
 
-	public function getReferrer() {
-		return is_null($this->referrer_id) ? false : User::get($this->referrer_id);
+	/**
+	 * @return User|null
+	 * @throws Exception
+	 */
+	public function getReferrer(): ?User {
+		return is_null($this->referrer_id) ? null : User::get($this->referrer_id);
 	}
 
 	public function getDirectory() {
@@ -295,6 +376,10 @@ class User extends Model {
 		return "Unspecified";
 	}
 
+	/**
+	 * @return int|string
+	 * @throws Exception
+	 */
 	public function getAge() {
 
 		if(is_null($this->date_of_birth)) return __("N/A");
@@ -312,33 +397,41 @@ class User extends Model {
 		return implode(" ", $parts);
 	}
 
-	public function hasPermission($object) {
+	/**
+	 * @param $object
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function hasPermission($object): bool {
 
-		if($this->level == User::LEVEL_SUPERADMIN) return true;
-		if($this->level == User::LEVEL_ADMIN) return true;
+		if($this->isAdmin()) return true;
 
 		$customers = $this->getCustomers();
 		$customer_ids = array_column($customers, "id");
 
-		if(is_a($object, "Customer")) {
+		if($object instanceof Customer) {
 			return in_array($object->id, $customer_ids);
 		}
 
-		if(is_a($object, "Location")) {
+		if($object instanceof Location) {
 			return in_array($object->customer_id, $customer_ids);
 		}
 
-		if(is_a($object, "Project")) {
+		if($object instanceof Project) {
 			return in_array($object->customer_id, $customer_ids);
 		}
 
-		if(is_a($object, "Template")) {
+		if($object instanceof Template) {
 			return in_array($object->customer_id, $customer_ids);
 		}
 
 		return false;
 	}
 
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function deactivate() {
 		// Decline all pending tests
 		$pending_tests = $this->getPendingTests();
@@ -351,7 +444,11 @@ class User extends Model {
 		return $this->commit();
 	}
 
-	public function softDelete() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function softDelete(): bool {
 
 		// Delete identification documents
 		$this->deleteIDFiles();
@@ -379,12 +476,14 @@ class User extends Model {
 		// Set deleted time
 		$this->dts_deleted = Util::getDateTime();
 
-		$success = $this->commit();
-
-		return true;
+		return $this->commit();
 	}
 
-	public function deleteIDFiles() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function deleteIDFiles(): bool {
 
 		$files = UserFile::query([
 			"user_id" => $this->id,
@@ -401,8 +500,11 @@ class User extends Model {
 		return true;
 	}
 
-
-	public function deleteAddresses() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function deleteAddresses(): bool {
 		$addresses = $this->getAddresses();
 		foreach($addresses as $address) {
 			$address->delete();
@@ -411,7 +513,11 @@ class User extends Model {
 		return true;
 	}
 
-	public function getAddresses() {
+	/**
+	 * @return UserAddress[]
+	 * @throws Exception
+	 */
+	public function getAddresses(): array {
 
 		$addresses = UserAddress::query([
 			"user_id" => $this->id,
@@ -422,7 +528,11 @@ class User extends Model {
 		return $addresses;
 	}
 
-	public function getInvoiceAddress() {
+	/**
+	 * @return UserAddress|null
+	 * @throws Exception
+	 */
+	public function getInvoiceAddress(): ?UserAddress {
 		$addresses = UserAddress::query([
 			"user_id" => $this->id,
 		]);
@@ -434,9 +544,13 @@ class User extends Model {
 		// If only one address in account, just return it
 		if(count($addresses) == 1) return array_shift($addresses);
 
-		return false;
+		return null;
 	}
 
+	/**
+	 * @return Customer[]
+	 * @throws Exception
+	 */
 	public function getCustomers() {
 
 		if($this->level >= User::LEVEL_ADMIN) {
@@ -453,7 +567,11 @@ class User extends Model {
 		return [];
 	}
 
-	public function getPendingTests() {
+	/**
+	 * @return Test[]
+	 * @throws Exception
+	 */
+	public function getPendingTests(): array {
 		return Test::query([
 			"tester_id" => $this->id,
 			"status" => [Test::STATUS_ASSIGNED, Test::STATUS_CONFIRMED, Test::STATUS_STARTED, Test::STATUS_PENDING_VERIFICATION],
@@ -463,7 +581,11 @@ class User extends Model {
 		]);
 	}
 
-	public function getCompletedTests() {
+	/**
+	 * @return Test[]
+	 * @throws Exception
+	 */
+	public function getCompletedTests(): array {
 		return Test::query([
 			"tester_id" => $this->id,
 			"status" => [Test::STATUS_CANCELLED, Test::STATUS_COMPLETED],
@@ -473,17 +595,27 @@ class User extends Model {
 		]);
 	}
 
-	public function getReferrals() {
+	/**
+	 * @return User[]
+	 * @throws Exception
+	 */
+	public function getReferrals(): array {
 		return User::query([
 			"referrer_id" => $this->id
 		]);
 	}
 
-	public function getPreferredPaymentMethodText() {
+	/**
+	 * @return string
+	 */
+	public function getPreferredPaymentMethodText(): string {
 		return User::PAYMENT_METHODS[$this->preferred_payment_method];
 	}
 
-	public function getURL() {
+	/**
+	 * @return string
+	 */
+	public function getURL(): string {
 		return "/account/users/{$this->id}";
 	}
 

+ 33 - 8
engine/user_address.php

@@ -1,24 +1,48 @@
 <?php
 
+/**
+ * Class UserAddress
+ *
+ * @property int $id
+ * @property int $user_id
+ * @property string $name
+ * @property string $address_1
+ * @property string $address_2
+ * @property string $city
+ * @property string $county
+ * @property string $postal_code
+ * @property string $state
+ * @property string $country
+ * @property double $latitude
+ * @property double $longitude
+ * @property float $max_radius_miles
+ * @property bool $invoice
+ */
+
 class UserAddress extends Model {
 
 	protected static $table = "user_address";
 	protected static $id_field = "id";
 	protected static $fillable_fields = ["user_id", "name", "address_1", "address_2", "city", "county", "postal_code", "state", "country", "latitude", "longitude", "max_radius_miles", "invoice"];
 
-	protected static $field_map = [
-	];
-
 	const RADIUSES = [
 		"0.25", "0.50", "1.00", "1.50", "2.00", "2.50", "3.00", "4.00", "5.00", "7.50", "10.00", "12.50", "15.00", "20.00", "25.00",
 	];
 
 	// Object methods
-	public function getUser() {
+
+	/**
+	 * @return User|null
+	 * @throws Exception
+	 */
+	public function getUser(): ?User {
 		return User::get($this->user_id);
 	}
 
-	public function getDisplayAddress() {
+	/**
+	 * @return string
+	 */
+	public function getDisplayAddress(): string {
 		$parts = [];
 		$fields = ["address_1", "address_2", "city", "county", "postal_code", "state", "country"];
 
@@ -29,10 +53,11 @@ class UserAddress extends Model {
 		return implode(", ", array_filter($parts));
 	}
 
-	public function getGeolocation() {
+	/**
+	 * @return array
+	 */
+	public function getGeolocation(): array {
 		return [$this->latitude, $this->longitude];
 	}
 
 }
-
-?>

+ 18 - 4
engine/user_customer.php

@@ -1,5 +1,12 @@
 <?php
 
+/**
+ * Class UserCustomer
+ *
+ * @property int $user_id
+ * @property int $customer_id
+ */
+
 class UserCustomer extends Model {
 
 	protected static $table = "user_customer";
@@ -7,14 +14,21 @@ class UserCustomer extends Model {
 	protected static $fillable_fields = ["user_id", "customer_id"];
 
 	// Object methods
-	public function getUser() {
+
+	/**
+	 * @return User|null
+	 * @throws Exception
+	 */
+	public function getUser(): ?User {
 		return User::get($this->user_id);
 	}
 
-	public function getCustomer() {
+	/**
+	 * @return Customer|null
+	 * @throws Exception
+	 */
+	public function getCustomer(): ?Customer {
 		return Customer::get($this->customer_id);
 	}
 
 }
-
-?>

+ 9 - 4
engine/user_file.php

@@ -1,5 +1,14 @@
 <?php
 
+/**
+ * Class UserFile
+ *
+ * @property int $id
+ * @property int $user_id
+ * @property int $type
+ * @property string $dts_uploaded
+ */
+
 class UserFile extends Model {
 
 	protected static $table = "user_file";
@@ -9,8 +18,4 @@ class UserFile extends Model {
 	const TYPE_ID = 1;
 	const TYPE_PHOTO = 2;
 
-	// Object methods
-
 }
-
-?>

+ 123 - 161
engine/util.php

@@ -1,7 +1,12 @@
 <?php
+
 class Util {
 
-	public static function getGenderText($gender) {
+	/**
+	 * @param string $gender
+	 * @return string
+	 */
+	public static function getGenderText(string $gender): string {
 		switch($gender) {
 			case "M": return MALE;
 			case "F": return FEMALE;
@@ -9,7 +14,11 @@ class Util {
 		}
 	}
 
-	public static function getBooleanText($boolean) {
+	/**
+	 * @param string $boolean
+	 * @return string
+	 */
+	public static function getBooleanText(string $boolean): string {
 		switch($boolean) {
 			case "Y": return YES;
 			case "N": return NO;
@@ -17,12 +26,23 @@ class Util {
 		}
 	}
 
-	public static function convertUTF8($string, $target_encoding = "CP1252") {
+	/**
+	 * @param string $string
+	 * @param string $target_encoding
+	 * @return string
+	 */
+	public static function convertUTF8(string $string, string $target_encoding = "CP1252"): string {
 		return mb_convert_encoding($string, $target_encoding, "UTF-8");
 	}
 
-	public static function getPaginationObject($array, $page_size = 25) {
-		$item_count = count($array);
+	/**
+	 * @param array $items
+	 * @param int $page_size
+	 * @return object
+	 * @throws Exception
+	 */
+	public static function getPaginationObject(array $items, int $page_size = 25) {
+		$item_count = count($items);
 
 		$page = http::value("page");
 		if($page < 1) $page = 1;
@@ -56,12 +76,22 @@ class Util {
 		];
 	}
 
-	public static function getItemDirectory($folder, $id) {
+	/**
+	 * @param string $folder
+	 * @param int $id
+	 * @return string
+	 */
+	public static function getItemDirectory(string $folder, int $id): string {
 		$shard = str_pad($id % 1000, 3, "0", STR_PAD_LEFT);
 		return ROOT_DIR . "/files/" . $folder . "/" . $shard . "/" . $id;
 	}
 
-	public static function createItemDirectory($folder, $id) {
+	/**
+	 * @param string $folder
+	 * @param int $id
+	 * @return string
+	 */
+	public static function createItemDirectory(string $folder, int $id): string {
 
 		$directory = Util::getItemDirectory($folder, $id);
 
@@ -72,15 +102,32 @@ class Util {
 		return $directory;
 	}
 
-	public static function slug($string) {
+	/**
+	 * @param string $string
+	 * @return string
+	 */
+	public static function slug(string $string): string {
 		$slug = strtolower($string);
 		$slug = preg_replace("/[^0-9a-z]/i", "-", $slug); // Replace anything not 0-9 a-z with dash
-		$slug = preg_replace("/\-+/", "-", $slug); // Replace consequential dashes with dash
+		$slug = preg_replace("/-+/", "-", $slug); // Replace consequential dashes with dash
 		$slug = trim($slug, "-");
 		return $slug;
 	}
 
-	public static function getDisplayFileSize($size) {
+	/**
+	 * @param string $string
+	 * @param int $id
+	 * @return string
+	 */
+	public static function slugWithId(string $string, int $id): string {
+		return Util::slug($string) . "-" . $id;
+	}
+
+	/**
+	 * @param int $size
+	 * @return string
+	 */
+	public static function getDisplayFileSize(int $size): string {
 		if($size < pow(2, 10)) return number_format($size) . " bytes";
 		if($size < pow(2, 20)) return number_format($size / pow(2, 10), 2) . " KB";
 		if($size < pow(2, 30)) return number_format($size / pow(2, 20), 2) . " MB";
@@ -88,7 +135,12 @@ class Util {
 		return number_format($size / pow(2, 40), 2) . " TB";
 	}
 
-	public static function timeDifference($unix_time, $options = []) {
+	/**
+	 * @param int $unix_time
+	 * @param array $options
+	 * @return string
+	 */
+	public static function timeDifference(int $unix_time, $options = []): string {
 
 		$plain = $options["plain"] ?? false;
 
@@ -141,7 +193,11 @@ class Util {
 
 	}
 
-	public static function getTimeZones() {
+	/**
+	 * @return array
+	 * @throws Exception
+	 */
+	public static function getTimeZones(): array {
 
 		// Taken and modified from: https://stackoverflow.com/a/17355238
 
@@ -202,25 +258,46 @@ class Util {
 		return $time_zone_list;
 	}
 
-	public static function getDate($time = false) {
+	/**
+	 * @param bool $time
+	 * @return string
+	 */
+	public static function getDate($time = false): string {
 		if(!$time) $time = time();
 		return gmdate("Y-m-d", $time);
 	}
 
-	public static function getUTCDateTime($time = false) {
+	/**
+	 * @param bool $time
+	 * @return string
+	 */
+	public static function getUTCDateTime($time = false): string {
 		return Util::getDateTime($time);
 	}
 
-	public static function getDateTime($time = false) {
+	/**
+	 * @param bool $time
+	 * @return string
+	 */
+	public static function getDateTime($time = false): string {
 		if(!$time) $time = time();
 		return gmdate("Y-m-d H:i:s", $time);
 	}
 
-	public static function getUnixTimeFromUTC($dts) {
+	/**
+	 * @param string $dts
+	 * @return false|int
+	 */
+	public static function getUnixTimeFromUTC(string $dts) {
 		return strtotime($dts . " UTC");
 	}
 
-	public static function getDurationFromDTS($dts1, $dts2) {
+	/**
+	 * @param string $dts1
+	 * @param string $dts2
+	 * @return float|int
+	 */
+	public static function getDurationFromDTS(string $dts1, string $dts2) {
 		$tz = date_default_timezone_get();
 		date_default_timezone_set("UTC");
 
@@ -232,7 +309,11 @@ class Util {
 		return abs($t2 - $t1);
 	}
 
-	public static function getDisplayDateTime($time = false) {
+	/**
+	 * @param int|bool $time
+	 * @return string
+	 */
+	public static function getDisplayDateTime($time = false): string {
 		if($time === false) $time = time();
 
 		$current_year = date("Y");
@@ -243,7 +324,11 @@ class Util {
 		return date($format, $time);
 	}
 
-	public static function getDisplayDate($time = false) {
+	/**
+	 * @param int|bool $time
+	 * @return string
+	 */
+	public static function getDisplayDate($time = false): string {
 		if($time === false) $time = time();
 
 		$current_year = date("Y");
@@ -254,17 +339,27 @@ class Util {
 		return date($format, $time);
 	}
 
-	public static function getDisplayDateTimeFromUTC($dts) {
+	/**
+	 * @param string $dts
+	 * @return string
+	 */
+	public static function getDisplayDateTimeFromUTC(string $dts): string {
 		$unix = Util::getUnixTimeFromUTC($dts);
 		return Util::getDisplayDateTime($unix);
 	}
 
-	public static function sortObjectArray($array, $field, $compare_function = "") {
+	/**
+	 * @param array $array
+	 * @param string $field
+	 * @param string $compare_function
+	 * @return array
+	 */
+	public static function sortObjectArray(array $array, string $field, string $compare_function = ""): array {
 
 		usort($array, function($a, $b) use ($compare_function, $field) {
 
 			switch($compare_function) {
-				case "":
+				default:
 					if($a->$field == $b->$field) return 0;
 					return ($a->$field < $b->$field) ? -1 : 1;
 				case "strnatcasecmp":
@@ -275,7 +370,11 @@ class Util {
 		return $array;
 	}
 
-	public static function arrayFlipByID($input = []) {
+	/**
+	 * @param array $input
+	 * @return array
+	 */
+	public static function arrayFlipByID(array $input = []): array {
 		$output = [];
 
 		foreach($input as $object) {
@@ -285,141 +384,4 @@ class Util {
 		return $output;
 	}
 
-	public static function formatText($string, $options = []) {
-
-		$bb_code = $options["bb_code"] ?? true;
-		$emoticon = $options["emoticon"] ?? true;
-
-		$string = htmlspecialchars($string);
-		$string = nl2br($string);
-
-		/*
-		if($emoticon && $emoticonresult) {
-			db::data_seek($emoticonresult, 0);
-			while($myrow = db::fetch_array($emoticonresult)) {
-				$replacetext = $myrow["replacetext"];
-				$url = $myrow["url"];
-				$description = $myrow["description"];
-				$string = str_replace("$replacetext", "<img src=\"$dirPrefix$url\" alt=\"$description\" />", $string);
-			}
-		}
-		*/
-
-		if($emoticon) {
-			$string = Emoticon::apply($string);
-		}
-
-		if($bb_code) {
-			$string = Util::BBCode($string);
-		}
-
-		$pattern = "[0-9a-zA-Z\&\/\-\#\%\.\?\=\;\_\:\,\+\(\)\!]";
-
-		$string = preg_replace("/^http(s?):\/\/($pattern*)/", "<a href=\"http$1://$2\" target=\"_blank\">http$1://$2</a> ", $string); // Case for beginning
-		$string = preg_replace("/\shttp(s?):\/\/($pattern*)/", " <a href=\"http$1://$2\" target=\"_blank\">http$1://$2</a>", $string); // Case for middle
-		$string = preg_replace("/http(s?):\/\/($pattern*)$/", " <a href=\"http$1://$2\" target=\"_blank\">http$1://$2</a>", $string); // Case for end
-
-		return $string;
-	}
-
-	public static function BBCode($string) {
-
-		preg_match_all("/\[quote/i", $string, $matches);
-		$quote_begin_count = count($matches["0"]);
-
-		preg_match_all("/\[\/quote\]/i", $string, $matches);
-		$quote_end_count = count($matches["0"]);
-
-		$quotes = min($quote_begin_count, $quote_end_count);
-
-		$valid_quotes = ($quote_begin_count == $quote_end_count);
-
-		if(!$valid_quotes) {
-		}
-
-		$search = [
-			"/\[b\](.*?)\[\/b\]/is",
-			"/\[i\](.*?)\[\/i\]/is",
-			"/\[u\](.*?)\[\/u\]/is",
-			"/\[s\](.*?)\[\/s\]/is",
-			"/\[spoiler\](.*?)\[\/spoiler\]/is",
-			"/\[img\=(.*?)\]/is",
-			"/\[img\](.*?)\[\/img\]/is",
-			"/\[img width\=(.*?)\](.*?)\[\/img\]/is",
-			"/\[url\](.*?)\[\/url\]/is",
-			"/\[url\=(.*?)\](.*?)\[\/url\]/is",
-			"/\[color\=(.*?)\](.*?)\[\/color\]/is",
-			"/\[colour\=(.*?)\](.*?)\[\/colour\]/is",
-			"/\[size\=(.*?)\](.*?)\[\/size\]/is",
-			"/\[font\=(.*?)\](.*?)\[\/font\]/is",
-			"/\[center\](.*?)\[\/center\]<br \/>/is",
-			"/\[center\](.*?)\[\/center\]/is",
-			"/\[code\](.*?)\[\/code\]/is",
-			"/\[background\=(.*?)\](.*?)\[\/background\]/is",
-			"/\[youtube\][^\s]+v\=([A-Za-z0-9\-_]+)[^\s]*\[\/youtube\]/is", // YouTube URL
-			"/\[youtube\]([A-Za-z0-9\-_]+?)\[\/youtube\]/is", // YouTube ID
-			"/\[twitch\]([A-Za-z0-9\-_]+?)\[\/twitch\]/is", // Twitch ID
-			"/\[hrd?\]\<br \/\>/is",
-			"/\[nico\](.*?)\[\/nico\]/is",
-			"/\[leftfloat\](.*?)\[\/leftfloat\]/is",
-			"/\[rightfloat\](.*?)\[\/rightfloat\]/is",
-			"/\[leftfloat width\=(.*?)\](.*?)\[\/leftfloat\]/is",
-			"/\[clear\]/is",
-		];
-
-		$replace = [
-			'<strong>$1</strong>',
-			'<em>$1</em>',
-			'<u>$1</u>',
-			'<del>$1</del>',
-			'<span class="spoiler">$1</span>',
-			'<img class="img-fluid" src="$1" alt="$1" />',
-			'<img class="img-fluid" src="$1" alt="$1" />',
-			'<img class="img-fluid" width="$1" src="$2" alt="$2" />',
-			'<a href="$1" target="_blank">$1</a>',
-			'<a href="$1" target="_blank">$2</a>',
-			'<span style="color: $1;">$2</span>',
-			'<span style="color: $1;">$2</span>',
-			'<span style="font-size: $1'.'px;">$2</span>',
-			'<span style="font-family: $1;">$2</span>',
-			'<div class="text-center">$1</div>',
-			'<div class="text-center">$1</div>',
-			'<div class="code">$1</div>',
-			'<span style="background: $1;">$2</span>',
-			'<iframe width="448" height="280" src="https://www.youtube.com/embed/$1"></iframe>',
-			'<iframe width="448" height="280" src="https://www.youtube.com/embed/$1"></iframe>',
-			'<object type="application/x-shockwave-flash" height="378" width="620" id="live_embed_player_flash" data="https://www.twitch.tv/widgets/live_embed_player.swf?channel=$1" bgcolor="#000000">
-<param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="movie" value="http://www.twitch.tv/widgets/live_embed_player.swf" /><param name="flashvars" value="hostname=www.twitch.tv&channel=$1&auto_play=false&start_volume=25" /></object>',
-			'<hr />',
-			'<script type="text/javascript" src="https://ext.nicovideo.jp/thumb_watch/$1"></script>',
-			'<div class="float-left">$1</div>',
-			'<div class="float-right">$1</div>',
-			'<div class="float-left" style="width: $1%;">$2</div>',
-			'<div class="float-none"></div>',
-		];
-
-		$string = preg_replace($search, $replace, $string);
-
-		if($valid_quotes) {
-			$search = [
-				"/\[quote\]/is",
-				"/\[quote\=(.*?)\]([^\]])/is",
-				"/\[quote\=(.*?)\]/is",
-				"/\[\/quote\]<br \/>/is",
-				"/\[\/quote\]/is",
-			];
-
-			$replace = [
-				'<div class="card quote mb-3"><div class="card-header">Quote</div><div class="card-body">',
-				'<div class="card quote mb-3"><div class="card-header">Quote: $1</div><div class="card-body">$2',
-				'<div class="card quote mb-3"><div class="card-header">Quote: $1</div><div class="card-body">',
-				'</div></div>',
-				'</div></div>',
-			];
-
-			$string = preg_replace($search, $replace, $string, $quotes);
-		}
-
-		return $string;
-	}
-}
+}

+ 13 - 1
engine/venue_type.php

@@ -1,5 +1,12 @@
 <?php
 
+/**
+ * Class VenueType
+ *
+ * @property int $id
+ * @property string $name
+ */
+
 class VenueType extends Model {
 
 	protected static $table = "venue_type";
@@ -7,7 +14,12 @@ class VenueType extends Model {
 	protected static $fillable_fields = ["name"];
 
 	// Static methods
-	public static function getAll() {
+
+	/**
+	 * @return VenueType[]
+	 * @throws Exception
+	 */
+	public static function getAll(): array {
 		return self::query([], ["sort" => "name"]);
 	}
 

+ 14 - 3
engine/view.php

@@ -4,11 +4,17 @@ class View {
 
 	protected static $included = [];
 
-	public static function include($view, $params = []) {
+	/**
+	 * @param string $view
+	 * @param array $params
+	 * @throws Exception
+	 */
+	public static function include(string $view, array $params = []) {
 		$view_path = ROOT_DIR . "/views/" . $view . ".php";
 		if(file_exists($view_path)) {
 			self::$included[] = $view;
 			extract($params);
+			/** @noinspection PhpIncludeInspection */
 			require $view_path;
 		}
 		else {
@@ -16,8 +22,13 @@ class View {
 		}
 	}
 
-	public static function includeOnce($view, $params = []) {
+	/**
+	 * @param string $view
+	 * @param array $params
+	 * @throws Exception
+	 */
+	public static function includeOnce(string $view, array $params = []) {
 		if(in_array($view, self::$included)) return;
 		self::include($view, $params);
 	}
-}
+}

+ 73 - 0
export_processing/project_quickbooks_customer_csv.php

@@ -0,0 +1,73 @@
+<?php
+
+/**
+ * @var Project[] $projects
+ */
+
+$utc_timezone = new DateTimeZone("UTC");
+$invoice_interval = new DateInterval("P30D");
+
+$current_dt = new DateTime();
+$date = $current_dt->format("d/m/Y");
+
+$field_names = [
+	"Invoice No",
+	"Customer",
+	"Invoice Date",
+	"Due Date",
+	"Terms",
+	"Location",
+	"Memo",
+	"Item (Product/Service)",
+	"Item Description",
+	"Item Quantity",
+	"Item Rate",
+	"Item Amount",
+	"Item Tax Code",
+	"Item Tax Amount",
+	"Service Date",
+];
+
+fputcsv($handle, $field_names);
+
+foreach($projects as $project) {
+
+    if($project->dts_finished === null) continue;
+
+    $customer = $project->getCustomer();
+
+    $invoice = $project->getCustomerInvoice();
+    $line_items = $invoice->getLineItems();
+
+    $invoice_generated_dt = new DateTime($project->dts_finished, $utc_timezone);
+    $invoice_date = $invoice_generated_dt->format("d/m/Y");
+
+    $invoice_generated_dt->add($invoice_interval);
+	$invoice_due_date = $invoice_generated_dt->format("d/m/Y");
+
+	$time_text = $project->getTimeOfDayText();
+
+    foreach($line_items as $item) {
+
+		$output = [];
+
+		$output[] = $invoice->getReference(); // "Invoice No",
+		$output[] = $customer->name; // "Customer",
+		$output[] = $invoice_date; // "Invoice Date",
+		$output[] = $invoice_due_date; // "Due Date",
+		$output[] = "Net 30"; // "Terms",
+		$output[] = ""; // "Location",
+		$output[] = "{$project->id} {$project->name} ({$time_text})"; // "Memo",
+		$output[] = $item->getName(); // "Item (Product/Service)",
+		$output[] = ""; // "Item Description",
+		$output[] = $item->getQuantity() ?: "1"; // "Item Quantity",
+		$output[] = $item->getPrice(); // "Item Rate",
+		$output[] = $item->getTotal(); // "Item Amount",
+		$output[] = ($invoice->getTaxRate() * 100) . "%"; // "Item Tax Code",
+		$output[] = $invoice->getTaxRate() * $item->getTotal(); // "Item Tax Amount",
+		$output[] = $date; // "Service Date",
+
+		fputcsv($handle, $output);
+
+    }
+}

+ 60 - 0
export_processing/project_quickbooks_tester_csv.php

@@ -0,0 +1,60 @@
+<?php
+
+$utc_timezone = new DateTimeZone("UTC");
+$invoice_interval = new DateInterval("P30D");
+
+$field_names = [
+	"BillNo",
+	"Supplier",
+	"BillDate",
+	"DueDate",
+	"Terms",
+	"Location",
+	"Memo",
+	"Account",
+	"LineDescription",
+	"LineAmount",
+	"LineTaxCode",
+	"LineTaxAmount",
+];
+
+fputcsv($handle, $field_names);
+
+foreach($tests as $test) {
+
+    if($test->dts_tester_invoice_paid === null) continue;
+
+    $project = $test->getProject();
+    $template = $project->getTemplate();
+	$location = $test->getLocation();
+	$tester = $test->getTester();
+	$values = $test->getValues(true);
+
+    $test_cost = $test->test_fee > 0 ? $test->test_fee : $project->default_tester_fee;
+    $travel_costs = $test->test_travel_cost > 0 ? $test->test_travel_cost : 0;
+    $other_costs = $template->getTesterInvoiceCosts($values);
+
+    $total_cost = $test_cost + $travel_costs + $other_costs;
+
+    $invoice_generated_dt = new DateTime($test->dts_tester_invoice_generated, $utc_timezone);
+    $invoice_date = $invoice_generated_dt->format("d/m/Y");
+
+    $invoice_generated_dt->add($invoice_interval);
+    $invoice_due_date = $invoice_generated_dt->format("d/m/Y");
+
+	$output = [];
+	$output[] = $test->getTesterInvoiceReference();
+	$output[] = sprintf("%d %s %s", $tester->id, $tester->first_name, $tester->last_name);
+	$output[] = $invoice_date;
+	$output[] = $invoice_due_date;
+	$output[] = "Net 30";
+	$output[] = "";
+	$output[] = "$location->id $location->name";
+	$output[] = "Tester Fees";
+	$output[] = "";
+	$output[] = $total_cost;
+	$output[] = "No VAT";
+	$output[] = "0";
+
+	fputcsv($handle, $output);
+}

+ 35 - 0
json/age_verification.json

@@ -48,6 +48,25 @@
 		}
 	],
 	"duringTest": [
+
+		{
+			"type": "header",
+			"content": "Venue Sensor"
+		},
+		{
+			"type": "dropdown",
+			"name": "door_sensor_alert",
+			"label": "Door Sensor Alert",
+			"values": ["", "0", "1"],
+			"displayStrings": ["Don't know", "No", "Yes"],
+			"helpText": "Was there a sound or visual alert when you entered the venue?",
+			"customerExport": false
+		},
+
+		{
+			"type": "hr"
+		},
+
 		{
 			"type": "header",
 			"content": "Challenge Details"
@@ -68,6 +87,10 @@
 			"helpText": "Describe how the challenge took place. For example: \"While entering I was approached politely and asked for ID.\""
 		},
 
+		{
+			"type": "hr"
+		},
+
 		{
 			"type": "header",
 			"content": "Challenger Details (if challenged)"
@@ -104,6 +127,10 @@
 			"customerExport": false
 		},
 
+		{
+			"type": "hr"
+		},
+
 		{
 			"type": "header",
 			"content": "Play Details"
@@ -150,6 +177,10 @@
 			"helpText": "For example: Enter 1.50 if you have spent £1.50."
 		},
 
+		{
+			"type": "hr"
+		},
+
 		{
 			"type": "header",
 			"content": "Signage Details"
@@ -190,6 +221,10 @@
 			"helpText": "Describe the location of the poster that was displayed."
 		},
 
+		{
+			"type": "hr"
+		},
+
 		{
 			"type": "header",
 			"content": "Notes"

+ 37 - 0
json/age_verification_mitchells_and_butlers.json

@@ -49,6 +49,24 @@
 		}
 	],
 	"duringTest": [
+		{
+			"type": "header",
+			"content": "Venue Sensor"
+		},
+		{
+			"type": "dropdown",
+			"name": "door_sensor_alert",
+			"label": "Door Sensor Alert",
+			"values": ["", "0", "1"],
+			"displayStrings": ["Don't know", "No", "Yes"],
+			"helpText": "Was there a sound or visual alert when you entered the venue?",
+			"customerExport": false
+		},
+
+		{
+			"type": "hr"
+		},
+
 		{
 			"type": "header",
 			"content": "Challenge Details"
@@ -69,6 +87,10 @@
 			"helpText": "Describe how the challenge took place. For example: \"While entering I was approached politely and asked for ID.\""
 		},
 
+		{
+			"type": "hr"
+		},
+
 		{
 			"type": "header",
 			"content": "Challenger Details (if challenged)"
@@ -105,6 +127,10 @@
 			"customerExport": false
 		},
 
+		{
+			"type": "hr"
+		},
+
 		{
 			"type": "header",
 			"content": "Bar Details"
@@ -142,6 +168,9 @@
 			"maxLength": 20
 		},
 
+		{
+			"type": "hr"
+		},
 
 		{
 			"type": "header",
@@ -205,6 +234,10 @@
 			"helpText": "For example: Enter 1.50 if you have spent £1.50."
 		},
 
+		{
+			"type": "hr"
+		},
+
 		{
 			"type": "header",
 			"content": "Signage Details"
@@ -245,6 +278,10 @@
 			"helpText": "Describe the location of the poster that was displayed."
 		},
 
+		{
+			"type": "hr"
+		},
+
 		{
 			"type": "header",
 			"content": "Notes"

BIN
locales/en_GB/LC_MESSAGES/en_GB.mo


File diff suppressed because it is too large
+ 290 - 295
locales/en_GB/LC_MESSAGES/en_GB.po


BIN
locales/es_ES/LC_MESSAGES/es_ES.mo


File diff suppressed because it is too large
+ 246 - 270
locales/es_ES/LC_MESSAGES/es_ES.po


BIN
locales/nl_NL/LC_MESSAGES/nl_NL.mo


File diff suppressed because it is too large
+ 218 - 251
locales/nl_NL/LC_MESSAGES/nl_NL.po


File diff suppressed because it is too large
+ 365 - 201
package-lock.json


+ 14 - 8
package.json

@@ -14,26 +14,32 @@
   "license": "ISC",
   "dependencies": {
     "@google/markerclusterer": "^1.0.3",
-    "bootstrap": "^4.2.1",
-    "chart.js": "^2.7.3",
+    "bootstrap": "^4.3.1",
+    "chart.js": "^2.8.0",
     "chartjs-plugin-datalabels": "^0.6.0",
     "clipboard": "^2.0.4",
     "datatables.net-bs4": "^1.10.19",
     "datatables.net-buttons-bs4": "^1.5.6",
     "datatables.net-responsive-bs4": "^2.2.3",
     "daterangepicker": "^3.0.5",
-    "gulp": "^4.0.1",
-    "gulp-autoprefixer": "^6.1.0",
+    "gulp": "^4.0.2",
+    "gulp-autoprefixer": "^7.0.0",
     "gulp-clean-css": "^4.2.0",
     "gulp-rename": "^1.4.0",
     "gulp-sass": "^4.0.2",
     "holderjs": "^2.9.6",
     "jquery": "^3.4.1",
-    "popper.js": "^1.14.6"
+    "popper.js": "^1.15.0"
   },
   "devDependencies": {
-    "@fortawesome/fontawesome-pro": "^5.8.1",
+    "@fortawesome/fontawesome-pro": "^5.10.2",
     "cross-env": "^5.2.0",
-    "laravel-mix": "^4.0.15"
-  }
+    "laravel-mix": "^4.1.2"
+  },
+  "browserslist": [
+    "last 1 version",
+    "> 1%",
+    "maintained node versions",
+    "not dead"
+  ]
 }

File diff suppressed because it is too large
+ 3 - 3
public/css/bootstrap.min.css


BIN
public/img/markers/closed.png


BIN
public/img/markers/do_not_test.png


File diff suppressed because it is too large
+ 4 - 7
public/js/Chart.bundle.min.js


File diff suppressed because it is too large
+ 1 - 1
public/js/all.min.js


+ 120 - 85
public/js/app-map-overview.js

@@ -1,16 +1,20 @@
+
 var markerGroups = [];
 var infoWindow = false;
 
 $(function() {
 
-	$("a[data-customer-id]").click(function(event) {
+	// On customer select
+	$("a[data-customer-id]").click(function() {
 		let customerId = $(this).data("customer-id");
 
 		let key = "customer-" + customerId;
 		if(typeof markerGroups[key] !== "undefined") {
 			for(let i in markerGroups[key]) {
-				let m = markerGroups[key][i];
-				m.setMap(null);
+				if(markerGroups[key].hasOwnProperty(i)) {
+					let m = markerGroups[key][i];
+					m.setMap(null);
+				}
 			}
 		}
 
@@ -26,14 +30,17 @@ $(function() {
 		return false;
 	});
 
-	$("a[data-project-id]").click(function(event) {
+	// On project select
+	$("a[data-project-id]").click(function() {
 		let projectId = $(this).data("project-id");
 
 		let key = "project-" + projectId;
 		if(typeof markerGroups[key] !== "undefined") {
 			for(let i in markerGroups[key]) {
-				let m = markerGroups[key][i];
-				m.setMap(null);
+				if(markerGroups[key].hasOwnProperty(i)) {
+					let m = markerGroups[key][i];
+					m.setMap(null);
+				}
 			}
 		}
 
@@ -49,13 +56,16 @@ $(function() {
 		return false;
 	});
 
-	$("a[data-all-addresses]").click(function(event) {
+	// On all addresses select
+	$("a[data-all-addresses]").click(function() {
 
 		let key = "all-addresses";
 		if(typeof markerGroups[key] !== "undefined") {
 			for(let i in markerGroups[key]) {
-				let m = markerGroups[key][i];
-				m.setMap(null);
+				if(markerGroups[key].hasOwnProperty(i)) {
+					let m = markerGroups[key][i];
+					m.setMap(null);
+				}
 			}
 		}
 
@@ -75,13 +85,21 @@ $(function() {
 
 function loadCustomerLocations(customerId) {
 
-	if(infoWindow == false) {
+	if(infoWindow === false) {
 		infoWindow = new google.maps.InfoWindow();
 	}
 
 	let minDate = $("#min-date").val();
 	let maxDate = $("#max-date").val();
 
+	let $customerItem = $("a[data-customer-id=" + customerId + "]");
+
+	/**
+	 * @property {Object} response
+	 * @property {Array} response.locations
+	 * @property {Boolean} response.success
+	 */
+
 	$.get("/account/map-overview/get-customer-locations", {
 		customer_id: customerId,
 		min_date: minDate,
@@ -90,37 +108,19 @@ function loadCustomerLocations(customerId) {
 	}, function(response) {
 		if(!response.success) return false;
 
-		let map = maps["map"];
 		let key = "customer-" + customerId;
 
 		markerGroups[key] = [];
 
-		for(let i in response.locations) {
-			let l = response.locations[i];
-
-			let position = {
-				lat: l.latitude,
-				lng: l.longitude
-			};
-
-			var options = {
-				position: position,
-				title: l.name,
-				map: map
-			};
-
-			if(l.icon) options.icon = "/img/markers/" + l.icon;
-
-			infoWindow.setContent("");
-
-			let marker = new google.maps.Marker(options);
-			addMarkerClickListenerForLocation(marker, l);
+		let count = response.locations.length;
 
+		for(let i = 0; i < count; ++i) {
+			let marker = addLocationMarker(response.locations[i]);
 			markerGroups[key].push(marker);
 		}
 
-		$("a[data-customer-id=" + customerId + "]").data("selected", true);
-		$("a[data-customer-id=" + customerId + "]").find(".badge").addClass("badge-danger").text(response.locations.length);
+		$customerItem.data("selected", true);
+		$customerItem.find(".badge").addClass("badge-danger").text(response.locations.length);
 
 	});
 
@@ -128,13 +128,21 @@ function loadCustomerLocations(customerId) {
 
 function loadProjectLocations(projectId) {
 
-	if(infoWindow == false) {
+	if(infoWindow === false) {
 		infoWindow = new google.maps.InfoWindow();
 	}
 
 	let minDate = $("#min-date").val();
 	let maxDate = $("#max-date").val();
 
+	let $projectItem = $("a[data-project-id=" + projectId + "]");
+
+	/**
+	 * @property {Object} response
+	 * @property {Array} response.locations
+	 * @property {Boolean} response.success
+	 */
+
 	$.get("/account/map-overview/get-project-locations", {
 		project_id: projectId,
 		min_date: minDate,
@@ -143,47 +151,63 @@ function loadProjectLocations(projectId) {
 	}, function(response) {
 		if(!response.success) return false;
 
-		let map = maps["map"];
 		let key = "project-" + projectId;
 
 		markerGroups[key] = [];
 
-		for(let i in response.locations) {
+		let count = response.locations.length;
 
-			let l = response.locations[i];
+		for(let i = 0; i < count; ++i) {
+			let marker = addLocationMarker(response.locations[i]);
+			markerGroups[key].push(marker);
+		}
 
-			let position = {
-				lat: l.latitude,
-				lng: l.longitude
-			};
+		$projectItem.data("selected", true);
+		$projectItem.find(".badge").addClass("badge-danger").text(response.locations.length);
 
-			var options = {
-				position: position,
-				title: l.name,
-				map: map
-			};
+	});
+}
 
-			if(l.icon) options.icon = "/img/markers/" + l.icon;
+function addLocationMarker(location) {
 
-			let marker = new google.maps.Marker(options);
-			addMarkerClickListenerForLocation(marker, l);
+	let map = maps["map"];
 
-			markerGroups[key].push(marker);
+	let position = {
+		lat: location.latitude,
+		lng: location.longitude
+	};
 
-		}
+	var options = {
+		position: position,
+		title: location.name,
+		map: map
+	};
 
-		$("a[data-project-id=" + projectId + "]").data("selected", true);
-		$("a[data-project-id=" + projectId + "]").find(".badge").addClass("badge-danger").text(response.locations.length);
+	if(location.icon) options.icon = "/img/markers/" + location.icon;
+	if(location.doNotTest) options.icon = "/img/markers/do_not_test.png";
+	if(location.closed) options.icon = "/img/markers/closed.png";
 
-	});
+	infoWindow.setContent("");
+
+	let marker = new google.maps.Marker(options);
+	addMarkerClickListenerForLocation(marker, location);
+	return marker;
 }
 
 function loadAllAddresses() {
 
-	if(infoWindow == false) {
+	if(infoWindow === false) {
 		infoWindow = new google.maps.InfoWindow();
 	}
 
+	/**
+	 * @property {Object} response
+	 * @property {Array} response.addresses
+	 * @property {Boolean} response.success
+	 */
+
+	let $allAddresses = $("a[data-all-addresses]");
+
 	$.get("/api/addresses/get-all", {
 		submit: $("#submit").val()
 	}, function(response) {
@@ -194,82 +218,93 @@ function loadAllAddresses() {
 
 		markerGroups[key] = [];
 
-		for(let i in response.addresses) {
+		let addressCount = response.addresses.length;
+
+		for(let i = 0; i < addressCount; ++i) {
 
-			let a = response.addresses[i];
+			let address = response.addresses[i];
 
 			let position = {
-				lat: a.latitude,
-				lng: a.longitude
+				lat: address.latitude,
+				lng: address.longitude
 			};
 
 			var options = {
 				position: position,
-				title: a.name,
+				title: address.name,
 				map: map
 			};
 
 			let marker = new google.maps.Marker(options);
-			addMarkerClickListenerForAddress(marker, a);
+			addMarkerClickListenerForAddress(marker, address);
 
 			markerGroups[key].push(marker);
 
 		}
 
-		$("a[data-all-addresses]").data("selected", true);
-		$("a[data-all-addresses]").find(".badge").addClass("badge-danger").text(response.addresses.length);
+		$allAddresses.data("selected", true);
+		$allAddresses.find(".badge").addClass("badge-danger").text(response.addresses.length);
 
 	});
 }
 
-function addMarkerClickListenerForLocation(m, l) {
+function addMarkerClickListenerForLocation(marker, location) {
 	let map = maps["map"];
-	m.addListener("click", function() {
-		let content = "<strong><a href=\"/account/locations/" + l.id + "\" target=\"_blank\">" + l.name + "</a></strong><br />";
-		if(l.internalId) {
-			content += "<div class=\"small\"><strong>Internal ID:</strong> " + l.internalId + "</div>";
+	marker.addListener("click", function() {
+		let content = "<div><strong><a href=\"/account/locations/" + location.id + "\" target=\"_blank\">" + location.name + "</a></strong></div>";
+
+		if(location.doNotTest) {
+			content += "<span class=\"badge badge-warning\">Do Not Test</span>";
+		}
+
+		if(location.closed) {
+			content += "<span class=\"badge badge-danger\">Closed</span>";
+		}
+
+		if(location.internalId) {
+			content += "<div class=\"small\"><strong>Internal ID:</strong> " + location.internalId + "</div>";
 		}
-		content += "<div class=\"small\"><strong>Location ID:</strong> " + l.id + "</div>";
+		content += "<div class=\"small\"><strong>Location ID:</strong> " + location.id + "</div>";
 
-		if(l.test) {
+		if(location.test) {
 
 			content += '<hr />';
 
-			content += '<div class="small"><strong>Test ID:</strong> <a href="/account/tests/' + l.test.id + '" target="_blank">' + l.test.id + '</a></div>';
+			content += '<div class="small"><strong>Test ID:</strong> <a href="/account/tests/' + location.test.id + '" target="_blank">' + location.test.id + '</a></div>';
 
-			if(l.test.formattedStartDts) {
-				content += '<div class="small"><strong>Date/Time:</strong> ' + l.test.formattedStartDts + '</div>';
+			if(location.test.formattedStartDts) {
+				content += '<div class="small"><strong>Date/Time:</strong> ' + location.test.formattedStartDts + '</div>';
 			}
 
-			if(l.test.tester) {
-				content += '<div class="small"><strong>Tester ID:</strong> ' + l.test.tester.id + '</div>';
-				content += '<div class="small"><strong>Tester Name:</strong> <a href="/account/users/' + l.test.tester.id + '" target="_blank">' + l.test.tester.name + '</a></div>';
+			if(location.test.tester) {
+				content += '<div class="small"><strong>Tester ID:</strong> ' + location.test.tester.id + '</div>';
+				content += '<div class="small"><strong>Tester Name:</strong> <a href="/account/users/' + location.test.tester.id + '" target="_blank">' + location.test.tester.name + '</a></div>';
 			}
 
 			let pastDueBadge = '';
-			if(l.test.pastDue) {
+			if(location.test.pastDue) {
 				pastDueBadge = '<span class="badge badge-lg badge-primary">Past Due</span>';
 			}
 
-			if(l.test.formattedDueDts) {
-				content += '<div class="small"><strong>Due:</strong> ' + l.test.formattedDueDts + ' ' + pastDueBadge + '</div>';
+			if(location.test.formattedDueDts) {
+				content += '<div class="small"><strong>Due:</strong> ' + location.test.formattedDueDts + ' ' + pastDueBadge + '</div>';
 			}
 
 		}
 
 
 		infoWindow.setContent(content);
-		infoWindow.open(map, m);
+		infoWindow.open(map, marker);
 	});
 }
 
-function addMarkerClickListenerForAddress(m, a) {
+function addMarkerClickListenerForAddress(marker, address) {
 	let map = maps["map"];
-	m.addListener("click", function() {
-		let content = "<strong><a href=\"/account/users/" + a.userId + "\" target=\"_blank\">" + a.name + "</a></strong><br />";
-		content += "ID: " + a.userId + "<br />";
+	marker.addListener("click", function() {
+		let content = "<strong><a href=\"/account/users/" + address.userId + "\" target=\"_blank\">" + address.name + "</a></strong><br />";
+		content += "ID: " + address.userId + "<br />";
 
 		infoWindow.setContent(content);
-		infoWindow.open(map, m);
+		infoWindow.open(map, marker);
 	});
 }

+ 19 - 0
public/js/app-projects.js

@@ -22,6 +22,25 @@ $(function() {
 				$("#projects-form").attr("action", "/account/projects/export-csv");
 				$("#type").val("customer");
 				break;
+
+			case "export-quickbooks-customer-csv":
+				$("#projects-form").attr("action", "/account/projects/export-csv");
+				$("#type").val("quickbooks-customer");
+				break;
+
+			case "export-quickbooks-tester-csv":
+				$("#projects-form").attr("action", "/account/projects/export-csv");
+				$("#type").val("quickbooks-tester");
+				break;
+		}
+	});
+
+	$("#projects-table-select-all").on("click", function() {
+		let $checkboxes = $(this).parents("table").find("input:checkbox");
+		let count = $checkboxes.length;
+
+		for(let i = 0; i < count; i++) {
+			$checkboxes.get(i).checked = this.checked;
 		}
 	});
 

+ 10 - 0
public/js/app-test-list.js

@@ -0,0 +1,10 @@
+$(function() {
+	$("#tests-table-select-all").on("click", function() {
+		let $checkboxes = $(this).parents("table").find("input:checkbox");
+		let count = $checkboxes.length;
+
+		for(let i = 0; i < count; i++) {
+			$checkboxes.get(i).checked = this.checked;
+		}
+	});
+});

File diff suppressed because it is too large
+ 2 - 2
public/js/bootstrap.min.js


File diff suppressed because it is too large
+ 0 - 0
public/js/bootstrap.min.js.map


File diff suppressed because it is too large
+ 1 - 1
public/js/popper.min.js


File diff suppressed because it is too large
+ 0 - 0
public/js/popper.min.js.map


+ 8 - 2
routes.php

@@ -65,12 +65,17 @@ $routes = [
 	"/^account\/projects\/$id_pattern\/edit$/" => ["controller" => "project_edit", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/$id_pattern\/edit\/template-overrides$/" => ["controller" => "project_edit_template_overrides", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/export-csv$/" => ["controller" => "project_export", "require_user_level" => User::LEVEL_ADMIN],
-	"/^account\/projects\/$id_pattern\/export-(admin|customer)-csv$/" => ["controller" => "project_export", "params" => ["id", "type"], "require_user_level" => User::LEVEL_ADMIN],
+	"/^account\/projects\/$id_pattern\/export-(admin|customer|quickbooks)-csv$/" => ["controller" => "project_export", "params" => ["id", "type"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/$id_pattern\/export-kml$/" => ["controller" => "project_kml", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/$id_pattern\/invoice$/" => ["controller" => "project_invoice", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/$id_pattern\/(mark-finished|mark-unfinished)$/" => ["controller" => "project_mark_finished", "params" => ["id", "action"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/$id_pattern\/(get-locations|get-testers|create-test|assign-tester)$/" => ["controller" => "project_ajax", "params" => ["id", "action"], "type" => "json", "require_user_level" => User::LEVEL_ADMIN],
 
+	// Test Results
+	"/^account\/test-results$/" => ["controller" => "test_results_customer_list"],
+	"/^account\/test-results\/{$slug_id_pattern}$/" => ["controller" => "test_results_project_list", "params" => ["customer_id"]],
+	"/^account\/test-results\/{$slug_id_pattern}\/{$slug_id_pattern}$/" => ["controller" => "test_results_test_list", "params" => ["customer_id", "project_id"]],
+
 	// Tests
 	"/^account\/tests$/" => ["controller" => "tests", "require_user_level" => User::LEVEL_TESTER],
 	"/^account\/tests\/postal\-codes$/" => ["controller" => "tests_tester_postal_codes", "require_user_level" => User::LEVEL_TESTER],
@@ -79,6 +84,7 @@ $routes = [
 	"/^account\/tests\/completed$/" => ["controller" => "tests_completed", "require_user_level" => User::LEVEL_TESTER],
 	"/^account\/tests\/$id_pattern$/" => ["controller" => "test", "params" => ["id"], "require_user_level" => User::LEVEL_TESTER],
 	"/^account\/tests\/$id_pattern\/(selfie)$/" => ["controller" => "test_file", "params" => ["id", "name"], "require_user_level" => User::LEVEL_TESTER],
+	"/^account\/tests\/$id_pattern\/files\/(pdf)$/" => ["controller" => "test_file", "params" => ["id", "name"], "require_user_level" => User::LEVEL_CUSTOMER],
 	"/^account\/tests\/$id_pattern\/files\/([a-z_]+)$/" => ["controller" => "test_file", "params" => ["id", "name"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/tests\/$id_pattern\/result$/" => ["controller" => "test_result", "params" => ["id"], "require_user_level" => User::LEVEL_VENUE],
 	"/^account\/tests\/$id_pattern\/pdf$/" => ["controller" => "test_pdf", "params" => ["id"], "require_user_level" => User::LEVEL_VENUE],
@@ -121,7 +127,7 @@ $routes = [
 	"/^account\/customers\/$id_pattern$/" => ["controller" => "customer_view", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/customers\/$id_pattern\/edit$/" => ["controller" => "customer_edit", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 
-	"/^api\/customers\/$id_pattern\/(get-locations)$/" => ["controller" => "customer_ajax", "params" => ["id", "action"], "require_user_level" => User::LEVEL_ADMIN],
+	"/^api\/customers\/$id_pattern\/(get-locations)$/" => ["controller" => "customer_ajax", "params" => ["id", "action"], "require_user_level" => User::LEVEL_CUSTOMER],
 
 	// Practice
 	"/^account\/practice$/" => ["controller" => "practice_template_select", "require_user_level" => User::LEVEL_TESTER],

+ 22 - 587
template_processing/age_verification/reports_build_charts.php

@@ -1,592 +1,27 @@
 <?php
 
-// Tests by Stage
-
-$chart = new Chart;
-$chart->setType("doughnut");
-$chart->setTitle("Tests by Stage $date_range_label");
-$chart->setLabels(["1 - On Entry", "2 - While Browsing", "3 - During Play", "4 - On Exit", "5 - No Challenge"]);
-$chart->addDataset("Tests", [
-	$total_data->stage1Count,
-	$total_data->stage2Count,
-	$total_data->stage3Count,
-	$total_data->stage4Count,
-	$total_data->stage5Count,
-], [
-	"background_colours" => [
-		"#4CAF50",
-		"#FFEB3B",
-		"#FBC02D",
-		"#FFAB91",
-		"#F44336",
-	],
-	"datalabels" => Chart::DATALABELS_BOX,
-]);
-$chart->setPrintSuffixes("");
-$chart->print = true;
-$chart->printPercentages = true;
-$chart->printTotalColumn = true;
-$chart->setPrintLabels(["Stage 1", "Stage 2", "Stage 3", "Stage 4", "Stage 5"]);
-
-$charts[] = $chart;
-
-
-// Challenger Gender
-$chart = new Chart;
-$chart->setType("pie");
-$chart->setTitle("Staff Gender $date_range_label");
-$chart->setLabels(["Male", "Female", "Unspecified"]);
-$chart->addDataset("Counts", [
-	$total_data->maleChallengerCount,
-	$total_data->femaleChallengerCount,
-	$total_data->unspecifiedChallengerCount,
-], [
-	"background_colours" => [
-		"#2196F3",
-		"#E91E63",
-		"#9E9E9E",
-	],
-	"datalabels" => Chart::DATALABELS_BOX,
-]);
-$charts[] = $chart;
-
-// Tester Gender
-$chart = new Chart;
-$chart->setType("pie");
-$chart->setTitle("Tester Gender $date_range_label");
-$chart->setLabels(["Male", "Female"]);
-$chart->addDataset("Counts", [
-	$total_data->maleTesterCount,
-	$total_data->femaleTesterCount,
-], [
-	"background_colours" => [
-		"#2196F3",
-		"#E91E63",
-	],
-	"datalabels" => Chart::DATALABELS_BOX,
-]);
-$charts[] = $chart;
-
-// Pass / Fail
-$chart = new Chart;
-$chart->setType("pie");
-$chart->setTitle("Pass / Fail $date_range_label");
-$chart->setLabels(["Pass", "Fail"]);
-$chart->addDataset("Counts", [
-	$total_data->passCount,
-	$total_data->failCount,
-], [
-	"background_colours" => [
-		"#4CAF50",
-		"#F44336",
-	],
-	"datalabels" => Chart::DATALABELS_BOX,
-]);
-$charts[] = $chart;
-
-// Pass Rate Period
-$pass_rates = array_values(array_map(function($d) {
-	if($d->testCount == 0) return 0;
-	return round(($d->passCount / $d->testCount) * 100);
-}, $data));
-
-$fail_rates = array_values(array_map(function($d) {
-	if($d->testCount == 0) return 0;
-	$pass_rate = round(($d->passCount / $d->testCount) * 100);
-	return 100 - $pass_rate;
-}, $data));
-
-$chart = new Chart;
-$chart->addXAxis([
-	"type" => "category",
-	"stacked" => true,
-]);
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => 100],
-	"stacked" => true,
-]);
-
-$chart->setType("bar");
-$chart->setTitle("Pass / Fail by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("Pass Rate (%)", $pass_rates, [
-	"background_colours" => "#4CAF50"
-]);
-$chart->addDataset("Fail Rate (%)", $fail_rates, [
-	"background_colours" => "#F44336"
-]);
-$chart->setDatalabelSuffixes("%", "%");
-$charts[] = $chart;
-
-// Eye Contact Period
-$eye_contact_rates = array_values(array_map(function($period) {
-	if($period->testCount == 0) return [0, 0, 0];
-
-	$yes = round(($period->eyeContactCounts[0] / $period->testCount) * 100);
-	$no = 100 - $yes;
-	$na = 0;
-
-	return [$yes, $no, $na];
-}, $data));
-
-$chart = new Chart;
-$chart->addXAxis([
-	"type" => "category",
-	"stacked" => true,
-]);
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => 100],
-	"stacked" => true,
-]);
-$chart->setType("bar");
-$chart->setTitle("Eye Contact by {$resolution_name}");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("Yes (%)", array_column($eye_contact_rates, 0), [
-	"background_colours" => "#4CAF50"
-]);
-$chart->addDataset("No (%)", array_column($eye_contact_rates, 1), [
-	"background_colours" => "#F44336"
-]);
-$chart->setDatalabelSuffixes("%", "%");
-$charts[] = $chart;
-
-// Totals by Period
-
-$test_counts = array_column($data, "testCount");
-$pass_counts = array_column($data, "passCount");
-$fail_counts = array_column($data, "failCount");
-
-$chart = new Chart;
-$chart->setType("bar");
-$chart->setTitle("Totals by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => ceil(max($test_counts) / 10) * 10]
-]);
-$chart->addYAxis([
-	"position" => "right",
-	"id" => "y-axis-2",
-	"grid_lines" => false,
-	"tick_config" => ["min" => 0, "max" => 100]
-]);
-
-$chart->addDataset("Pass Rate (%)", $pass_rates, [
-	"border_colours" => "#FFEB3B",
-	"background_colours" => "transparent",
-	"type" => "line",
-	"y_axis_id" => "y-axis-2",
-	"datalabels" => [
-		"display" => false
-	],
-	"line_tension" => 0,
-]);
-$chart->addDataset("Test Count", $test_counts, [
-	"background_colours" => "#2196F3",
-	"type" => "bar",
-	"y_axis_id" => "y-axis-1",
-	"datalabels" => [
-		"display" => false
-	],
-]);
-$chart->addDataset("Pass", $pass_counts, [
-	"background_colours" => "#4CAF50",
-	"type" => "bar",
-	"y_axis_id" => "y-axis-1",
-	"datalabels" => [
-		"display" => false
-	],
-]);
-$chart->addDataset("Fail", $fail_counts, [
-	"background_colours" => "#F44336",
-	"type" => "bar",
-	"y_axis_id" => "y-axis-1",
-	"datalabels" => [
-		"display" => false
-	],
-]);
-$chart->setDatalabelSuffixes("%", "", "", "");
-$chart->print = true;
-$charts[] = $chart;
-
-// Point of Challenge (Each Period)
-
-foreach($keys as $index => $key) {
-	$key_label = $key_labels[$index];
-
-	$period_data = $data[$key];
-
-	if($period_data->testCount == 0) continue;
-
-	$chart = new Chart;
-	$chart->setType("pie");
-	$chart->setTitle("$key_label Point of Challenge");
-	$chart->setLabels(["On Entry", "While Browsing", "During Play", "On Exit", "No Challenge"]);
-	$chart->addDataset("Counts", [
-		$period_data->stage1Count,
-		$period_data->stage2Count,
-		$period_data->stage3Count,
-		$period_data->stage4Count,
-		$period_data->stage5Count,
-	], [
-		"background_colours" => [
-			"#4CAF50",
-			"#FFEB3B",
-			"#FBC02D",
-			"#FFAB91",
-			"#F44336",
-		],
-		"datalabels" => Chart::DATALABELS_BOX,
-	]);
-	$charts[] = $chart;
+/** @var ChartGenerator $generator */
+
+$charts[] = $generator->getTestsByStageChart();
+$charts[] = $generator->getChallengerGenderChart();
+$charts[] = $generator->getTesterGenderChart();
+$charts[] = $generator->getPassFailCountChart();
+$charts[] = $generator->getPeriodicPassFailRateChart();
+$charts[] = $generator->getPeriodicEyeContactChart();
+$charts[] = $generator->getPeriodicDoorSensorAlertPassRateChart();
+$charts[] = $generator->getPeriodicEyeContactPassRateChart();
+$charts[] = $generator->getPeriodicTotalsChart();
+$charts = array_merge($charts, $generator->getPointOfChallengeCharts());
+$charts[] = $generator->getPeriodicTesterGenderChart();
+$charts[] = $generator->getPeriodicTestCountChart();
+$charts = array_merge($charts, $generator->getGenderComparisonCharts());
+
+if($generator->hasRegionData()) {
+	$charts[] = $generator->getRegionPassRateChart();
+	$charts[] = $generator->getPeriodicRegionPassRateChart();
 }
 
-// Tester Genders by Period
-$male_counts = array_values(array_map(function($d) {
-	return $d->maleTesterCount;
-}, $data));
-
-$female_counts = array_values(array_map(function($d) {
-	return $d->femaleTesterCount;
-}, $data));
-
-$chart = new Chart;
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => ceil(max(max($male_counts), max($female_counts)) / 10) * 10]
-]);
-
-$chart->setType("bar");
-$chart->setTitle("Tester Gender by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("Male", $male_counts, [
-	"background_colours" => "#2196F3"
-]);
-$chart->addDataset("Female", $female_counts, [
-	"background_colours" => "#E91E63"
-]);
-$charts[] = $chart;
-
-// Test Count by Period
-$test_counts = array_values(array_map(function($d) {
-	return $d->testCount;
-}, $data));
-
-$chart = new Chart;
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => ceil(max($test_counts) / 10) * 10]
-]);
-$chart->setType("bar");
-$chart->setTitle("Tests by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("Tests", $test_counts, [
-	"background_colours" => "#2196F3"
-]);
-$charts[] = $chart;
-
-// Gender Graphs
-$gender_keys = [
-	"maleChallengeMale" => [
-		"title" => "Male Challenge Male",
-		"label" => "M Cha. M",
-	],
-	"maleChallengeFemale" => [
-		"title" => "Male Challenge Female",
-		"label" => "M Cha. F",
-	],
-	"femaleChallengeMale" => [
-		"title" => "Female Challenge Male",
-		"label" => "F Cha. M",
-	],
-	"femaleChallengeFemale" => [
-		"title" => "Female Challenge Female",
-		"label" => "F Cha. F",
-	],
-	"unknownChallenge" => [
-		"title" => "Gender Not Specified",
-		"label" => "Gender Not Specified",
-	],
-];
-
-$gender_test_counts = [];
-foreach($gender_keys as $gk => $gv) {
-	$gender_test_counts[] = array_sum(array_column($data, "{$gk}Count"));
+if($generator->hasAreaManagerData()) {
+	$charts[] = $generator->getAreaManagerPassRateChart();
+	$charts[] = $generator->getPeriodicAreaManagerPassRateChart();
 }
-
-// Gender Comparison by Date Range
-$chart = new Chart;
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => ceil(max($gender_test_counts) / 10) * 10]
-]);
-$chart->setType("bar");
-$chart->setTitle("Gender Comparison $date_range_label");
-$chart->setLabels(array_column($gender_keys, "label"));
-$chart->addDataset("Tests", $gender_test_counts, [
-	"background_colours" => "#2196F3"
-]);
-$charts[] = $chart;
-
-// Gender Comparison by Resolution
-$mcm_counts = array_column($data, "maleChallengeMaleCount");
-$mcf_counts = array_column($data, "maleChallengeFemaleCount");
-$fcm_counts = array_column($data, "femaleChallengeMaleCount");
-$fcf_counts = array_column($data, "femaleChallengeFemaleCount");
-$ns_counts = array_column($data, "unknownChallengeCount");
-
-$chart = new Chart;
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => ceil(max(max($mcm_counts), max($mcf_counts), max($fcm_counts), max($fcf_counts)) / 10) * 10]
-]);
-$chart->setType("bar");
-$chart->setTitle("Gender Comparison by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("M Cha. M", $mcm_counts, ["background_colours" => "#2196F3"]);
-$chart->addDataset("M Cha. F", $mcf_counts, ["background_colours" => "#3F51B5"]);
-$chart->addDataset("F Cha. M", $fcm_counts, ["background_colours" => "#9C27B0"]);
-$chart->addDataset("F Cha. F", $fcf_counts, ["background_colours" => "#E91E63"]);
-$chart->addDataset("Not Specified", $ns_counts, ["background_colours" => "#9E9E9E"]);
-$chart->print = true;
-$charts[] = $chart;
-
-// Gender Comparison Pass Rate by Resolution
-$mcm_pass_counts = array_column($data, "maleChallengeMalePassCount");
-$mcf_pass_counts = array_column($data, "maleChallengeFemalePassCount");
-$fcm_pass_counts = array_column($data, "femaleChallengeMalePassCount");
-$fcf_pass_counts = array_column($data, "femaleChallengeFemalePassCount");
-$ns_pass_counts = array_column($data, "unknownChallengePassCount");
-
-foreach(["mcm", "mcf", "fcm", "fcf", "ns"] as $prefix) {
-	$pass_rates = [];
-	$pass_counts = ${$prefix . "_pass_counts"};
-	$test_counts = ${$prefix . "_counts"};
-
-	foreach($test_counts as $index => $test_count) {
-		if($test_count == 0) {
-			$pass_rates[] = 0;
-			continue;
-		}
-		$pass_rates[] = number_format(($pass_counts[$index] * 100) / $test_count, 2);
-	}
-
-	${$prefix . "_pass_rates"} = $pass_rates;
-}
-
-$chart = new Chart;
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => 100],
-]);
-$chart->setType("bar");
-$chart->setTitle("Gender Comparison Pass Rate by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("M Cha. M", $mcm_pass_rates, ["background_colours" => "#2196F3", "datalabels" => ["display" => false],  "line_tension" => 0]);
-$chart->addDataset("M Cha. F", $mcf_pass_rates, ["background_colours" => "#3F51B5", "datalabels" => ["display" => false], "line_tension" => 0]);
-$chart->addDataset("F Cha. M", $fcm_pass_rates, ["background_colours" => "#9C27B0", "datalabels" => ["display" => false], "line_tension" => 0]);
-$chart->addDataset("F Cha. F", $fcf_pass_rates, ["background_colours" => "#E91E63", "datalabels" => ["display" => false], "line_tension" => 0]);
-$chart->addDataset("Not Specified", $ns_pass_rates, ["background_colours" => "#9E9E9E", "datalabels" => ["display" => false], "line_tension" => 0]);
-$chart->print = true;
-$chart->setDatalabelSuffixes("%", "%", "%", "%", "%");
-$charts[] = $chart;
-
-// Gender Comparison Point of Challenge
-foreach($keys as $index => $key) {
-	$key_label = $key_labels[$index];
-	$period_data = $data[$key];
-
-	foreach($gender_keys as $prefix => $gv) {
-
-		$title = $gv["label"];
-		$test_count = $period_data->{$prefix . "Count"};
-		$stage_data = $period_data->{$prefix . "Stages"};
-
-		if($test_count == 0) continue;
-
-		$chart = new Chart;
-		$chart->setType("pie");
-		$chart->setTitle("$key_label $title Point of Challenge");
-		$chart->setLabels(["On Entry", "While Browsing", "During Play", "On Exit", "No Challenge"]);
-		$chart->addDataset("Counts", $stage_data, [
-			"background_colours" => [
-				"#4CAF50",
-				"#FFEB3B",
-				"#FBC02D",
-				"#FFAB91",
-				"#F44336",
-			],
-			"datalabels" => Chart::DATALABELS_BOX,
-		]);
-		$charts[] = $chart;
-	}
-}
-
-// Region Graphs
-if($has_regions) {
-
-	ksort($region_data, SORT_NATURAL);
-
-	$region_keys = array_keys($region_data);
-
-	$x_data_labels = array_map(function($key) {
-		return "Region $key";
-	}, $region_keys);
-
-	// Region Pass Rate (Selected Date Range)
-	$data_values = [];
-
-	$test_counts = [];
-	$pass_counts = [];
-	$fail_counts = [];
-
-	foreach($region_data as $region => $r_data) {
-		$total_region_test_count = array_sum(array_column($r_data, "testCount"));
-		$total_region_pass_count = array_sum(array_column($r_data, "passCount"));
-
-		$test_counts[] = $total_region_test_count;
-		$pass_counts[] = $total_region_pass_count;
-		$fail_counts[] = $total_region_test_count - $total_region_pass_count;
-
-		$data_values[] = ($total_region_test_count == 0) ? 0 : round(($total_region_pass_count * 100) / $total_region_test_count);
-	}
-
-	$chart = new Chart;
-	$chart->addYAxis([
-		"id" => "y-axis-1",
-		"tick_config" => ["min" => 0, "max" => 100]
-	]);
-	$chart->setType("bar");
-	$chart->setTitle("Region Pass Rate $date_range_label");
-	$chart->setLabels($x_data_labels);
-	$chart->addDataset("Pass %", $data_values , [
-		"background_colours" => "#2196F3"
-	]);
-	$chart->addPrintDataset("Tests", $test_counts);
-	$chart->addPrintDataset("Pass", $pass_counts);
-	$chart->addPrintDataset("Fail", $fail_counts);
-
-	$chart->setDatalabelSuffixes("%");
-	$chart->print = true;
-	$chart->printTotalColumn = true;
-	$charts[] = $chart;
-
-	// Region Pass Rate Period
-	$chart = new Chart;
-	$chart->addYAxis([
-		"id" => "y-axis-1",
-		"tick_config" => ["min" => 0, "max" => 100]
-	]);
-	$chart->setType("bar");
-	$chart->setTitle("Region Pass Rate by $resolution_name");
-	$chart->setLabels($x_data_labels);
-
-	foreach($keys as $index => $key) {
-		$data_values = [];
-		foreach($region_keys as $region) {
-			$r_data = $region_data[$region][$key];
-			$data_values[] = ($r_data->testCount == 0) ? 0 : round(($r_data->passCount * 100) / $r_data->testCount);
-		}
-		$chart->addDataset($key_labels[$index], $data_values, ["background_colours" => Chart::COLOURS[$index]]);
-	}
-	$chart->setDatalabelSuffixes(...array_fill(0, count($keys), "%"));
-
-	$charts[] = $chart;
-
-}
-
-// Area Manager Graphs
-if($has_area_managers) {
-
-	ksort($area_manager_data, SORT_NATURAL);
-
-	$area_manager_keys = array_keys($area_manager_data);
-
-	$x_data_labels = array_map(function($key) {
-		return "$key";
-	}, $area_manager_keys);
-
-	// Area Pass Rate (Selected Date Range)
-	$data_values = [];
-
-	$test_counts = [];
-	$pass_counts = [];
-	$fail_counts = [];
-
-	foreach($area_manager_data as $area_manager => $a_data) {
-		$total_area_manager_test_count = array_sum(array_column($a_data, "testCount"));
-		$total_area_manager_pass_count = array_sum(array_column($a_data, "passCount"));
-		$total_area_manager_fail_count = array_sum(array_column($a_data, "failCount"));
-
-		$test_counts[] = $total_area_manager_test_count;
-		$pass_counts[] = $total_area_manager_pass_count;
-		$fail_counts[] = $total_area_manager_fail_count;
-
-		$data_values[] = ($total_area_manager_test_count == 0) ? 0 : round(($total_area_manager_pass_count * 100) / $total_area_manager_test_count);
-	}
-
-	$chart = new Chart;
-	$chart->addXAxis([
-		"type" => "category",
-		"scale_label_config" => [
-			"display" => true,
-			"labelString" => "Area Manager",
-		]
-	]);
-	$chart->addYAxis([
-		"id" => "y-axis-1",
-		"tick_config" => ["min" => 0, "max" => 100]
-	]);
-	$chart->setType("bar");
-	$chart->setTitle("Area Manager Pass Rate $date_range_label");
-	$chart->setLabels($x_data_labels);
-	$chart->addDataset("Pass %", $data_values , [
-		"background_colours" => "#2196F3"
-	]);
-	$chart->addPrintDataset("Tests", $test_counts);
-	$chart->addPrintDataset("Pass", $pass_counts);
-	$chart->addPrintDataset("Fail", $fail_counts);
-	$chart->setDatalabelSuffixes("%");
-	$chart->print = true;
-	$chart->printTotalColumn = true;
-	$charts[] = $chart;
-
-	// Area Pass Rate Period
-	$chart = new Chart;
-	$chart->addXAxis([
-		"type" => "category",
-		"scale_label_config" => [
-			"display" => true,
-			"labelString" => "Area Manager",
-		]
-	]);
-	$chart->addYAxis([
-		"id" => "y-axis-1",
-		"tick_config" => ["min" => 0, "max" => 100]
-	]);
-	$chart->setType("bar");
-	$chart->setTitle("Area Manager Pass Rate by $resolution_name");
-	$chart->setLabels($x_data_labels);
-
-	foreach($keys as $index => $key) {
-		$data_values = [];
-		foreach($area_manager_keys as $area_manager) {
-			$a_data = $area_manager_data[$area_manager][$key];
-			$data_values[] = ($a_data->testCount == 0) ? 0 : round(($a_data->passCount * 100) / $a_data->testCount);
-		}
-		$chart->addDataset($key_labels[$index], $data_values, [
-			"background_colours" => Chart::COLOURS[$index],
-			"datalabels" => [
-				"display" => false,
-			],
-		]);
-	}
-	$chart->setDatalabelSuffixes(...array_fill(0, count($keys), "%"));
-
-	$charts[] = $chart;
-
-}
-
-?>

+ 6 - 0
template_processing/age_verification/reports_create_empty_objects.php

@@ -8,6 +8,12 @@ $empty_data = (object) [
 
 	"eyeContactCounts" => [0, 0, 0],
 
+	"eyeContactPassCounts" => [0, 0, 0],
+	"eyeContactFailCounts" => [0, 0, 0],
+
+	"doorSensorAlertPassCounts" => [0, 0, 0],
+	"doorSensorAlertFailCounts" => [0, 0, 0],
+
 	"maleTesterCount" => 0,
 	"femaleTesterCount" => 0,
 

+ 42 - 0
template_processing/age_verification/reports_process_test.php

@@ -1,20 +1,61 @@
 <?php
 
+/**
+ * @var object $total_data Total data
+ * @var array $data Periodic data
+ * @var string $key Current period key
+ * @var string $region
+ * @var string $area_manager
+ * @var Test $test
+ * @var array $test_values
+ */
+
+$booleanPassFieldIncrementor = function($value, $pass, $prefix) use (&$data, $key) {
+
+	if($pass) {
+		$field = $prefix . "PassCounts";
+	}
+	else {
+		$field = $prefix . "FailCounts";
+	}
+
+	if($value === null) {
+		$index = 2;
+	}
+	else if($value) {
+		$index = 1;
+	}
+	else {
+		$index = 0;
+	}
+
+	$data[$key]->$field[$index]++;
+};
+
 $stage_key = "stage" . $test->challenge_stage . "Count";
 $data[$key]->$stage_key++;
 $total_data->{$stage_key}++;
 
+$door_sensor_alert = $test_values->door_sensor_alert ?? null;
+$eye_contact = $test->challenger_eye_contact ?? null;
+
 if($test->pass) {
 	$data[$key]->passCount++;
 	$total_data->passCount++;
 	if($region) $region_data[$region][$key]->passCount++;
 	if($area_manager) $area_manager_data[$area_manager][$key]->passCount++;
+
+	$booleanPassFieldIncrementor($eye_contact, true, "eyeContact");
+	$booleanPassFieldIncrementor($door_sensor_alert, true, "doorSensorAlert");
 }
 else {
 	$data[$key]->failCount++;
 	$total_data->failCount++;
 	if($region) $region_data[$region][$key]->failCount++;
 	if($area_manager) $area_manager_data[$area_manager][$key]->failCount++;
+
+	$booleanPassFieldIncrementor($eye_contact, false, "eyeContact");
+	$booleanPassFieldIncrementor($door_sensor_alert, false, "doorSensorAlert");
 }
 
 if($test->challenger_gender == "M") {
@@ -55,6 +96,7 @@ if($gender_prefix != "unknownChallenge") {
 	switch($tester->gender) {
 		case "M": $gender_prefix .= "Male"; break;
 		case "F": $gender_prefix .= "Female"; break;
+		default: $gender_prefix = "unknownChallenge"; break;
 	}
 }
 

+ 24 - 587
template_processing/age_verification_mitchells_butlers/reports_build_charts.php

@@ -1,592 +1,29 @@
 <?php
 
-// Tests by Stage
-
-$chart = new Chart;
-$chart->setType("doughnut");
-$chart->setTitle("Tests by Stage $date_range_label");
-$chart->setLabels(["1 - On Entry", "2 - While Browsing", "3 - During Play", "4 - On Exit", "5 - No Challenge"]);
-$chart->addDataset("Tests", [
-	$total_data->stage1Count,
-	$total_data->stage2Count,
-	$total_data->stage3Count,
-	$total_data->stage4Count,
-	$total_data->stage5Count,
-], [
-	"background_colours" => [
-		"#4CAF50",
-		"#FFEB3B",
-		"#FBC02D",
-		"#FFAB91",
-		"#F44336",
-	],
-	"datalabels" => Chart::DATALABELS_BOX,
-]);
-$chart->setPrintSuffixes("");
-$chart->print = true;
-$chart->printPercentages = true;
-$chart->printTotalColumn = true;
-$chart->setPrintLabels(["Stage 1", "Stage 2", "Stage 3", "Stage 4", "Stage 5"]);
-
-$charts[] = $chart;
-
-
-// Challenger Gender
-$chart = new Chart;
-$chart->setType("pie");
-$chart->setTitle("Staff Gender $date_range_label");
-$chart->setLabels(["Male", "Female", "Unspecified"]);
-$chart->addDataset("Counts", [
-	$total_data->maleChallengerCount,
-	$total_data->femaleChallengerCount,
-	$total_data->unspecifiedChallengerCount,
-], [
-	"background_colours" => [
-		"#2196F3",
-		"#E91E63",
-		"#9E9E9E",
-	],
-	"datalabels" => Chart::DATALABELS_BOX,
-]);
-$charts[] = $chart;
-
-// Tester Gender
-$chart = new Chart;
-$chart->setType("pie");
-$chart->setTitle("Tester Gender $date_range_label");
-$chart->setLabels(["Male", "Female"]);
-$chart->addDataset("Counts", [
-	$total_data->maleTesterCount,
-	$total_data->femaleTesterCount,
-], [
-	"background_colours" => [
-		"#2196F3",
-		"#E91E63",
-	],
-	"datalabels" => Chart::DATALABELS_BOX,
-]);
-$charts[] = $chart;
-
-// Pass / Fail
-$chart = new Chart;
-$chart->setType("pie");
-$chart->setTitle("Pass / Fail $date_range_label");
-$chart->setLabels(["Pass", "Fail"]);
-$chart->addDataset("Counts", [
-	$total_data->passCount,
-	$total_data->failCount,
-], [
-	"background_colours" => [
-		"#4CAF50",
-		"#F44336",
-	],
-	"datalabels" => Chart::DATALABELS_BOX,
-]);
-$charts[] = $chart;
-
-// Pass Rate Period
-$pass_rates = array_values(array_map(function($d) {
-	if($d->testCount == 0) return 0;
-	return round(($d->passCount / $d->testCount) * 100);
-}, $data));
-
-$fail_rates = array_values(array_map(function($d) {
-	if($d->testCount == 0) return 0;
-	$pass_rate = round(($d->passCount / $d->testCount) * 100);
-	return 100 - $pass_rate;
-}, $data));
-
-$chart = new Chart;
-$chart->addXAxis([
-	"type" => "category",
-	"stacked" => true,
-]);
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => 100],
-	"stacked" => true,
-]);
-
-$chart->setType("bar");
-$chart->setTitle("Pass / Fail by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("Pass Rate (%)", $pass_rates, [
-	"background_colours" => "#4CAF50"
-]);
-$chart->addDataset("Fail Rate (%)", $fail_rates, [
-	"background_colours" => "#F44336"
-]);
-$chart->setDatalabelSuffixes("%", "%");
-$charts[] = $chart;
-
-// Eye Contact Period
-$eye_contact_rates = array_values(array_map(function($period) {
-	if($period->testCount == 0) return [0, 0, 0];
-
-	$yes = round(($period->eyeContactCounts[0] / $period->testCount) * 100);
-	$no = 100 - $yes;
-	$na = 0;
-
-	return [$yes, $no, $na];
-}, $data));
-
-$chart = new Chart;
-$chart->addXAxis([
-	"type" => "category",
-	"stacked" => true,
-]);
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => 100],
-	"stacked" => true,
-]);
-$chart->setType("bar");
-$chart->setTitle("Eye Contact by {$resolution_name}");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("Yes (%)", array_column($eye_contact_rates, 0), [
-	"background_colours" => "#4CAF50"
-]);
-$chart->addDataset("No (%)", array_column($eye_contact_rates, 1), [
-	"background_colours" => "#F44336"
-]);
-$chart->setDatalabelSuffixes("%", "%");
-$charts[] = $chart;
-
-// Totals by Period
-
-$test_counts = array_column($data, "testCount");
-$pass_counts = array_column($data, "passCount");
-$fail_counts = array_column($data, "failCount");
-
-$chart = new Chart;
-$chart->setType("bar");
-$chart->setTitle("Totals by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => ceil(max($test_counts) / 10) * 10]
-]);
-$chart->addYAxis([
-	"position" => "right",
-	"id" => "y-axis-2",
-	"grid_lines" => false,
-	"tick_config" => ["min" => 0, "max" => 100]
-]);
-
-$chart->addDataset("Pass Rate (%)", $pass_rates, [
-	"border_colours" => "#FFEB3B",
-	"background_colours" => "transparent",
-	"type" => "line",
-	"y_axis_id" => "y-axis-2",
-	"datalabels" => [
-		"display" => false
-	],
-	"line_tension" => 0,
-]);
-$chart->addDataset("Test Count", $test_counts, [
-	"background_colours" => "#2196F3",
-	"type" => "bar",
-	"y_axis_id" => "y-axis-1",
-	"datalabels" => [
-		"display" => false
-	],
-]);
-$chart->addDataset("Pass", $pass_counts, [
-	"background_colours" => "#4CAF50",
-	"type" => "bar",
-	"y_axis_id" => "y-axis-1",
-	"datalabels" => [
-		"display" => false
-	],
-]);
-$chart->addDataset("Fail", $fail_counts, [
-	"background_colours" => "#F44336",
-	"type" => "bar",
-	"y_axis_id" => "y-axis-1",
-	"datalabels" => [
-		"display" => false
-	],
-]);
-$chart->setDatalabelSuffixes("%", "", "", "");
-$chart->print = true;
-$charts[] = $chart;
-
-// Point of Challenge (Each Period)
-
-foreach($keys as $index => $key) {
-	$key_label = $key_labels[$index];
-
-	$period_data = $data[$key];
-
-	if($period_data->testCount == 0) continue;
-
-	$chart = new Chart;
-	$chart->setType("pie");
-	$chart->setTitle("$key_label Point of Challenge");
-	$chart->setLabels(["On Entry", "While Browsing", "During Play", "On Exit", "No Challenge"]);
-	$chart->addDataset("Counts", [
-		$period_data->stage1Count,
-		$period_data->stage2Count,
-		$period_data->stage3Count,
-		$period_data->stage4Count,
-		$period_data->stage5Count,
-	], [
-		"background_colours" => [
-			"#4CAF50",
-			"#FFEB3B",
-			"#FBC02D",
-			"#FFAB91",
-			"#F44336",
-		],
-		"datalabels" => Chart::DATALABELS_BOX,
-	]);
-	$charts[] = $chart;
+/** @var ChartGenerator $generator */
+
+$charts[] = $generator->getTestsByStageChart();
+$charts[] = $generator->getChallengerGenderChart();
+$charts[] = $generator->getTesterGenderChart();
+$charts[] = $generator->getPassFailCountChart();
+$charts[] = $generator->getPeriodicPassFailRateChart();
+$charts[] = $generator->getPeriodicEyeContactChart();
+$charts[] = $generator->getPeriodicDoorSensorAlertPassRateChart();
+$charts[] = $generator->getPeriodicEyeContactPassRateChart();
+$charts[] = $generator->getPeriodicLineOfSightPassRateChart();
+$charts[] = $generator->getPeriodicBarPurchasePassRateChart();
+$charts[] = $generator->getPeriodicTotalsChart();
+$charts = array_merge($charts, $generator->getPointOfChallengeCharts());
+$charts[] = $generator->getPeriodicTesterGenderChart();
+$charts[] = $generator->getPeriodicTestCountChart();
+$charts = array_merge($charts, $generator->getGenderComparisonCharts());
+
+if($generator->hasRegionData()) {
+	$charts[] = $generator->getRegionPassRateChart();
+	$charts[] = $generator->getPeriodicRegionPassRateChart();
 }
 
-// Tester Genders by Period
-$male_counts = array_values(array_map(function($d) {
-	return $d->maleTesterCount;
-}, $data));
-
-$female_counts = array_values(array_map(function($d) {
-	return $d->femaleTesterCount;
-}, $data));
-
-$chart = new Chart;
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => ceil(max(max($male_counts), max($female_counts)) / 10) * 10]
-]);
-
-$chart->setType("bar");
-$chart->setTitle("Tester Gender by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("Male", $male_counts, [
-	"background_colours" => "#2196F3"
-]);
-$chart->addDataset("Female", $female_counts, [
-	"background_colours" => "#E91E63"
-]);
-$charts[] = $chart;
-
-// Test Count by Period
-$test_counts = array_values(array_map(function($d) {
-	return $d->testCount;
-}, $data));
-
-$chart = new Chart;
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => ceil(max($test_counts) / 10) * 10]
-]);
-$chart->setType("bar");
-$chart->setTitle("Tests by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("Tests", $test_counts, [
-	"background_colours" => "#2196F3"
-]);
-$charts[] = $chart;
-
-// Gender Graphs
-$gender_keys = [
-	"maleChallengeMale" => [
-		"title" => "Male Challenge Male",
-		"label" => "M Cha. M",
-	],
-	"maleChallengeFemale" => [
-		"title" => "Male Challenge Female",
-		"label" => "M Cha. F",
-	],
-	"femaleChallengeMale" => [
-		"title" => "Female Challenge Male",
-		"label" => "F Cha. M",
-	],
-	"femaleChallengeFemale" => [
-		"title" => "Female Challenge Female",
-		"label" => "F Cha. F",
-	],
-	"unknownChallenge" => [
-		"title" => "Gender Not Specified",
-		"label" => "Gender Not Specified",
-	],
-];
-
-$gender_test_counts = [];
-foreach($gender_keys as $gk => $gv) {
-	$gender_test_counts[] = array_sum(array_column($data, "{$gk}Count"));
+if($generator->hasAreaManagerData()) {
+	$charts[] = $generator->getAreaManagerPassRateChart();
+	$charts[] = $generator->getPeriodicAreaManagerPassRateChart();
 }
-
-// Gender Comparison by Date Range
-$chart = new Chart;
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => ceil(max($gender_test_counts) / 10) * 10]
-]);
-$chart->setType("bar");
-$chart->setTitle("Gender Comparison $date_range_label");
-$chart->setLabels(array_column($gender_keys, "label"));
-$chart->addDataset("Tests", $gender_test_counts, [
-	"background_colours" => "#2196F3"
-]);
-$charts[] = $chart;
-
-// Gender Comparison by Resolution
-$mcm_counts = array_column($data, "maleChallengeMaleCount");
-$mcf_counts = array_column($data, "maleChallengeFemaleCount");
-$fcm_counts = array_column($data, "femaleChallengeMaleCount");
-$fcf_counts = array_column($data, "femaleChallengeFemaleCount");
-$ns_counts = array_column($data, "unknownChallengeCount");
-
-$chart = new Chart;
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => ceil(max(max($mcm_counts), max($mcf_counts), max($fcm_counts), max($fcf_counts)) / 10) * 10]
-]);
-$chart->setType("bar");
-$chart->setTitle("Gender Comparison by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("M Cha. M", $mcm_counts, ["background_colours" => "#2196F3"]);
-$chart->addDataset("M Cha. F", $mcf_counts, ["background_colours" => "#3F51B5"]);
-$chart->addDataset("F Cha. M", $fcm_counts, ["background_colours" => "#9C27B0"]);
-$chart->addDataset("F Cha. F", $fcf_counts, ["background_colours" => "#E91E63"]);
-$chart->addDataset("Not Specified", $ns_counts, ["background_colours" => "#9E9E9E"]);
-$chart->print = true;
-$charts[] = $chart;
-
-// Gender Comparison Pass Rate by Resolution
-$mcm_pass_counts = array_column($data, "maleChallengeMalePassCount");
-$mcf_pass_counts = array_column($data, "maleChallengeFemalePassCount");
-$fcm_pass_counts = array_column($data, "femaleChallengeMalePassCount");
-$fcf_pass_counts = array_column($data, "femaleChallengeFemalePassCount");
-$ns_pass_counts = array_column($data, "unknownChallengePassCount");
-
-foreach(["mcm", "mcf", "fcm", "fcf", "ns"] as $prefix) {
-	$pass_rates = [];
-	$pass_counts = ${$prefix . "_pass_counts"};
-	$test_counts = ${$prefix . "_counts"};
-
-	foreach($test_counts as $index => $test_count) {
-		if($test_count == 0) {
-			$pass_rates[] = 0;
-			continue;
-		}
-		$pass_rates[] = number_format(($pass_counts[$index] * 100) / $test_count, 2);
-	}
-
-	${$prefix . "_pass_rates"} = $pass_rates;
-}
-
-$chart = new Chart;
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => 100],
-]);
-$chart->setType("bar");
-$chart->setTitle("Gender Comparison Pass Rate by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("M Cha. M", $mcm_pass_rates, ["background_colours" => "#2196F3", "datalabels" => ["display" => false],  "line_tension" => 0]);
-$chart->addDataset("M Cha. F", $mcf_pass_rates, ["background_colours" => "#3F51B5", "datalabels" => ["display" => false], "line_tension" => 0]);
-$chart->addDataset("F Cha. M", $fcm_pass_rates, ["background_colours" => "#9C27B0", "datalabels" => ["display" => false], "line_tension" => 0]);
-$chart->addDataset("F Cha. F", $fcf_pass_rates, ["background_colours" => "#E91E63", "datalabels" => ["display" => false], "line_tension" => 0]);
-$chart->addDataset("Not Specified", $ns_pass_rates, ["background_colours" => "#9E9E9E", "datalabels" => ["display" => false], "line_tension" => 0]);
-$chart->print = true;
-$chart->setDatalabelSuffixes("%", "%", "%", "%", "%");
-$charts[] = $chart;
-
-// Gender Comparison Point of Challenge
-foreach($keys as $index => $key) {
-	$key_label = $key_labels[$index];
-	$period_data = $data[$key];
-
-	foreach($gender_keys as $prefix => $gv) {
-
-		$title = $gv["label"];
-		$test_count = $period_data->{$prefix . "Count"};
-		$stage_data = $period_data->{$prefix . "Stages"};
-
-		if($test_count == 0) continue;
-
-		$chart = new Chart;
-		$chart->setType("pie");
-		$chart->setTitle("$key_label $title Point of Challenge");
-		$chart->setLabels(["On Entry", "While Browsing", "During Play", "On Exit", "No Challenge"]);
-		$chart->addDataset("Counts", $stage_data, [
-			"background_colours" => [
-				"#4CAF50",
-				"#FFEB3B",
-				"#FBC02D",
-				"#FFAB91",
-				"#F44336",
-			],
-			"datalabels" => Chart::DATALABELS_BOX,
-		]);
-		$charts[] = $chart;
-	}
-}
-
-// Region Graphs
-if($has_regions) {
-
-	ksort($region_data, SORT_NATURAL);
-
-	$region_keys = array_keys($region_data);
-
-	$x_data_labels = array_map(function($key) {
-		return "Region $key";
-	}, $region_keys);
-
-	// Region Pass Rate (Selected Date Range)
-	$data_values = [];
-
-	$test_counts = [];
-	$pass_counts = [];
-	$fail_counts = [];
-
-	foreach($region_data as $region => $r_data) {
-		$total_region_test_count = array_sum(array_column($r_data, "testCount"));
-		$total_region_pass_count = array_sum(array_column($r_data, "passCount"));
-
-		$test_counts[] = $total_region_test_count;
-		$pass_counts[] = $total_region_pass_count;
-		$fail_counts[] = $total_region_test_count - $total_region_pass_count;
-
-		$data_values[] = ($total_region_test_count == 0) ? 0 : round(($total_region_pass_count * 100) / $total_region_test_count);
-	}
-
-	$chart = new Chart;
-	$chart->addYAxis([
-		"id" => "y-axis-1",
-		"tick_config" => ["min" => 0, "max" => 100]
-	]);
-	$chart->setType("bar");
-	$chart->setTitle("Region Pass Rate $date_range_label");
-	$chart->setLabels($x_data_labels);
-	$chart->addDataset("Pass %", $data_values , [
-		"background_colours" => "#2196F3"
-	]);
-	$chart->addPrintDataset("Tests", $test_counts);
-	$chart->addPrintDataset("Pass", $pass_counts);
-	$chart->addPrintDataset("Fail", $fail_counts);
-
-	$chart->setDatalabelSuffixes("%");
-	$chart->print = true;
-	$chart->printTotalColumn = true;
-	$charts[] = $chart;
-
-	// Region Pass Rate Period
-	$chart = new Chart;
-	$chart->addYAxis([
-		"id" => "y-axis-1",
-		"tick_config" => ["min" => 0, "max" => 100]
-	]);
-	$chart->setType("bar");
-	$chart->setTitle("Region Pass Rate by $resolution_name");
-	$chart->setLabels($x_data_labels);
-
-	foreach($keys as $index => $key) {
-		$data_values = [];
-		foreach($region_keys as $region) {
-			$r_data = $region_data[$region][$key];
-			$data_values[] = ($r_data->testCount == 0) ? 0 : round(($r_data->passCount * 100) / $r_data->testCount);
-		}
-		$chart->addDataset($key_labels[$index], $data_values, ["background_colours" => Chart::COLOURS[$index]]);
-	}
-	$chart->setDatalabelSuffixes(...array_fill(0, count($keys), "%"));
-
-	$charts[] = $chart;
-
-}
-
-// Area Manager Graphs
-if($has_area_managers) {
-
-	ksort($area_manager_data, SORT_NATURAL);
-
-	$area_manager_keys = array_keys($area_manager_data);
-
-	$x_data_labels = array_map(function($key) {
-		return "$key";
-	}, $area_manager_keys);
-
-	// Area Pass Rate (Selected Date Range)
-	$data_values = [];
-
-	$test_counts = [];
-	$pass_counts = [];
-	$fail_counts = [];
-
-	foreach($area_manager_data as $area_manager => $a_data) {
-		$total_area_manager_test_count = array_sum(array_column($a_data, "testCount"));
-		$total_area_manager_pass_count = array_sum(array_column($a_data, "passCount"));
-		$total_area_manager_fail_count = array_sum(array_column($a_data, "failCount"));
-
-		$test_counts[] = $total_area_manager_test_count;
-		$pass_counts[] = $total_area_manager_pass_count;
-		$fail_counts[] = $total_area_manager_fail_count;
-
-		$data_values[] = ($total_area_manager_test_count == 0) ? 0 : round(($total_area_manager_pass_count * 100) / $total_area_manager_test_count);
-	}
-
-	$chart = new Chart;
-	$chart->addXAxis([
-		"type" => "category",
-		"scale_label_config" => [
-			"display" => true,
-			"labelString" => "Area Manager",
-		]
-	]);
-	$chart->addYAxis([
-		"id" => "y-axis-1",
-		"tick_config" => ["min" => 0, "max" => 100]
-	]);
-	$chart->setType("bar");
-	$chart->setTitle("Area Manager Pass Rate $date_range_label");
-	$chart->setLabels($x_data_labels);
-	$chart->addDataset("Pass %", $data_values , [
-		"background_colours" => "#2196F3"
-	]);
-	$chart->addPrintDataset("Tests", $test_counts);
-	$chart->addPrintDataset("Pass", $pass_counts);
-	$chart->addPrintDataset("Fail", $fail_counts);
-	$chart->setDatalabelSuffixes("%");
-	$chart->print = true;
-	$chart->printTotalColumn = true;
-	$charts[] = $chart;
-
-	// Area Pass Rate Period
-	$chart = new Chart;
-	$chart->addXAxis([
-		"type" => "category",
-		"scale_label_config" => [
-			"display" => true,
-			"labelString" => "Area Manager",
-		]
-	]);
-	$chart->addYAxis([
-		"id" => "y-axis-1",
-		"tick_config" => ["min" => 0, "max" => 100]
-	]);
-	$chart->setType("bar");
-	$chart->setTitle("Area Manager Pass Rate by $resolution_name");
-	$chart->setLabels($x_data_labels);
-
-	foreach($keys as $index => $key) {
-		$data_values = [];
-		foreach($area_manager_keys as $area_manager) {
-			$a_data = $area_manager_data[$area_manager][$key];
-			$data_values[] = ($a_data->testCount == 0) ? 0 : round(($a_data->passCount * 100) / $a_data->testCount);
-		}
-		$chart->addDataset($key_labels[$index], $data_values, [
-			"background_colours" => Chart::COLOURS[$index],
-			"datalabels" => [
-				"display" => false,
-			],
-		]);
-	}
-	$chart->setDatalabelSuffixes(...array_fill(0, count($keys), "%"));
-
-	$charts[] = $chart;
-
-}
-
-?>

+ 12 - 0
template_processing/age_verification_mitchells_butlers/reports_create_empty_objects.php

@@ -8,6 +8,18 @@ $empty_data = (object) [
 
 	"eyeContactCounts" => [0, 0, 0],
 
+	"eyeContactPassCounts" => [0, 0, 0],
+	"eyeContactFailCounts" => [0, 0, 0],
+
+	"lineOfSightPassCounts" => [0, 0, 0],
+	"lineOfSightFailCounts" => [0, 0, 0],
+
+	"doorSensorAlertPassCounts" => [0, 0, 0],
+	"doorSensorAlertFailCounts" => [0, 0, 0],
+
+	"barPurchasePassCounts" => [0, 0, 0],
+	"barPurchaseFailCounts" => [0, 0, 0],
+
 	"maleTesterCount" => 0,
 	"femaleTesterCount" => 0,
 

+ 48 - 0
template_processing/age_verification_mitchells_butlers/reports_process_test.php

@@ -1,20 +1,67 @@
 <?php
 
+/**
+ * @var object $total_data Total data
+ * @var array $data Periodic data
+ * @var string $key Current period key
+ * @var string $region
+ * @var string $area_manager
+ * @var Test $test
+ * @var array $test_values
+ */
+
+$booleanPassFieldIncrementor = function($value, $pass, $prefix) use (&$data, $key) {
+
+	if($pass) {
+		$field = $prefix . "PassCounts";
+	}
+	else {
+		$field = $prefix . "FailCounts";
+	}
+
+	if($value === null) {
+		$index = 2;
+	}
+	else if($value) {
+		$index = 1;
+	}
+	else {
+		$index = 0;
+	}
+
+	$data[$key]->$field[$index]++;
+};
+
 $stage_key = "stage" . $test->challenge_stage . "Count";
 $data[$key]->$stage_key++;
 $total_data->{$stage_key}++;
 
+$line_of_sight = $test_values->play_machine_line_of_sight ?? null;
+$bar_purchase = $test_values->bar_purchase ?? null;
+$door_sensor_alert = $test_values->door_sensor_alert ?? null;
+$eye_contact = $test->challenger_eye_contact ?? null;
+
 if($test->pass) {
 	$data[$key]->passCount++;
 	$total_data->passCount++;
 	if($region) $region_data[$region][$key]->passCount++;
 	if($area_manager) $area_manager_data[$area_manager][$key]->passCount++;
+
+	$booleanPassFieldIncrementor($eye_contact, true, "eyeContact");
+	$booleanPassFieldIncrementor($line_of_sight, true, "lineOfSight");
+	$booleanPassFieldIncrementor($bar_purchase, true, "barPurchase");
+	$booleanPassFieldIncrementor($door_sensor_alert, true, "doorSensorAlert");
 }
 else {
 	$data[$key]->failCount++;
 	$total_data->failCount++;
 	if($region) $region_data[$region][$key]->failCount++;
 	if($area_manager) $area_manager_data[$area_manager][$key]->failCount++;
+
+	$booleanPassFieldIncrementor($eye_contact, false, "eyeContact");
+	$booleanPassFieldIncrementor($line_of_sight, false, "lineOfSight");
+	$booleanPassFieldIncrementor($bar_purchase, false, "barPurchase");
+	$booleanPassFieldIncrementor($door_sensor_alert, false, "doorSensorAlert");
 }
 
 if($test->challenger_gender == "M") {
@@ -55,6 +102,7 @@ if($gender_prefix != "unknownChallenge") {
 	switch($tester->gender) {
 		case "M": $gender_prefix .= "Male"; break;
 		case "F": $gender_prefix .= "Female"; break;
+		default: $gender_prefix = "unknownChallenge"; break;
 	}
 }
 

+ 13 - 249
template_processing/mystery_shop/reports_build_charts.php

@@ -1,251 +1,15 @@
 <?php
 
-// Tests by Cleanliness
-
-$chart = new Chart;
-$chart->setType("doughnut");
-$chart->setTitle("Tests by Cleanliness $date_range_label");
-$chart->setLabels(["Very dirty", "Dirty", "Adequate", "Clean", "Very Clean"]);
-$chart->addDataset("Tests", [
-	$total_data->cleanlinessCounts[0],
-	$total_data->cleanlinessCounts[1],
-	$total_data->cleanlinessCounts[2],
-	$total_data->cleanlinessCounts[3],
-	$total_data->cleanlinessCounts[4],
-], [
-	"background_colours" => [
-		"#F44336",
-		"#FFAB91",
-		"#FBC02D",
-		"#FFEB3B",
-		"#4CAF50",
-	],
-	"datalabels" => Chart::DATALABELS_BOX,
-]);
-$chart->setPrintSuffixes("");
-$chart->print = true;
-$chart->printTotalColumn = true;
-$chart->printPercentages = true;
-
-$charts[] = $chart;
-
-// Cleanliness (Each Period)
-foreach($keys as $index => $key) {
-	$key_label = $key_labels[$index];
-
-	$period_data = $data[$key];
-
-	if($period_data->testCount == 0) continue;
-
-	$chart = new Chart;
-	$chart->setType("pie");
-	$chart->setTitle("$key_label Cleanliness");
-	$chart->setLabels(["Very dirty", "Dirty", "Adequate", "Clean", "Very Clean"]);
-	$chart->addDataset("Counts", [
-		$period_data->cleanlinessCounts[0],
-		$period_data->cleanlinessCounts[1],
-		$period_data->cleanlinessCounts[2],
-		$period_data->cleanlinessCounts[3],
-		$period_data->cleanlinessCounts[4],
-	], [
-		"background_colours" => [
-			"#F44336",
-			"#FFAB91",
-			"#FBC02D",
-			"#FFEB3B",
-			"#4CAF50",
-		],
-		"datalabels" => Chart::DATALABELS_BOX,
-	]);
-	$charts[] = $chart;
-}
-
-// Tester Gender
-$chart = new Chart;
-$chart->setType("pie");
-$chart->setTitle("Tester Gender $date_range_label");
-$chart->setLabels(["Male", "Female"]);
-$chart->addDataset("Counts", [
-	$total_data->maleTesterCount,
-	$total_data->femaleTesterCount,
-], [
-	"background_colours" => [
-		"#2196F3",
-		"#E91E63",
-	],
-	"datalabels" => Chart::DATALABELS_BOX,
-]);
-$charts[] = $chart;
-
-// Staff Badge Worn
-$staff_badge_worn_counts = array_column($data, "staffBadgeWornCounts");
-
-$unknown_counts = array_column($staff_badge_worn_counts, 0);
-$no_counts = array_column($staff_badge_worn_counts, 1);
-$yes_counts = array_column($staff_badge_worn_counts, 2);
-
-$chart = new Chart;
-$chart->setType("bar");
-$chart->setTitle("Staff Badge Worn by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("Don't know", $unknown_counts, [
-	"background_colours" => "#CCCCCC"
-]);
-$chart->addDataset("No", $no_counts, [
-	"background_colours" => "#F44336"
-]);
-$chart->addDataset("Yes", $yes_counts, [
-	"background_colours" => "#4CAF50"
-]);
-$charts[] = $chart;
-
-// Staff Offered Drink
-$staff_offered_drink_counts = array_column($data, "staffOfferedDrinkCounts");
-
-$no_counts = array_column($staff_offered_drink_counts, 0);
-$yes_counts = array_column($staff_offered_drink_counts, 1);
-
-$chart = new Chart;
-$chart->setType("bar");
-$chart->setTitle("Staff Offered Drink by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("No", $no_counts, [
-	"background_colours" => "#F44336"
-]);
-$chart->addDataset("Yes", $yes_counts, [
-	"background_colours" => "#4CAF50"
-]);
-$charts[] = $chart;
-
-// Staff Offered Promotion
-$staff_offered_promotion_counts = array_column($data, "staffOfferedPromotionCounts");
-
-$no_counts = array_column($staff_offered_promotion_counts, 0);
-$yes_counts = array_column($staff_offered_promotion_counts, 1);
-
-$chart = new Chart;
-$chart->setType("bar");
-$chart->setTitle("Staff Offered Promotion by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("No", $no_counts, [
-	"background_colours" => "#F44336"
-]);
-$chart->addDataset("Yes", $yes_counts, [
-	"background_colours" => "#4CAF50"
-]);
-$charts[] = $chart;
-
-// Staff Offered Help
-$staff_offered_help_counts = array_column($data, "staffOfferedHelpCounts");
-
-$no_counts = array_column($staff_offered_help_counts, 0);
-$yes_counts = array_column($staff_offered_help_counts, 1);
-
-$chart = new Chart;
-$chart->setType("bar");
-$chart->setTitle("Staff Offered Help by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("No", $no_counts, [
-	"background_colours" => "#F44336"
-]);
-$chart->addDataset("Yes", $yes_counts, [
-	"background_colours" => "#4CAF50"
-]);
-$charts[] = $chart;
-
-// Staff Behaviour (Each Period)
-foreach($keys as $index => $key) {
-	$key_label = $key_labels[$index];
-
-	$period_data = $data[$key];
-
-	if($period_data->testCount == 0) continue;
-
-	$chart = new Chart;
-	$chart->setType("pie");
-	$chart->setTitle("$key_label Staff Behaviour");
-	$chart->setLabels(["N/A", "Rude", "Slightly rude", "Neither rude or polite", "Polite", "Very polite"]);
-	$chart->addDataset("Counts", [
-		$period_data->staffBehaviourCounts[0],
-		$period_data->staffBehaviourCounts[1],
-		$period_data->staffBehaviourCounts[2],
-		$period_data->staffBehaviourCounts[3],
-		$period_data->staffBehaviourCounts[4],
-		$period_data->staffBehaviourCounts[5],
-	], [
-		"background_colours" => [
-			"#CCCCCC",
-			"#F44336",
-			"#FFAB91",
-			"#FBC02D",
-			"#FFEB3B",
-			"#4CAF50",
-		],
-		"datalabels" => Chart::DATALABELS_BOX,
-	]);
-	$charts[] = $chart;
-}
-
-// Staff Uniform
-$staff_uniform_counts = array_column($data, "staffUniformCounts");
-
-$no_counts = array_column($staff_uniform_counts, 0);
-$yes_counts = array_column($staff_uniform_counts, 1);
-
-$chart = new Chart;
-$chart->setType("bar");
-$chart->setTitle("Staff Uniform by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("No", $no_counts, [
-	"background_colours" => "#F44336"
-]);
-$chart->addDataset("Yes", $yes_counts, [
-	"background_colours" => "#4CAF50"
-]);
-$charts[] = $chart;
-
-// Tester Genders by Period
-$male_counts = array_values(array_map(function($d) {
-	return $d->maleTesterCount;
-}, $data));
-
-$female_counts = array_values(array_map(function($d) {
-	return $d->femaleTesterCount;
-}, $data));
-
-$chart = new Chart;
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => ceil(max(max($male_counts), max($female_counts)) / 10) * 10]
-]);
-
-$chart->setType("bar");
-$chart->setTitle("Tester Gender by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("Male", $male_counts, [
-	"background_colours" => "#2196F3"
-]);
-$chart->addDataset("Female", $female_counts, [
-	"background_colours" => "#E91E63"
-]);
-$charts[] = $chart;
-
-// Test Count by Period
-$test_counts = array_values(array_map(function($d) {
-	return $d->testCount;
-}, $data));
-
-$chart = new Chart;
-$chart->addYAxis([
-	"id" => "y-axis-1",
-	"tick_config" => ["min" => 0, "max" => ceil(max($test_counts) / 10) * 10]
-]);
-$chart->setType("bar");
-$chart->setTitle("Tests by $resolution_name");
-$chart->setLabels($x_data_labels);
-$chart->addDataset("Tests", $test_counts, [
-	"background_colours" => "#2196F3"
-]);
-$charts[] = $chart;
-
-?>
+/** @var ChartGenerator $generator */
+
+$charts[] = $generator->getCleanlinessChart();
+$charts = array_merge($charts, $generator->getPeriodicCleanlinessCharts());
+$charts[] = $generator->getTesterGenderChart();
+$charts[] = $generator->getPeriodicStaffBadgeWornChart();
+$charts[] = $generator->getPeriodicStaffOfferedDrinkChart();
+$charts[] = $generator->getPeriodicStaffOfferedPromotionChart();
+$charts[] = $generator->getPeriodicStaffOfferedHelpChart();
+$charts = array_merge($charts, $generator->getPeriodicStaffBehaviourCharts());
+$charts[] = $generator->getPeriodicStaffUniformChart();
+$charts[] = $generator->getPeriodicTesterGenderChart();
+$charts[] = $generator->getPeriodicTestCountChart();

+ 12 - 1
views/customer_select.php

@@ -8,6 +8,17 @@
 	$uri_parts = explode("?", $uri);
 	$path = array_shift($uri_parts);
 
+	if(Core::$user->isAdmin() && Core::$allow_all_customers) {
+		$query = $_GET;
+		unset($query["path"]);
+		$query["customer_id"] = "ALL";
+		?>
+		<a class="list-group-item list-group-item-action" href="<?=htmlspecialchars($path)?>?<?=http_build_query($query)?>">
+			<?=__("All")?>
+		</a>
+		<?php
+	}
+
 	foreach($customers as $customer) {
 		$query = $_GET;
 		unset($query["path"]);
@@ -23,4 +34,4 @@
 	?>
 	</div>
 
-</div>
+</div>

+ 16 - 92
views/location.php

@@ -1,9 +1,10 @@
 <?php
-$tabs = [
-	["details", "Details"],
-	["photos", "Photos"],
-	["tests", "Tests"],
-];
+
+$tabs = [];
+$tabs[] = ["details", __("Details")];
+if(Core::$user->isAdmin()) $tabs[] = ["photos", __("Photos")];
+$tabs[] = ["tests", __("Tests")];
+if(Core::$user->isAdmin()) $tabs[] = ["log", __("Log")];
 
 $details = [
 	"ID" => $location->id,
@@ -18,12 +19,10 @@ if($location->region) $details["Region"] = $location->region;
 if($location->internal_id) $details["Internal ID"] = $location->internal_id;
 if($location->area_manager) $details["Area Manager"] = $location->area_manager;
 
-$photos = $location->getPhotos();
 $venue_types = $location->getVenueTypes();
 $type_names = array_column($venue_types, "name");
 $type_names_csv = implode(", ", $type_names);
 
-
 if($venue_types) $details["Types"] = $type_names_csv;
 
 ?>
@@ -86,94 +85,19 @@ if($venue_types) $details["Types"] = $type_names_csv;
 				</div>
 			</div>
 		</div>
-		<div class="tab-pane fade" id="photos" role="tabpanel" aria-labelledby="photos-tab">
+
 		<?php
-		if(empty($photos)) {
-			?>
-			<div class="alert alert-info">
-				<i class="fal fa-fw fa-info-circle"></i> No photos are available for this location.
-			</div>
-			<?php
+		if(Core::$user->isAdmin()) {
+			View::include("location_photos_tab", compact("location"));
 		}
-		else {
-			?>
-			<div class="row">
-			<?php
-			foreach($photos as $photo) {
-				$uri = "/account/locations/$location->id/photos/$photo->id";
-				?>
-				<div class="col-md-4">
-					<a href="<?=$uri?>">
-						<img class="border img-fluid img-contain" src="/img/blank_4_3.png" style="background-image: url(<?=$uri?>)" />
-					</a>
-				</div>
-				<?php
-			}
-			?>
-			</div>
-			<?php
+
+		View::include("location_tests_tab", compact("location"));
+
+		if(Core::$user->isAdmin()) {
+			View::include("location_log_tab", compact("location"));
 		}
 		?>
-		</div>
-		<div class="tab-pane fade" id="tests" role="tabpanel" aria-labelledby="tests-tab">
-			<?php
-			if(empty($tests)) {
-				?>
-				<div class="alert alert-info">
-					This location has no tests.
-				</div>
-				<?php
-			}
-			else {
-				?>
-				<table class="table table-hover">
-					<thead>
-						<tr>
-							<th>ID</th>
-							<th>Project</th>
-							<th>Status</th>
-							<th></th>
-						</tr>
-					</thead>
-					<tbody>
-					<?php
-					foreach($tests as $test) {
-						$project = $test->getProject();
-						?>
-						<tr>
-							<td class="text-right align-middle">
-								<?=$test->id?>
-							</td>
-							<td class="align-middle">
-								<a href="/account/projects/<?=$project->id?>"><?=htmlspecialchars($project->name)?></a>
-							</td>
-							<td class="align-middle">
-								<span class="badge badge-lg badge-<?=$test->getStatusClass()?>"><?=htmlspecialchars($test->getStatusText())?></span>
-							</td>
-							<td class="text-right">
-							<?php
-							if($test->status >= Test::STATUS_PENDING_VERIFICATION) {
-								?>
-								<a class="btn btn-outline-primary" href="/account/tests/<?=$test->id?>">View Results</a>
-								<?php
-							}
-							else {
-								?>
-								<a class="btn btn-outline-primary" href="/account/projects/<?=$test->project_id?>">View Project</a>
-								<?php
-							}
-							?>
-							</td>
-						</tr>
-						<?php
-					}
-					?>
-					</tbody>
-				</table>
-				<?php
-			}
-			?>
-		</div>
+
 	</div>
 
-</div>
+</div>

+ 66 - 48
views/location_form.php

@@ -1,9 +1,12 @@
 <?php
 $tabs = [
 	["details", "Details"],
-	["photos", "Photos"],
 ];
 
+if(Core::$user->isAdmin()) {
+	$tabs[] = ["photos", "Photos"];
+}
+
 $venue_types = VenueType::getAll();
 $venue_type_count = count($venue_types);
 $venue_type_columns = array_chunk($venue_types, ceil($venue_type_count / 2));
@@ -116,13 +119,22 @@ if($location->id) {
 							</div>
 						</div>
 
+                        <div class="row mb-1">
+                            <div class="col-sm offset-sm-4">
+                                <div class="form-check">
+                                    <input class="form-check-input" type="checkbox" name="do_not_test" id="do-not-test" value="1" <?=Form::checked($location->do_not_test)?> />
+                                    <label for="do-not-test">Do Not Test</label>
+                                </div>
+                            </div>
+                        </div>
+
 						<div class="row mb-1">
 							<div class="col-sm offset-sm-4">
 								<div class="form-check">
 									<input class="form-check-input" type="checkbox" name="closed" id="closed" value="1" <?=Form::checked($location->closed)?> />
 									<label for="closed">Closed</label>
 								</div>
-								<small class="text-muted form-text">By marking a location as closed, they will no longer appear for selection in new Projects.</small>
+								<small class="text-muted form-text">By marking a location as closed, the location will be unable to be selected for any new tests.</small>
 							</div>
 						</div>
 					</div>
@@ -139,7 +151,7 @@ if($location->id) {
 						}
 						else {
 							?>
-							<div class="mb-3" id="map" style="height: 330px;" data-maps data-lat="<?=$location->latitude?>" data-lng="<?=$location->longitude?>" data-zoom="14" data-marker="true" data-marker-draggable="true" data-marker-dragend-target="#map-data"></div>
+							<div class="mb-3" id="map" style="height: 330px;" data-maps data-lat="<?=$location->latitude?>" data-lng="<?=$location->longitude?>" data-zoom="15" data-marker="true" data-marker-draggable="true" data-marker-dragend-target="#map-data"></div>
 
 							<div id="map-data">
 								<input type="hidden" name="latitude" data-latitude value="<?=$location->latitude?>" />
@@ -212,72 +224,78 @@ if($location->id) {
 				</div>
 			</div>
 
-			<div class="tab-pane fade" id="photos" role="tabpanel" aria-labelledby="photos-tab">
-				<div class="row">
-					<div class="col-lg">
-						<div class="row mb-1">
-							<label class="col-sm-4 col-form-label" for="shop-left">Shop Name (Left)</label>
-							<div class="col-sm">
-								<input class="form-control" type="text" name="shop_left" id="shop-left" placeholder="Enter shop name (left)" value="<?=htmlspecialchars($location->shop_left)?>" />
+			<?php
+			if(Core::$user->isAdmin()) {
+				?>
+
+				<div class="tab-pane fade" id="photos" role="tabpanel" aria-labelledby="photos-tab">
+					<div class="row">
+						<div class="col-lg">
+							<div class="row mb-1">
+								<label class="col-sm-4 col-form-label" for="shop-left">Shop Name (Left)</label>
+								<div class="col-sm">
+									<input class="form-control" type="text" name="shop_left" id="shop-left" placeholder="Enter shop name (left)" value="<?=htmlspecialchars($location->shop_left)?>" />
+								</div>
 							</div>
-						</div>
-						<div class="row mb-1">
-							<label class="col-sm-4 col-form-label" for="shop-right">Shop Name (Right)</label>
-							<div class="col-sm">
-								<input class="form-control" type="text" name="shop_right" id="shop-right" placeholder="Enter shop name (right)" value="<?=htmlspecialchars($location->shop_right)?>" />
+							<div class="row mb-1">
+								<label class="col-sm-4 col-form-label" for="shop-right">Shop Name (Right)</label>
+								<div class="col-sm">
+									<input class="form-control" type="text" name="shop_right" id="shop-right" placeholder="Enter shop name (right)" value="<?=htmlspecialchars($location->shop_right)?>" />
+								</div>
 							</div>
-						</div>
 
-					</div>
-					<div class="col-lg">
-					<?php
-					if($location->id) {
-						?>
-						<div class="row mb-3">
-							<label class="col-sm-4 col-form-label" for="photo">JPEG File</label>
-							<div class="col-sm">
-								<input class="form-control-file" type="file" name="photo" id="photo" />
-							</div>
 						</div>
+						<div class="col-lg">
 						<?php
-						if(!empty($photos)) {
+						if($location->id) {
 							?>
-							<h3>Manage Photos</h3>
-
-							<div class="row">
+							<div class="row mb-3">
+								<label class="col-sm-4 col-form-label" for="photo">JPEG File</label>
+								<div class="col-sm">
+									<input class="form-control-file" type="file" name="photo" id="photo" />
+								</div>
+							</div>
 							<?php
-							foreach($photos as $photo) {
+							if(!empty($photos)) {
 								?>
-								<div class="col-md-6">
-									<div class="card">
-										<img class="card-img-top img-cover" src="/img/blank_4_3.png" alt="Photo" style="background-image: url(/account/locations/6/photos/<?=$photo->id?>)" />
-										<div class="card-body">
-											<div class="form-check">
-												<input class="form-check-input" type="checkbox" name="delete_file_ids[]" id="photo-<?=$photo->id?>" value="<?=$photo->id?>" />
-												<label class="form-check-label" for="photo-<?=$photo->id?>">Delete</label>
+								<h3>Manage Photos</h3>
+
+								<div class="row">
+								<?php
+								foreach($photos as $photo) {
+									?>
+									<div class="col-md-6">
+										<div class="card">
+											<img class="card-img-top img-cover" src="/img/blank_4_3.png" alt="Photo" style="background-image: url(/account/locations/6/photos/<?=$photo->id?>)" />
+											<div class="card-body">
+												<div class="form-check">
+													<input class="form-check-input" type="checkbox" name="delete_file_ids[]" id="photo-<?=$photo->id?>" value="<?=$photo->id?>" />
+													<label class="form-check-label" for="photo-<?=$photo->id?>">Delete</label>
+												</div>
 											</div>
 										</div>
 									</div>
+									<?php
+								}
+								?>
 								</div>
 								<?php
 							}
+						}
+						else {
 							?>
+							<div class="alert alert-info">
+								<i class="fal fa-fw fa-info-circle"></i> Adding photos will become available when location is added.
 							</div>
 							<?php
 						}
-					}
-					else {
 						?>
-						<div class="alert alert-info">
-							<i class="fal fa-fw fa-info-circle"></i> Adding photos will become available when location is added.
 						</div>
-						<?php
-					}
-					?>
 					</div>
 				</div>
-			</div>
-
+				<?php
+			}
+			?>
 		</div>
 
 		<div class="row">
@@ -293,4 +311,4 @@ if($location->id) {
 		</div>
 
 	</form>
-</div>
+</div>

+ 57 - 0
views/location_log_tab.php

@@ -0,0 +1,57 @@
+
+<?php
+/**
+ * @var Location $location
+ */
+
+$entries = $location->getUpdateLogEntries();
+
+?>
+<div class="tab-pane fade" id="log" role="tabpanel" aria-labelledby="log-tab">
+<?php
+if(empty($entries)) {
+    ?>
+    <div class="alert alert-info">
+        <i class="fal fa-fw fa-info-circle"></i> No log entries to display for this location.
+    </div>
+    <?php
+}
+else {
+    ?>
+    <table class="table table-sm table-bordered">
+        <thead>
+            <tr>
+                <th>Date/Time</th>
+                <th>User</th>
+                <th>Field</th>
+                <th>Before</th>
+                <th>After</th>
+            </tr>
+        </thead>
+        <tbody>
+            <?php
+            foreach($entries as $entry) {
+                $user = $entry->getUser();
+                $dts = Util::getDisplayDateTimeFromUTC($entry->dts);
+                $modifications = $entry->getModifications();
+                foreach($modifications as $modification) {
+                    ?>
+                    <tr>
+                        <td><?=htmlspecialchars($dts)?></td>
+                        <td><a href="<?=htmlspecialchars($user->getURL())?>"><?=htmlspecialchars($user->email)?></a></td>
+                        <td class="text-monospace"><?=htmlspecialchars($modification->field)?></td>
+                        <td class="text-monospace"><?=htmlspecialchars($modification->before)?></td>
+                        <td class="text-monospace"><?=htmlspecialchars($modification->after)?></td>
+                    </tr>
+                    <?php
+                }
+                ?>
+                <?php
+            }
+            ?>
+        </tbody>
+    </table>
+    <?php
+}
+?>
+</div>

+ 38 - 0
views/location_photos_tab.php

@@ -0,0 +1,38 @@
+
+<?php
+/**
+ * @var Location $location
+ */
+
+$photos = $location->getPhotos();
+
+?>
+<div class="tab-pane fade" id="photos" role="tabpanel" aria-labelledby="photos-tab">
+<?php
+if(empty($photos)) {
+    ?>
+    <div class="alert alert-info">
+        <i class="fal fa-fw fa-info-circle"></i> No photos are available for this location.
+    </div>
+    <?php
+}
+else {
+    ?>
+    <div class="row">
+    <?php
+    foreach($photos as $photo) {
+        $uri = "/account/locations/$location->id/photos/$photo->id";
+        ?>
+        <div class="col-md-4">
+            <a href="<?=$uri?>">
+                <img class="border img-fluid img-contain" src="/img/blank_4_3.png" style="background-image: url(<?=$uri?>)" />
+            </a>
+        </div>
+        <?php
+    }
+    ?>
+    </div>
+    <?php
+}
+?>
+</div>

+ 162 - 0
views/location_tests_tab.php

@@ -0,0 +1,162 @@
+<?php
+/**
+ * @var Location $location
+ */
+
+if(Core::$user->isAdmin()) {
+    $tests = $location->getTests();
+}
+else {
+    $tests = $location->getCompletedTests();
+}
+
+?>
+
+<div class="tab-pane fade" id="tests" role="tabpanel" aria-labelledby="tests-tab">
+    <?php
+    if(empty($tests)) {
+        ?>
+        <div class="alert alert-info">
+            This location has no tests.
+        </div>
+        <?php
+    }
+    else {
+        ?>
+        <table class="table table-bordered table-hover">
+            <thead>
+                <tr>
+                    <th>ID</th>
+                    <?php
+                    if(Core::$user->isAdmin()) {
+                        ?>
+                        <th>Project</th>
+                        <?php
+                    }
+                    else {
+                        ?>
+                        <th>Date/Time</th>
+                        <?php
+                    }
+                    ?>
+                    <th>Status</th>
+                    <th>Result</th>
+                    <th>Challenge Stage</th>
+                    <th>PDF</th>
+                    <?php
+                    if(Core::$user->isAdmin()) {
+                        ?>
+                        <th>Actions</th>
+                        <?php
+                    }
+                    ?>
+                </tr>
+            </thead>
+            <tbody>
+            <?php
+            foreach($tests as $test) {
+                $project = $test->getProject();
+                $template = $project->getTemplate();
+                $has_pass_fail = $template->hasPassFail();
+
+                $pass_text = $test->getPassText();
+                $pass_class = $test->getPassClass();
+                $pass_icon = $test->getPassIcon();
+
+                $challenge_stage = $test->challenge_stage;
+                $challenge_stage_text = $test->getChallengeStageText();
+                ?>
+                <tr>
+                    <td class="text-right align-middle">
+                        <?=$test->id?>
+                    </td>
+                    <td>
+                        <?php
+                        if(Core::$user->isAdmin()) {
+                            ?>
+                            <a href="/account/projects/<?=$project->id?>"><?=htmlspecialchars($project->name)?></a>
+                            <?php
+                        }
+                        else {
+                            echo Util::getDisplayDateTimeFromUTC($test->dts_start);
+                        }
+                        ?>
+                    </td>
+                    <td class="text-center">
+                        <span class="badge badge-lg badge-<?=$test->getStatusClass()?>"><?=htmlspecialchars($test->getStatusText())?></span>
+                    </td>
+                    <td class="text-center">
+                    <?php
+                    if($has_pass_fail) {
+                        ?>
+                        <strong class="text-<?=$pass_class?>"><?=htmlspecialchars($pass_text)?></strong>
+                        <?php
+                    }
+                    else {
+                        echo htmlspecialchars(__("N/A"));
+                    }
+                    ?>
+                    </td>
+                    <td>
+                    <?php
+                    if($has_pass_fail) {
+                        if($test->isPending()) {
+                            ?>
+                            <?=htmlspecialchars(__("Pending"))?>
+                            <?php
+                        }
+                        else {
+                            ?>
+                            <strong class="text-<?=$pass_class?>"><?=htmlspecialchars(__("Stage %d", $challenge_stage))?></strong> -
+                            <?=htmlspecialchars($challenge_stage_text)?>
+                            <?php
+                        }
+                    }
+                    else {
+                        echo htmlspecialchars(__("N/A"));
+                    }
+                    ?>
+                    </td>
+                    <td>
+                    <?php
+                    if($test->hasPDF()) {
+                        $pdf_url = $test->getPDFUrl();
+                        ?>
+                        <a href="<?=htmlspecialchars($pdf_url)?>" target="_blank">View PDF</a>
+                        <?php
+                    }
+                    else {
+                        echo htmlspecialchars(__("No PDF available"));
+                    }
+                    ?>
+                    </td>
+                    <?php
+                    if(Core::$user->isAdmin()) {
+                        ?>
+                        <td>
+                        <?php
+                        if($test->status >= Test::STATUS_PENDING_VERIFICATION) {
+                            ?>
+                            <a href="/account/tests/<?=$test->id?>">View Results</a>
+                            <?php
+                        }
+                        else {
+                            ?>
+                            <a href="/account/projects/<?=$test->project_id?>">View Project</a>
+                            <?php
+                        }
+                        ?>
+                        </td>
+                        <?php
+                    }
+                    ?>
+                </tr>
+                <?php
+            }
+            ?>
+            </tbody>
+        </table>
+        <?php
+    }
+    ?>
+</div>

Some files were not shown because too many files changed in this diff