Просмотр исходного кода

Remove "Travel Costs" modal; allow verifiers to manually enter travel costs

Alan Lam 5 лет назад
Родитель
Сommit
58ec5f51d5

+ 8 - 448
controllers/test.php

@@ -1,7 +1,7 @@
 <?php /** @noinspection PhpUnhandledExceptionInspection */
 
 /**
- * @var Test $test
+ * @var int $id
  */
 
 Core::addScript("public/js/app-test.js");
@@ -9,14 +9,8 @@ Core::addScript("public/js/app-test.js");
 $test = Test::get($id);
 if(!$test) throw new Exception(__("Test cannot be found."));
 
-$is_confirmed = $test->status == Test::STATUS_CONFIRMED;
-$is_started = $test->status == Test::STATUS_STARTED;
-$is_unverified = $test->status == Test::STATUS_PENDING_VERIFICATION;
-
 $location = $test->getLocation();
 $project = $test->getProject();
-$customer = $project->getCustomer();
-$tester = $test->getTester();
 $template = $project->getTemplate();
 
 $template_overrides = $project->getTemplateOverrides();
@@ -27,453 +21,19 @@ $template->setKeys($template_keys);
 
 $page_title = $location->name;
 
+$user = Core::$user;
+
 Core::addBreadcrumb("/account", "Account");
 Core::addBreadcrumb("/account/tests", "Tests");
 Core::addBreadcrumb("/account/tests/$id", $page_title);
 
-// Do test
-if(Core::$user->isTester()) {
-
-	Core::$show_footer_content = false;
-
-	if(Core::$user->id != $test->tester_id) throw new Exception(__("You do not have permission to view this page."));
-	if($test->status == Test::STATUS_ASSIGNED) throw new Exception(__("You do not have permission to view this page as you have not accepted the test yet."));
-
-	// Show completed message
-	if($test->status > Test::STATUS_PENDING_VERIFICATION) {
-		View::includeOnce("header", compact("page_title"));
-		View::include("test_form", compact("test", "location", "project", "template"));
-		View::includeOnce("footer");
-		return;
-	}
-
-	$json = json_decode($template->getJSON());
-
-	$submit = http::value("submit");
-	if($submit) {
-
-		$previous_timezone = date_default_timezone_get();
-
-		try {
-			Core::validateCSRFToken($submit);
-
-			$form_exception = new FormException;
-
-			if($is_confirmed) {
-				// Parse before the test form
-				$fields = $json->beforeTest;
-
-			}
-
-			if($is_started || $is_unverified) {
-				// Parse after the test form
-				$fields = $json->duringTest;
-
-				// Start/End times
-				if($is_started) {
-					$start_override = http::getDateTimeFromFields("start_override");
-					$end_override = http::getDateTimeFromFields("end_override");
-
-					$start_unix = null;
-					$end_unix = null;
-
-					if($start_override && $end_override) {
-						$start_unix = strtotime($start_override);
-						$end_unix = strtotime($end_override);
-
-						if($start_unix > $end_unix) $form_exception->addError(__("Entry Time must not be after Exit Time."));
-						if(!$start_unix && $end_unix && $test->dts_start) {
-							$recorded_start_unix = Util::getUnixTimeFromUTC($test->dts_start);
-							if($end_unix < $recorded_start_unix) $form_exception->addError(__("Exit Time cannot be later than the recorded Entry Time."));
-						}
-					}
-					else {
-						$form_exception->addError(__("Entry Time and Exit Time must be filled in."));
-					}
-
-				}
-
-			}
-
-			foreach($fields as $field) {
-
-				$name = $field->name ?? false;
-				if(empty($name)) continue; // Not a field
-
-				$required_key = $field->requiredKey ?? null;
-				if($required_key && !in_array($required_key, $template_keys)) continue;
-
-				$label = $field->label ?? "";
-				$type = $field->type;
-				$required = $field->required ?? false;
-				$values = $field->values ?? [];
-
-				if($type == "file") {
-					$file = (object) $_FILES[$name];
-
-					try {
-						if(!$required && $file->error == UPLOAD_ERR_NO_FILE) continue;
-						if($required && $file->error == UPLOAD_ERR_NO_FILE) {
-							throw new Exception("$label is required.");
-						}
-
-						// Detect upload error
-						if($file->error != UPLOAD_ERR_OK) throw new Exception(HTTP::getUploadErrorString($file->error));
-
-						// Get image details
-						$size = @getimagesize($file->tmp_name);
-						if(!$size) throw new Exception(sprintf(__("The uploaded file for %s is not an image."), $label));
-						list($width, $height, $type) = $size;
-						if($type != IMAGETYPE_JPEG) throw new Exception(sprintf(__("The uploaded file for %s is not a JPEG."), $label));
-
-						// Resize image
-						$output_image = Image::normalise($file->tmp_name);
-
-						// Write image to disk
-						$output_path = $test->getDirectory() . "/" . $name . ".jpg";
-
-						imagejpeg($output_image, $output_path, 60);
-						imagedestroy($output_image);
-					}
-					catch(Exception $e) {
-						$form_exception->addError($e->getMessage());
-					}
-				}
-				else {
-					$value = http::value($name, "trim");
-
-					if($required && $value === null) $form_exception->addError(sprintf(__("%s is required."), $label));
-					if($values && !in_array($value, $values)) $form_exception->addError(sprintf(__("Value for %s is invalid."), $label));
-
-					if(in_array($name, Test::TEST_FIELDS)) {
-						$test->$name = $value;
-					}
-					else {
-						$test_value = TestValue::get($test->id, $name);
-						if(!$test_value) {
-							$test_value = new TestValue;
-							$test_value->test_id = $test->id;
-							$test_value->name = $name;
-						}
-						$test_value->value = $value;
-						$success = $test_value->commit();
-						if(!$success) $form_exception->addError(sprintf(__("Failed to save value for %s."), $label));
-					}
-				}
-
-			}
-
-			if($form_exception->hasErrors()) throw $form_exception;
-
-			date_default_timezone_set("UTC");
-
-			// Before the Test
-			if($is_confirmed) {
-				$test->status = Test::STATUS_STARTED;
-				$test->dts_start = Util::getDateTime();
-				$test->dts_updated = Util::getDateTime();
-				$success = $test->commit();
-				if(!$success) throw new Exception(__("Failed to save test. Please try again later."));
-
-				Core::addAlert("success", __("Photos uploaded successfully."));
-
-				HTTP::redirect("/account/tests/$id");
-
-			}
-
-			// During the test
-			if($is_started || $is_unverified) {
-				$test->status = Test::STATUS_PENDING_VERIFICATION;
-
-				if($is_started) {
-					if($start_unix && $end_unix) {
-						$test->dts_start = date("Y-m-d H:i:s", $start_unix);
-						$test->dts_end = date("Y-m-d H:i:s", $end_unix);
-					}
-					else if($end_unix) {
-						$test->dts_end = date("Y-m-d H:i:s", $end_unix);
-					}
-				}
-
-				$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();
-				if(!$success) throw new Exception(__("Failed to save test. Please try again later."));
-
-				JSON::success();
-			}
-
-		}
-		catch(FormException $e) {
-			if(HTTP::isAJAX()) {
-				$e->generateJSONError();
-			}
-			else {
-				$e->generateAlerts();
-			}
-		}
-		catch(Exception $e) {
-			if(HTTP::isAJAX()) {
-				JSON::fail($e->getMessage());
-			}
-			else {
-				Core::addAlert("danger", $e->getMessage());
-			}
-		}
-
-		date_default_timezone_set($previous_timezone);
-
-	}
-
-
-	View::includeOnce("header", compact("page_title"));
-	View::include("test_form", compact("test", "location", "project", "template"));
-	View::includeOnce("footer");
-
+if($user->isTester()) {
+	require ROOT_DIR . "/controllers/test_tester_form.php";
 }
-
-// Verify test
-else if(Core::$user->canVerifyTests()) {
-
-	$json = json_decode($template->getJSON());
-	$fields = array_merge($json->beforeTest, [(object) ["type" => "hr"]], $json->duringTest);
-	$values = $test->getValues();
-
-	$names = array_map(function($value) { return $value->name; }, $values);
-
-	$values = array_combine(
-		array_map(function($value) { return $value->name; }, $values),
-		array_map(function($value) { return $value->value; }, $values)
-	);
-
-	$directory = $test->getDirectory();
-
-	$submit = http::value("submit");
-	$tester_message = http::value("tester_message", "trim");
-	if($submit) {
-		try {
-			Core::validateCSRFToken($submit);
-
-			$form_exception = new FormException;
-
-			$accept = http::value("accept");
-			$reject = http::value("reject");
-
-			$accept_tester_invoice = http::value("accept_tester_invoice");
-			$reject_tester_invoice = http::value("reject_tester_invoice");
-
-			if(($accept || $reject) && $test->status != Test::STATUS_PENDING_VERIFICATION) {
-				throw new Exception("This test is no longer pending verification.");
-			}
-
-			if(empty($test->verifier_id)) {
-				$test->verifier_id = Core::$user->id;
-				$test->dts_verified = Util::getDateTime();
-			}
-
-			$test->verifier_notes = http::value("verifier_notes", "trim");
-
-			// Check selected retest project
-			$new_test_project = false;
-			$new_test_project_id = http::value("new_test_project_id", "int");
-			$new_test_is_retest = http::value("new_test_is_retest", "int");
-			if($new_test_project_id) {
-				$new_test_project = Project::get($new_test_project_id);
-				if(!$new_test_project || $new_test_project->customer_id != $customer->id) throw new Exception("The new test project selected is invalid.");
-			}
-
-			// Modify test values
-
-			// Overrides
-			$unix_start = strtotime($test->dts_start . " UTC");
-			$unix_end = strtotime($test->dts_end . " UTC");
-
-			$pass_override = http::value("pass_override");
-			if(strlen($pass_override) > 0) {
-				$test->pass = $pass_override;
-			}
-
-			$start_override = http::getDateTimeFromFields("start_override");
-			if($start_override) {
-				$unix_start = strtotime($start_override);
-			}
-
-			$end_override = http::getDateTimeFromFields("end_override");
-			if($end_override) {
-				$unix_end = strtotime($end_override);
-			}
-
-			if($unix_start > $unix_end) {
-				$form_exception->addError("Start time cannot be after end time.");
-			}
-			else {
-				$test->dts_start = Util::getDateTime($unix_start);
-				$test->dts_end = Util::getDateTime($unix_end);
-			}
-
-			$test->customer_fee = null;
-			$customer_fee = http::value("customer_fee", "float");
-			if($customer_fee !== null && $customer_fee != $project->default_customer_fee) {
-				$test->customer_fee = $customer_fee;
-			}
-
-			$test->test_fee = null;
-			$tester_fee = http::value("tester_fee", "float");
-			if($tester_fee !== null && $tester_fee != $project->default_tester_fee) {
-				$test->test_fee = $tester_fee;
-			}
-
-			// Test forms
-			foreach($fields as $field) {
-				if($field->type == "header") continue;
-				if($field->type == "file") continue;
-				if(empty($field->name)) continue;
-
-				$required_key = $field->requiredKey ?? null;
-				if($required_key && !in_array($required_key, $template_keys)) continue;
-
-				$value = http::value($field->name, "trim");
-
-				if(in_array($field->name, Test::TEST_FIELDS)) {
-					$test->{$field->name} = $value;
-				}
-				else {
-					$test_value = TestValue::get($id, $field->name);
-					if(!$test_value) {
-						$test_value = new TestValue;
-						$test_value->test_id = $id;
-						$test_value->name = $field->name;
-					}
-					$test_value->value = $value;
-					$test_value->commit();
-				}
-			}
-
-			// Accept test as completed
-			if($accept) {
-				$test->status = Test::STATUS_COMPLETED;
-			}
-
-			// Reject test
-			if($reject) {
-				$test->status = Test::STATUS_CANCELLED;
-			}
-
-			if($form_exception->hasErrors()) throw $form_exception;
-
-			$test->retest = http::value("retest", "int");
-
-			$test->dts_updated = Util::getDateTime();
-			$success = $test->commit();
-			if(!$success) throw new Exception("Failed to update the test. Please try again later.");
-
-			if($new_test_project) {
-				$new_test = new Test;
-				$new_test->project_id = $new_test_project->id;
-				$new_test->location_id = $location->id;
-				$new_test->status = Test::STATUS_UNASSIGNED;
-				$new_test->dts_created = Util::getDateTime();
-				if($new_test_is_retest) {
-					$new_test->retest = 1;
-				}
-				$success = $new_test->commit();
-			}
-
-			// If rejected, recreate empty test for the location
-			if($reject) {
-				$new_test = new Test;
-				$new_test->project_id = $test->project_id;
-				$new_test->location_id = $test->location_id;
-				$new_test->status = Test::STATUS_UNASSIGNED;
-				$new_test->dts_created = Util::getDateTime();
-				$success = $new_test->commit();
-				if(!$success) throw new Exception("Failed to create a new test. Please try again later.");
-			}
-
-			if($accept) {
-				$tester->score++;
-				$tester->commit();
-
-				// Save PDF
-				$mpdf = $test->getMPDF();
-				$pdf_string = $mpdf->Output("", "S");
-				$pdf_path = $directory . "/pdf.pdf";
-
-				$success = file_put_contents($pdf_path, $pdf_string);
-
-				$email_customer = http::value("email_customer");
-				$email_location = http::value("email_location");
-				$email_location_area_manager = http::value("email_location_area_manager");
-
-				if($email_customer && $customer->email_after_test && $customer->email) {
-					$test->sendResultEmail($customer->email);
-				}
-
-				if($email_location && $customer->email_locations_after_test && $location->email) {
-					$test->sendResultEmail($location->email);
-				}
-
-				if($email_location_area_manager && $customer->email_locations_after_test && $location->area_manager_email) {
-					$test->sendResultEmail($location->area_manager_email);
-				}
-
-				if(EMAIL_TEST_RESULT) {
-					$test->sendResultEmail(EMAIL_TEST_RESULT);
-				}
-
-				if(EMAIL_TEST_RESULT_COPY) {
-					$test->sendResultEmail(EMAIL_TEST_RESULT_COPY);
-				}
-			}
-
-			if($test->status_tester_invoice == Test::STATUS_TESTER_INVOICE_PENDING) {
-
-				if($accept_tester_invoice) {
-					$success = $test->markTesterInvoicePaid();
-					if(!$success) throw new Exception("Failed to mark tester invoice as paid.");
-				}
-
-				if($reject_tester_invoice) {
-					$success = $test->rejectTesterInvoice();
-					if(!$success) throw new Exception("Failed to reject tester invoice.");
-				}
-
-			}
-
-			Core::addAlert("success", "Test updated successfully.");
-			HTTP::redirect("/account/tests/$id");
-		}
-		catch(FormException $e) {
-			$e->generateAlerts();
-		}
-		catch(Exception $e) {
-			Core::addAlert("danger", $e->getMessage());
-		}
-	}
-
-	$projects = $customer->getProjects();
-
-	/** @var Project[] $future_projects */
-	$future_projects = array_filter($projects, function($p) use ($project) {
-		if($p->id == $project->id) return false;
-		if($p->template_id != $project->template_id) return false;
-		$unix_deadline = Util::getUnixTimeFromUTC($p->dts_deadline);
-		return ($unix_deadline > time());
-	});
-
-	View::includeOnce("header", compact("page_title"));
-	View::include("test_verify_form", compact("test", "tester", "location", "project", "future_projects", "customer", "template", "fields", "values", "tester_message"));
-	View::includeOnce("footer");
-	return;
+else if($user->canVerifyTests()) {
+	require ROOT_DIR . "/controllers/test_verify_form.php";
 }
-
-// View test results
-else if(Core::$user->canAccessTestResult()) {
+else if($user->canAccessTestResult()) {
 	HTTP::redirect("/account/tests/$id/result");
 }
 else {

+ 20 - 49
controllers/test_invoice.php

@@ -1,11 +1,24 @@
-<?php
+<?php /** @noinspection PhpUnhandledExceptionInspection */
+
+/**
+ * @var int $id
+ */
 
 use \Mpdf\Mpdf;
 
 $test = Test::get($id);
-if(!$test) throw new Exception(__("Test not found."));
-if($test->status != Test::STATUS_COMPLETED) throw new Exception(__("An invoice cannot be generated for this test yet."));
-if(Core::$user->id != $test->tester_id && !Core::$user->canAdmin()) throw new Exception(__("You do not have permission to access this resource."));
+if(!$test) {
+	http_response_code(404);
+	throw new Exception(__("Test not found."));
+}
+if($test->status != Test::STATUS_COMPLETED) {
+	http_response_code(403);
+	throw new Exception(__("An invoice cannot be generated for this test yet."));
+}
+if(Core::$user->id != $test->tester_id && !Core::$user->canAdmin()) {
+	http_response_code(403);
+	throw new Exception(__("You do not have permission to access this resource."));
+}
 
 $project = $test->getProject();
 $template = $project->getTemplate();
@@ -16,36 +29,8 @@ $values = $test->getValues(true);
 $location_address = $location->name . ", " . $location->getDisplayAddress(["address_1", "address_2", "city", "postal_code"]);
 
 // Base cost
-$fee = floatval($test->test_fee) > 0 ? $test->test_fee : $project->default_tester_fee;
-$fee = (float) $fee;
-
-$travel_cost = (float) http::value("travel_cost", "float");
-$description = http::value("description", "trim");
-$photo = (object) $_FILES["photo"];
-$has_photo = false;
-
-if($travel_cost > 0) {
-	if(!$description) throw new Exception(__("Description cannot be empty."));
-
-	switch($photo->error) {
-		case UPLOAD_ERR_OK:
-			$is_jpeg = Image::isJPEG($photo->tmp_name);
-			if(!$is_jpeg) throw new Exception(__("The file uploaded was not a JPEG. Please try again."));
-
-			$has_photo = true;
-			break;
-		case UPLOAD_ERR_NO_FILE:
-			throw new Exception(__("No file was uploaded. Please try again."));
-			break;
-		default:
-			// Upload error
-			throw new Exception(__("An upload error has occurred. Please try again."));
-			break;
-	}
-}
-
-$test->test_travel_cost = $travel_cost;
-$test->test_travel_cost_description = $description;
+$fee = $test->getTestFee();
+$travel_cost = $test->getTravelCosts();
 
 $invoice_total = $fee + $travel_cost;
 
@@ -102,7 +87,7 @@ $mpdf = new Mpdf();
 $mpdf->SetSubject("Test Invoice");
 $mpdf->SetCreator(APP_NAME);
 $mpdf->SetAuthor(APP_NAME);
-$mpdf->SetTitle("Invoice ({$reference})");
+$mpdf->SetTitle("Invoice ($reference)");
 
 $mpdf->useSubstitutions = true;
 
@@ -128,7 +113,6 @@ ob_start();
 	<body>
 		<div>
 			<div style="float: left; width: 49.5%; font-size: 0.875rem;">
-
 				<div style="float: left; width: 49.5%;">
 					<strong><?=htmlspecialchars($tester->getDisplayName())?></strong><br />
 					<?=nl2br(htmlspecialchars(implode("\n", $address_parts)))?><br />
@@ -150,10 +134,6 @@ ob_start();
 				<div style="float: right; width: 49.5%;">
 					Tel: <?=htmlspecialchars(PHONE)?>
 				</div>
-
-
-
-
 			</div>
 			<div style="float: right; width: 49.5%; text-align: right;">
 				<div class="title">
@@ -240,7 +220,6 @@ ob_start();
 
 			<?=htmlspecialchars($tester->getDisplayName())?><br />
 
-
 			<?php
 			switch($tester->preferred_payment_method) {
 				case User::PAYMENT_METHOD_BANK_TRANSFER:
@@ -260,8 +239,6 @@ ob_start();
 					break;
 			}
 			?>
-
-
 		</div>
 	</body>
 </html>
@@ -280,11 +257,5 @@ $test->status_tester_invoice = Test::STATUS_TESTER_INVOICE_PENDING;
 $test->dts_tester_invoice_generated = Util::getDateTime();
 $test->commit();
 
-// Move photo to folder
-if($has_photo) {
-	$dst = $test->getTravelCostsPhotoPath();
-	move_uploaded_file($photo->tmp_name, $dst);
-}
-
 // Output to browser
 $mpdf->Output($download_filename, "D");

+ 224 - 0
controllers/test_tester_form.php

@@ -0,0 +1,224 @@
+<?php /** @noinspection PhpUnhandledExceptionInspection */
+
+/**
+ * @var int $id
+ * @var Test $test
+ * @var string $page_title
+ * @var Location $location
+ * @var Project $project
+ * @var Template $template
+ * @var string[] $template_keys
+ */
+
+$is_confirmed = $test->status == Test::STATUS_CONFIRMED;
+$is_started = $test->status == Test::STATUS_STARTED;
+$is_unverified = $test->status == Test::STATUS_PENDING_VERIFICATION;
+
+Core::$show_footer_content = false;
+
+if(Core::$user->id != $test->tester_id) throw new Exception(__("You do not have permission to view this page."));
+if($test->status == Test::STATUS_ASSIGNED) throw new Exception(__("You do not have permission to view this page as you have not accepted the test yet."));
+
+// Show completed message
+if($test->status > Test::STATUS_PENDING_VERIFICATION) {
+	View::includeOnce("header", compact("page_title"));
+	View::include("test_form", compact("test", "location", "project", "template"));
+	View::includeOnce("footer");
+	return;
+}
+
+$json = json_decode($template->getJSON());
+
+$submit = http::value("submit");
+if($submit) {
+
+	$previous_timezone = date_default_timezone_get();
+
+	try {
+		Core::validateCSRFToken($submit);
+
+		$form_exception = new FormException;
+
+		if($is_confirmed) {
+			// Parse before the test form
+			$fields = $json->beforeTest;
+
+		}
+
+		if($is_started || $is_unverified) {
+			// Parse after the test form
+			$fields = $json->duringTest;
+
+			// Start/End times
+			if($is_started) {
+				$start_override = http::getDateTimeFromFields("start_override");
+				$end_override = http::getDateTimeFromFields("end_override");
+
+				$start_unix = null;
+				$end_unix = null;
+
+				if($start_override && $end_override) {
+					$start_unix = strtotime($start_override);
+					$end_unix = strtotime($end_override);
+
+					if($start_unix > $end_unix) $form_exception->addError(__("Entry Time must not be after Exit Time."));
+					if(!$start_unix && $end_unix && $test->dts_start) {
+						$recorded_start_unix = Util::getUnixTimeFromUTC($test->dts_start);
+						if($end_unix < $recorded_start_unix) $form_exception->addError(__("Exit Time cannot be later than the recorded Entry Time."));
+					}
+				}
+				else {
+					$form_exception->addError(__("Entry Time and Exit Time must be filled in."));
+				}
+
+			}
+
+		}
+
+		if(empty($fields)) throw new LogicException(__("No fields can be shown."));
+
+		foreach($fields as $field) {
+
+			$name = $field->name ?? false;
+			if(empty($name)) continue; // Not a field
+
+			$required_key = $field->requiredKey ?? null;
+			if($required_key && !in_array($required_key, $template_keys)) continue;
+
+			$label = $field->label ?? "";
+			$type = $field->type;
+			$required = $field->required ?? false;
+			$values = $field->values ?? [];
+
+			if($type == "file") {
+				$file = (object) $_FILES[$name];
+
+				try {
+					if(!$required && $file->error == UPLOAD_ERR_NO_FILE) continue;
+					if($required && $file->error == UPLOAD_ERR_NO_FILE) {
+						throw new Exception("$label is required.");
+					}
+
+					// Detect upload error
+					if($file->error != UPLOAD_ERR_OK) throw new Exception(HTTP::getUploadErrorString($file->error));
+
+					// Get image details
+					$size = @getimagesize($file->tmp_name);
+					if(!$size) throw new Exception(sprintf(__("The uploaded file for %s is not an image."), $label));
+					[$width, $height, $type] = $size;
+					if($type != IMAGETYPE_JPEG) throw new Exception(sprintf(__("The uploaded file for %s is not a JPEG."), $label));
+
+					// Resize image
+					$output_image = Image::normalise($file->tmp_name);
+
+					// Write image to disk
+					$output_path = $test->getDirectory() . "/" . $name . ".jpg";
+
+					imagejpeg($output_image, $output_path, 60);
+					imagedestroy($output_image);
+				}
+				catch(Exception $e) {
+					$form_exception->addError($e->getMessage());
+				}
+			}
+			else {
+				$value = http::value($name, "trim");
+
+				if($required && $value === null) $form_exception->addError(sprintf(__("%s is required."), $label));
+				if($values && !in_array($value, $values)) $form_exception->addError(sprintf(__("Value for %s is invalid."), $label));
+
+				if(in_array($name, Test::TEST_FIELDS)) {
+					$test->$name = $value;
+				}
+				else {
+					$test_value = TestValue::get($test->id, $name);
+					if(!$test_value) {
+						$test_value = new TestValue;
+						$test_value->test_id = $test->id;
+						$test_value->name = $name;
+					}
+					$test_value->value = $value;
+					$success = $test_value->commit();
+					if(!$success) $form_exception->addError(sprintf(__("Failed to save value for %s."), $label));
+				}
+			}
+
+		}
+
+		if($form_exception->hasErrors()) throw $form_exception;
+
+		date_default_timezone_set("UTC");
+
+		// Before the Test
+		if($is_confirmed) {
+			$test->status = Test::STATUS_STARTED;
+			$test->dts_start = Util::getDateTime();
+			$test->dts_updated = Util::getDateTime();
+			$success = $test->commit();
+			if(!$success) throw new Exception(__("Failed to save test. Please try again later."));
+
+			Core::addAlert("success", __("Photos uploaded successfully."));
+
+			HTTP::redirect("/account/tests/$id");
+
+		}
+
+		// During the test
+		if($is_started || $is_unverified) {
+			$test->status = Test::STATUS_PENDING_VERIFICATION;
+
+			if($is_started) {
+
+				/**
+				 * @var int $start_unix
+				 * @var int $end_unix
+				 */
+
+				if($start_unix && $end_unix) {
+					$test->dts_start = date("Y-m-d H:i:s", $start_unix);
+					$test->dts_end = date("Y-m-d H:i:s", $end_unix);
+				}
+				else if($end_unix) {
+					$test->dts_end = date("Y-m-d H:i:s", $end_unix);
+				}
+			}
+
+			$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();
+			if(!$success) throw new Exception(__("Failed to save test. Please try again later."));
+
+			JSON::success();
+		}
+
+	}
+	catch(FormException $e) {
+		if(HTTP::isAJAX()) {
+			$e->generateJSONError();
+		}
+		else {
+			$e->generateAlerts();
+		}
+	}
+	catch(Exception $e) {
+		if(HTTP::isAJAX()) {
+			JSON::fail($e->getMessage());
+		}
+		else {
+			Core::addAlert("danger", $e->getMessage());
+		}
+	}
+
+	date_default_timezone_set($previous_timezone);
+
+}
+
+
+View::includeOnce("header", compact("page_title"));
+View::include("test_form", compact("test", "location", "project", "template"));
+View::includeOnce("footer");

+ 246 - 0
controllers/test_verify_form.php

@@ -0,0 +1,246 @@
+<?php /** @noinspection PhpUnhandledExceptionInspection */
+
+/**
+ * @var int $id
+ * @var Test $test
+ * @var string $page_title
+ * @var Location $location
+ * @var Project $project
+ * @var Template $template
+ * @var string[] $template_keys
+ */
+
+$customer = $project->getCustomer();
+$tester = $test->getTester();
+
+$json = json_decode($template->getJSON());
+$fields = array_merge($json->beforeTest, [(object) ["type" => "hr"]], $json->duringTest);
+$values = $test->getValues();
+
+$names = array_map(function($value) { return $value->name; }, $values);
+
+$values = array_combine(
+	array_map(function($value) { return $value->name; }, $values),
+	array_map(function($value) { return $value->value; }, $values)
+);
+
+$directory = $test->getDirectory();
+
+$submit = http::value("submit");
+$tester_message = http::value("tester_message", "trim");
+if($submit) {
+	try {
+		Core::validateCSRFToken($submit);
+
+		$form_exception = new FormException;
+
+		$accept = http::value("accept");
+		$reject = http::value("reject");
+
+		$accept_tester_invoice = http::value("accept_tester_invoice");
+		$reject_tester_invoice = http::value("reject_tester_invoice");
+
+		if(($accept || $reject) && $test->status != Test::STATUS_PENDING_VERIFICATION) {
+			throw new Exception("This test is no longer pending verification.");
+		}
+
+		if(empty($test->verifier_id)) {
+			$test->verifier_id = Core::$user->id;
+			$test->dts_verified = Util::getDateTime();
+		}
+
+		$test->verifier_notes = http::value("verifier_notes", "trim");
+
+		// Check selected retest project
+		$new_test_project = false;
+		$new_test_project_id = http::value("new_test_project_id", "int");
+		$new_test_is_retest = http::value("new_test_is_retest", "int");
+		if($new_test_project_id) {
+			$new_test_project = Project::get($new_test_project_id);
+			if(!$new_test_project || $new_test_project->customer_id != $customer->id) throw new Exception("The new test project selected is invalid.");
+		}
+
+		// Modify test values
+
+		// Overrides
+		$unix_start = strtotime($test->dts_start . " UTC");
+		$unix_end = strtotime($test->dts_end . " UTC");
+
+		$pass_override = http::value("pass_override");
+		if(strlen($pass_override) > 0) {
+			$test->pass = $pass_override;
+		}
+
+		$start_override = http::getDateTimeFromFields("start_override");
+		if($start_override) {
+			$unix_start = strtotime($start_override);
+		}
+
+		$end_override = http::getDateTimeFromFields("end_override");
+		if($end_override) {
+			$unix_end = strtotime($end_override);
+		}
+
+		if($unix_start > $unix_end) {
+			$form_exception->addError("Start time cannot be after end time.");
+		}
+		else {
+			$test->dts_start = Util::getDateTime($unix_start);
+			$test->dts_end = Util::getDateTime($unix_end);
+		}
+
+		$test->customer_fee = null;
+		$customer_fee = http::value("customer_fee", "float");
+		if($customer_fee !== null && $customer_fee != $project->default_customer_fee) {
+			$test->customer_fee = $customer_fee;
+		}
+
+		$test->test_fee = null;
+		$tester_fee = http::value("tester_fee", "float");
+		if($tester_fee !== null && $tester_fee != $project->default_tester_fee) {
+			$test->test_fee = $tester_fee;
+		}
+
+		$test->test_travel_cost = HTTP::value("travel_cost", "float");
+		if($test->test_travel_cost < 0 || $test->test_travel_cost > 999.99) $form_exception->addError("Travel costs must be between 0 and 999.99.");
+
+		// Test forms
+		foreach($fields as $field) {
+			if($field->type == "header") continue;
+			if($field->type == "file") continue;
+			if(empty($field->name)) continue;
+
+			$required_key = $field->requiredKey ?? null;
+			if($required_key && !in_array($required_key, $template_keys)) continue;
+
+			$value = http::value($field->name, "trim");
+
+			if(in_array($field->name, Test::TEST_FIELDS)) {
+				$test->{$field->name} = $value;
+			}
+			else {
+				$test_value = TestValue::get($id, $field->name);
+				if(!$test_value) {
+					$test_value = new TestValue;
+					$test_value->test_id = $id;
+					$test_value->name = $field->name;
+				}
+				$test_value->value = $value;
+				$test_value->commit();
+			}
+		}
+
+		// Accept test as completed
+		if($accept) {
+			$test->status = Test::STATUS_COMPLETED;
+		}
+
+		// Reject test
+		if($reject) {
+			$test->status = Test::STATUS_CANCELLED;
+		}
+
+		if($form_exception->hasErrors()) throw $form_exception;
+
+		$test->retest = http::value("retest", "int");
+
+		$test->dts_updated = Util::getDateTime();
+		$success = $test->commit();
+		if(!$success) throw new Exception("Failed to update the test. Please try again later.");
+
+		if($new_test_project) {
+			$new_test = new Test;
+			$new_test->project_id = $new_test_project->id;
+			$new_test->location_id = $location->id;
+			$new_test->status = Test::STATUS_UNASSIGNED;
+			$new_test->dts_created = Util::getDateTime();
+			if($new_test_is_retest) {
+				$new_test->retest = 1;
+			}
+			$success = $new_test->commit();
+		}
+
+		// If rejected, recreate empty test for the location
+		if($reject) {
+			$new_test = new Test;
+			$new_test->project_id = $test->project_id;
+			$new_test->location_id = $test->location_id;
+			$new_test->status = Test::STATUS_UNASSIGNED;
+			$new_test->dts_created = Util::getDateTime();
+			$success = $new_test->commit();
+			if(!$success) throw new Exception("Failed to create a new test. Please try again later.");
+		}
+
+		if($accept) {
+			$tester->score++;
+			$tester->commit();
+
+			// Save PDF
+			$mpdf = $test->getMPDF();
+			$pdf_string = $mpdf->Output("", "S");
+			$pdf_path = $directory . "/pdf.pdf";
+
+			$success = file_put_contents($pdf_path, $pdf_string);
+
+			$email_customer = http::value("email_customer");
+			$email_location = http::value("email_location");
+			$email_location_area_manager = http::value("email_location_area_manager");
+
+			if($email_customer && $customer->email_after_test && $customer->email) {
+				$test->sendResultEmail($customer->email);
+			}
+
+			if($email_location && $customer->email_locations_after_test && $location->email) {
+				$test->sendResultEmail($location->email);
+			}
+
+			if($email_location_area_manager && $customer->email_locations_after_test && $location->area_manager_email) {
+				$test->sendResultEmail($location->area_manager_email);
+			}
+
+			if(EMAIL_TEST_RESULT) {
+				$test->sendResultEmail(EMAIL_TEST_RESULT);
+			}
+
+			if(EMAIL_TEST_RESULT_COPY) {
+				$test->sendResultEmail(EMAIL_TEST_RESULT_COPY);
+			}
+		}
+
+		if($test->status_tester_invoice == Test::STATUS_TESTER_INVOICE_PENDING) {
+
+			if($accept_tester_invoice) {
+				$success = $test->markTesterInvoicePaid();
+				if(!$success) throw new Exception("Failed to mark tester invoice as paid.");
+			}
+
+			if($reject_tester_invoice) {
+				$success = $test->rejectTesterInvoice();
+				if(!$success) throw new Exception("Failed to reject tester invoice.");
+			}
+
+		}
+
+		Core::addAlert("success", "Test updated successfully.");
+		HTTP::redirect("/account/tests/$id");
+	}
+	catch(FormException $e) {
+		$e->generateAlerts();
+	}
+	catch(Exception $e) {
+		Core::addAlert("danger", $e->getMessage());
+	}
+}
+
+$projects = $customer->getProjects();
+
+$future_projects = array_filter($projects, function($p) use ($project) {
+	if($p->id == $project->id) return false;
+	if($p->template_id != $project->template_id) return false;
+	$unix_deadline = Util::getUnixTimeFromUTC($p->dts_deadline);
+	return ($unix_deadline > time());
+});
+
+View::includeOnce("header", compact("page_title"));
+View::include("test_verify_form", compact("test", "tester", "location", "project", "future_projects", "customer", "template", "fields", "values", "tester_message"));
+View::includeOnce("footer");

+ 1 - 2
controllers/tests_completed.php

@@ -1,4 +1,4 @@
-<?php
+<?php /** @noinspection PhpUnhandledExceptionInspection */
 
 Core::addScript("public/js/app-completed-tests.js");
 
@@ -20,6 +20,5 @@ $can_invoice = Core::$user->getInvoiceAddress() && Core::$user->hasValidPaymentM
 
 View::includeOnce("header", compact("page_title"));
 View::include("test_list_completed", compact("tests", "can_invoice", "pagination_object"));
-View::include("modal_test_invoice");
 View::includeOnce("modal_page_jump");
 View::includeOnce("footer");

+ 6 - 1
controllers/tests_tester_list.php

@@ -1,4 +1,9 @@
-<?php
+<?php /** @noinspection PhpUnhandledExceptionInspection */
+
+/**
+ * @var User $user
+ * @var string $page_title
+ */
 
 Core::addScript("public/js/app-tests-tester-list.js");
 

+ 15 - 6
engine/core.php

@@ -6,7 +6,7 @@ class Core {
 	/**
 	 * @var User $user
 	 */
-	public static $user = null;
+	public static $user;
 	public static $admin = false;
 
 	public static $controller = "404";
@@ -30,7 +30,10 @@ class Core {
 		"public/css/daterangepicker.css",
 	];
 
-	public static function locales() {
+	/**
+	 * @return string[]
+	 */
+	public static function locales(): array {
 		return [
 			"nl_NL" => "Dutch (Netherlands)",
 			"en_GB" => "English (United Kingdom)",
@@ -59,11 +62,17 @@ class Core {
 		Core::$stylesheets[] = $path; // Path is relative to root directory
 	}
 
-	public static function getScripts() {
+	/**
+	 * @return string[]
+	 */
+	public static function getScripts(): array {
 		return Core::$scripts;
 	}
 
-	public static function getStylesheets() {
+	/**
+	 * @return string[]
+	 */
+	public static function getStylesheets(): array {
 		return Core::$stylesheets;
 	}
 
@@ -109,7 +118,7 @@ class Core {
 		}
 	}
 
-	public static function isLoggedIn() {
+	public static function isLoggedIn(): bool {
 		return !empty($_SESSION["user_id"]);
 	}
 
@@ -118,7 +127,7 @@ class Core {
 	 * @return bool
 	 * @throws Exception
 	 */
-	public static function validateCSRFToken(string $token) {
+	public static function validateCSRFToken(string $token): bool {
 		if($_SESSION["csrf_token"] !== $token) throw new Exception("CSRF attempt blocked.");
 		return true;
 	}

+ 3 - 0
engine/project.php

@@ -506,6 +506,9 @@ class Project extends Model {
 		$this->template_keys = json_encode($keys);
 	}
 
+	/**
+	 * @return string[]
+	 */
 	public function getTemplateKeys(): array {
 		$keys = json_decode($this->template_keys);
 		return $keys ?: [];

+ 35 - 0
engine/test.php

@@ -739,4 +739,39 @@ class Test extends Model {
 		"/U" . str_pad($tester->id, 3, "0", STR_PAD_LEFT);
 	}
 
+	/**
+	 * @return float
+	 * @throws Exception
+	 */
+	public function getTestFee(): float {
+		return $this->test_fee !== null ? (float) $this->test_fee : (float) $this->getProject()->default_tester_fee;
+	}
+
+	public function getTravelCosts(): float {
+		return (float) $this->test_travel_cost;
+	}
+
+	/**
+	 * @return float
+	 * @throws Exception
+	 */
+	public function getInvoiceTotal(): float {
+		$template = $this->getProject()->getTemplate();
+		$values = $this->getValues(true);
+
+		// Base cost
+		$fee = $this->getTestFee();
+		$travel_cost = $this->getTravelCosts();
+
+		$invoice_total = $fee + $travel_cost;
+
+		// Additional tester invoice fields
+		$tester_invoice_fields = $template->getTesterInvoiceFields();
+		foreach($tester_invoice_fields as $field) {
+			$invoice_total += (float) $values[$field->name] ?? 0;
+		}
+
+		return $invoice_total;
+	}
+
 }

+ 21 - 10
views/test_list_completed.php

@@ -1,3 +1,11 @@
+<?php /** @noinspection PhpUnhandledExceptionInspection */
+
+/**
+ * @var object $pagination_object
+ * @var bool $can_invoice
+ */
+
+?>
 <div class="container mt-3 py-4">
 
 	<h2><?=htmlspecialchars(__("Completed Tests"))?></h2>
@@ -58,12 +66,13 @@
 				$attire = $test->attire;
 
 				$attire_class = $date_start_class = $time_start_class = "";
-			}
-			if($test->dts_start && $test->dts_end) {
-				$end_dt = new DateTime($test->dts_end);
-				$diff = $start_dt->diff($end_dt, true);
-				$duration = $diff->format(__("%i min. %S sec."));
-				$duration_class = "";
+
+				if($test->dts_end) {
+					$end_dt = new DateTime($test->dts_end);
+					$diff = $start_dt->diff($end_dt, true);
+					$duration = $diff->format(__("%i min. %S sec."));
+					$duration_class = "";
+				}
 			}
 
 			date_default_timezone_set($original_timezone);
@@ -74,15 +83,16 @@
 			$status_class = "secondary";
 			$status_text = __("Pending");
 
+			$fee = "N/A";
+
 			if($test->status == Test::STATUS_CANCELLED) {
 				$status_class = "danger";
 				$status_text = __("Rejected");
-				$fee = "N/A";
 			}
 			if($test->status == Test::STATUS_COMPLETED) {
 				$status_class = "success";
 				$status_text = __("Accepted");
-				$fee = $test->fee ? $test->fee : $project->default_tester_fee;
+				$fee = $test->getTestFee();
 				$fee = "£" . $fee;
 				$fee_class = "";
 			}
@@ -97,8 +107,9 @@
 									<?php
 									if($test->status == Test::STATUS_COMPLETED && $can_invoice) {
 										?>
-										<a href="#" data-toggle="modal" data-target="#modal-test-invoice" data-invoice data-id="<?=$test->id?>">
-											<i class="fal fa-fw fa-external-link"></i> <?=htmlspecialchars(__("Invoice"))?>
+										<a href="/account/tests/<?=$test->id?>/invoice">
+											<i class="fal fa-fw fa-external-link"></i>
+											<?=htmlspecialchars(__("Invoice"))?>
 										</a>
 										<?php
 									}

+ 12 - 0
views/test_verify_form.php

@@ -379,6 +379,18 @@ function render_card_list_group($details) {
 								</div>
 							</div>
 						</div>
+						<row class="row mb-1">
+							<label class="col-sm-4 col-form-label" for="travel-cost">Travel Costs</label>
+							<div class="col-sm">
+								<div class="input-group">
+									<div class="input-group-prepend">
+										<span class="input-group-text">£</span>
+									</div>
+									<input class="form-control" type="number" step="0.01" min="0" max="999.99" name="travel_cost" id="travel-cost" placeholder="Enter travel costs" value="<?=htmlspecialchars($test->test_travel_cost)?>" required />
+								</div>
+							</div>
+						</row>
+						
 						<div class="row mb-1">
 							<label class="col-sm-4 col-form-label" for="verifier-notes">Verifier Notes</label>
 							<div class="col-sm">